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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
347cb22183427c8826fbed5ffec600b811006a5a | C++ | winterlich/pandora | /src/prg/path.cpp | UTF-8 | 9,948 | 2.796875 | 3 | [
"MIT"
] | permissive | #include <cassert>
#include <localPRG.h>
#include "prg/path.h"
#define assert_msg(x) !(std::cerr << "Assertion failed: " << x << std::endl)
uint32_t prg::Path::get_start() const {
if (path.size() < 1)
return 0;
return path.front().start;
}
uint32_t prg::Path::get_end() const {
if (path.size() < 1)
return 0;
return path.back().start + (uint32_t) path.back().length;
}
uint32_t prg::Path::length() const {
uint32_t length = 0;
for (const auto &interval: path)
length += interval.length;
return length;
}
void prg::Path::add_end_interval(const Interval &i) {
memoizedDirty = true;
assert (i.start >= get_end() || assert_msg(
"tried to add interval starting at " << i.start << " to end of path finishing at " << get_end()));
path.push_back(i);
}
std::vector<LocalNodePtr> prg::Path::nodes_along_path(const LocalPRG &localPrg) {
//sanity check
assert ((isMemoized == false || (isMemoized == true && localPRGIdOfMemoizedLocalNodePath == localPrg.id)) ||
assert_msg(
"Memoization bug: memoized a local node path for PRG with id"
<< localPRGIdOfMemoizedLocalNodePath
<<
" but PRG id " << localPrg.id
<< " is also trying to use this memoized path"));
if (isMemoized == false || memoizedDirty == true) { //checks if we must do memoization
//yes
//not memoized, memoize
memoizedLocalNodePath = localPrg.nodes_along_path_core(*this);
//update the memoization control variables
localPRGIdOfMemoizedLocalNodePath = localPrg.id;
isMemoized = true;
memoizedDirty = false;
//return the local node path
return memoizedLocalNodePath;
} else if (memoizedDirty == false) {
//redudant call, return the memoized local node path
return memoizedLocalNodePath;
}
}
prg::Path prg::Path::subpath(const uint32_t start, const uint32_t len) const {
//function now returns the path starting at position start along the path, rather than at position start on
//linear PRG, and for length len
//cout << "find subpath of " << *this << " from " << start << " for length " << len << endl;
assert(start + len <= length());
prg::Path p;
std::deque<Interval> d;
uint32_t covered_length = 0;
uint32_t added_len = 0;
for (const auto &interval: path) {
if ((covered_length <= start and covered_length + interval.length > start and p.path.empty()) or
(covered_length == start and interval.length == 0 and p.path.empty())) {
assert(added_len == 0);
d = {Interval(interval.start + start - covered_length,
std::min(interval.get_end(), interval.start + start - covered_length + len - added_len))};
p.initialize(d);
added_len += std::min(len - added_len, interval.length - start + covered_length);
///cout << "added first interval " << p.path.back() << " and added length is now " << added_len << endl;
} else if (covered_length >= start and added_len <= len) {
p.add_end_interval(
Interval(interval.start, std::min(interval.get_end(), interval.start + len - added_len)));
added_len += std::min(len - added_len, interval.length);
//cout << "added interval " << p.path.back() << " and added length is now " << added_len << endl;
}
covered_length += interval.length;
//cout << "covered length is now " << covered_length << endl;
if (added_len >= len) {
break;
}
}
assert(added_len == len);
return p;
}
bool prg::Path::is_branching(const prg::Path &y) const // returns true if the two paths branch together or coalesce apart
{
// simple case, one ends before the other starts -> return false
if (get_end() < y.get_start() or y.get_end() < get_start()) {
return false;
}
// otherwise, check it out
bool overlap = false;
std::vector<Interval>::const_iterator it, it2;
for (it = path.begin(); it != path.end(); ++it) {
if (overlap) {
if (it->start != it2->start) {
// had paths which overlapped and now don't
//cout << "branch" << endl;
return true; // represent branching paths at this point
}
++it2;
if (it2 == y.path.end()) {
return false;
break;
}
} else {
for (it2 = y.path.begin(); it2 != y.path.end(); ++it2) {
//cout << *it << " " << *it2 << endl;
if ((it->get_end() > it2->start and it->start < it2->get_end()) or (*it == *it2)) {
// then the paths overlap
overlap = true;
//cout << "overlap" << endl;
// first query the previous intervals if they exist, to see if they overlap
if (it != path.begin() && it2 != y.path.begin() && (--it)->get_end() != (--it2)->get_end()) {
//cout << "coal" << endl;
return true; // represent coalescent paths at this point
} else {
++it2;
if (it2 == y.path.end()) {
return false;
}
break; // we will step through intervals from here comparing to path
}
}
}
}
}
return false;
}
bool prg::Path::is_subpath(const prg::Path &big_path) const {
if (big_path.length() < length()
or big_path.get_start() > get_start()
or big_path.get_end() < get_end()
or is_branching(big_path)) {
//cout << "fell at first hurdle " << (big_path.length() < length());
//cout << (big_path.start > start) << (big_path.end < end);
//cout << (is_branching(big_path)) << endl;
return false;
}
uint32_t offset = 0;
for (const auto &big_i : big_path.path) {
if (big_i.get_end() >= get_start()) {
offset += get_start() - big_i.start;
if (offset + length() > big_path.length()) {
return false;
} else if (big_path.subpath(offset, length()) == *this) {
return true;
}
break;
}
offset += big_i.length;
}
return false;
}
bool prg::Path::operator<(const prg::Path &y) const {
auto it2 = y.path.begin();
auto it = path.begin();
while (it != path.end() and it2 != y.path.end()) {
if (!(*it == *it2)) //for the first interval which is not the same in both paths
{
return (*it < *it2); // return interval comparison
}
it++;
it2++;
}
if (it == path.end() and it2 != y.path.end()) {
// if path is shorter than comparison path, but equal otherwise, return that it is smaller
return true;
}
return false; // shouldn't ever call this
}
bool prg::Path::operator==(const prg::Path &y) const {
if (path.size() != y.path.size()) { return false; }
auto it2 = y.path.begin();
for (auto it = path.begin(); it != path.end();) {
if (!(*it == *it2)) { return false; }
it++;
it2++;
}
return true;
}
// tests if the paths are equal except for null nodes at the start or
// ends of the paths
bool equal_except_null_nodes(const prg::Path &x, const prg::Path &y) {
auto it2 = y.begin();
for (auto it = x.begin(); it != x.end();) {
while (it != x.end() and it->length == 0) {
it++;
}
while (it2 != y.end() and it2->length == 0) {
it2++;
}
if (it == x.end() and it2 == y.end()) {
break;
} else if (it == x.end() or it2 == y.end()) {
return false;
}
if (it->length > 0 and it2->length > 0 and !(*it == *it2)) {
return false;
} else {
it++;
it2++;
}
}
return true;
}
bool prg::Path::operator!=(const prg::Path &y) const {
return (!(path == y.path));
}
std::ostream &prg::operator<<(std::ostream &out, const prg::Path &p) {
uint32_t num_intervals = p.path.size();
out << num_intervals << "{";
for (auto it = p.path.begin(); it != p.path.end(); ++it) {
out << *it;
}
out << "}";
return out;
}
std::istream &prg::operator>>(std::istream &in, prg::Path &p) {
uint32_t num_intervals;
in >> num_intervals;
std::deque<Interval> d(num_intervals, Interval());
in.ignore(1, '{');
for (uint32_t i = 0; i != num_intervals; ++i) {
in >> d[i];
}
in.ignore(1, '{');
p.initialize(d);
return in;
}
prg::Path prg::get_union(const prg::Path &x, const prg::Path &y) {
auto xit = x.path.begin();
auto yit = y.path.begin();
prg::Path p;
assert (x < y);
if (x.get_end() < y.get_start() or x.is_branching(y)) {
return p;
} else if (x.path.empty()) {
return y;
}
while (xit != x.path.end() and yit != y.path.end() and xit->get_end() < yit->start) {
if (p.path.empty()) {
p.initialize(*xit);
} else {
p.add_end_interval(*xit);
}
xit++;
}
if (xit != x.path.end() and yit != y.path.end() and xit->start <= yit->get_end()) {
// then we have overlap
if (p.path.empty()) {
p.initialize(Interval(xit->start, std::max(yit->get_end(), xit->get_end())));
} else {
p.add_end_interval(Interval(xit->start, std::max(yit->get_end(), xit->get_end())));
}
while (yit != --y.path.end()) {
yit++;
p.add_end_interval(*yit);
}
}
return p;
} | true |
93d29da8fe0b0ac155050b78283ff401557fbf8c | C++ | osumaru/Game | /osumaruEngine/Physics/RigidBodyDraw.h | SHIFT_JIS | 1,361 | 2.65625 | 3 | [] | no_license | #pragma once
#pragma once
#include "../Graphics/Primitive.h"
#include "../Graphics/Shader.h"
#include "IRigidBodyDraw.h"
struct SRigidBodyVSLayout
{
CVector4 pos;
CVector3 color;
};
//̂\NX
class CRigidBodyDraw : public IRigidBodyDraw
{
public:
//RXgN^
CRigidBodyDraw();
//fXgN^
~CRigidBodyDraw() override;
//
void Init();
/*
_lj
from 1ڂ̒_
to 2ڂ̒_
color v~eBu̐F
*/
void drawLine(const btVector3 &from, const btVector3 &to, const btVector3& color)override;
/*
`
viewMatrix J̃r[s
projectionMatrix J̎ˉes
*/
void Draw(CMatrix viewMatrix, CMatrix projectionMatrix)override;
//JEgZbg
void Reset() override
{
ZeroMemory(m_vertexBuffer, sizeof(m_vertexBuffer));
ZeroMemory(m_indexBuffer, sizeof(m_indexBuffer));
//t[CfbNXobt@ƒ_obt@Zbg
m_count = 0;
}
private:
static const int VERTEX_NUM = 100000;
SRigidBodyVSLayout m_vertexBuffer[VERTEX_NUM];
DWORD m_indexBuffer[VERTEX_NUM];
CPrimitive m_primitive; //v~eBu
int m_count; //v~eBu̐
CShader m_vs; //GtFNg
CShader m_ps;
CConstantBuffer m_cb;
}; | true |
aef0742bd45c5e71f0a6c4765eeab09bda58c1cd | C++ | knuu/competitive-programming | /aoj/12/aoj1275_2.cpp | UTF-8 | 367 | 2.515625 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
int f(int n, int k) { return n == 1 ? 0 : (f(n-1, k) + k) % n; }
int main() {
// use scanf in CodeForces!
cin.tie(0);
ios_base::sync_with_stdio(false);
while (1) {
int N, K, M; cin >> N >> K >> M;
if (N == 0 and K == 0 and M == 0) break;
cout << (f(N-1, K) + M) % N + 1 << endl;
}
return 0;
}
| true |
250b1379c7cccd22d862b6b5255f810bdd661249 | C++ | f2006116/fuchsia | /src/developer/debug/zxdb/symbols/variant.h | UTF-8 | 2,786 | 2.609375 | 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.
#ifndef SRC_DEVELOPER_DEBUG_ZXDB_SYMBOLS_VARIANT_H_
#define SRC_DEVELOPER_DEBUG_ZXDB_SYMBOLS_VARIANT_H_
#include <optional>
#include <vector>
#include "src/developer/debug/zxdb/symbols/symbol.h"
namespace zxdb {
// A variant is one possible value of a "variant part".
//
// Each Variant contains a discriminant value which is a selector for this in
// the containing VariantPart, and the set of data inside it.
//
// See VariantPart for a full description.
class Variant final : public Symbol {
public:
// Construct with fxl::MakeRefCounted().
// Symbol overrides.
const Variant* AsVariant() const override { return this; }
// The disciminant value associated with this variant. See VariantPart.
//
// The discriminant value may be unset which indicates that this variant is
// the default one.
//
// DWARF discriminant values can be either signed or unsigned, according to
// the type associated with the discriminant data member in the VariantPart.
// This makes it complicated do handle because the full type of the
// VariantPart needs to be understood just to properly parse the Variant out
// of the file.
//
// Since our only current use of these is Rust which always uses unsigned
// disciminants, we also assume unsigned here.
//
// If in the future we need to support signed disciminants, we could
// sign-extend the values during decode so that internally we always deal
// with unsigned types.
const std::optional<uint64_t>& discr_value() const { return discr_value_; }
// Data members. These should be DataMember objects. The offsets of the data
// members will be from the structure containing the VariantPart.
//
// As of this writing, Rust (our only use-case for this) generates variants
// with exactly one data member. If Rust has:
//
// enum MyEnum {
// Foo,
// Bar(i32),
// }
//
// DWARF will define two structure types "MyEnum::Foo" (with no members) and
// "MyEnum::Bar" (with one member) and each variant's data members will
// contain a DataMember of that type. The "name" of these data members will
// match the type ("Foo" and "Bar" in this example).
const std::vector<LazySymbol>& data_members() const { return data_members_; }
private:
FRIEND_REF_COUNTED_THREAD_SAFE(Variant);
FRIEND_MAKE_REF_COUNTED(Variant);
Variant(std::optional<uint64_t> discr_value,
std::vector<LazySymbol> data_members);
virtual ~Variant();
std::optional<uint64_t> discr_value_;
std::vector<LazySymbol> data_members_;
};
} // namespace zxdb
#endif // SRC_DEVELOPER_DEBUG_ZXDB_SYMBOLS_VARIANT_H_
| true |
2a250278bdb800a5299f86c292b8a41e59f110bd | C++ | aelawson/voxel_engine | /include/renderer.hpp | UTF-8 | 327 | 2.640625 | 3 | [] | no_license | #include <vector>
#pragma once
class Renderer {
public:
Renderer();
~Renderer();
void renderBlock(GLint x, GLint y, GLint z);
private:
GLuint _vao;
GLuint _vbo;
std::vector<GLfloat> _vertices;
void assembleBlock(GLfloat x, GLfloat y, GLfloat z);
void addVertex(std::vector<GLfloat> vertex);
};
| true |
d09677e4dcdefa7442491464cb152319032d272f | C++ | zRegle/algorithm | /bfs/Coloring a Border.cpp | UTF-8 | 2,826 | 3.625 | 4 | [] | no_license | /**
* Leetcode 1034. 边框着色
*
* 给出一个二维整数网格 grid,网格中的每个值表示该位置处的网格块的颜色。
* 只有当两个网格块的颜色相同,而且在四个方向中任意一个方向上相邻时,它们属于同一连通分量。
* 连通分量的边界是指连通分量中的所有与不在分量中的正方形相邻(四个方向上)的所有正方形,
* 或者在网格的边界上(第一行/列或最后一行/列)的所有正方形。
*
* 给出位于 (r0, c0) 的网格块和颜色 color,
* 使用指定颜色 color 为所给网格块的连通分量的边界进行着色,并返回最终的网格 grid 。
*
* 示例 1:
* 输入:grid = [[1,1],[1,2]], r0 = 0, c0 = 0, color = 3
* 输出:[[3, 3], [3, 2]]
* 示例 2:
* 输入:grid = [[1,2,2],[2,3,2]], r0 = 0, c0 = 1, color = 3
* 输出:[[1, 3, 3], [2, 3, 3]]
* 示例 3:
* 输入:grid = [[1,1,1],[1,1,1],[1,1,1]], r0 = 1, c0 = 1, color = 2
* 输出:[[2, 2, 2], [2, 1, 2], [2, 2, 2]]
*
* 提示:
* (1)1 <= grid.length <= 50
* (2)1 <= grid[0].length <= 50
* (3)1 <= grid[i][j] <= 1000
* (4)0 <= r0 < grid.length
* (5)0 <= c0 < grid[0].length
* (6)1 <= color <= 1000
*/
#include <vector>
#include <queue>
using std::vector;
using std::queue;
/* dfs方法参考dfs文件夹 */
/* 判断是否为边界:
* (1)是否处于网格边界?
* (2)相邻的四个格子是否有颜色跟grid[r0][c0]不一样的?
* 任意满足一个即为边界
*/
#define ID(x, y) (x * col + y)
#define VALID(x, y) (x >= 0 && y >= 0 && x < row && y < col)
class Solution {
public:
vector<vector<int>> colorBorder(vector<vector<int>>& grid, int r0, int c0, int color) {
int row = grid.size(), col = grid[0].size();
int direction[4][2] = {{-1,0}, {0,1}, {1,0}, {0,-1}};
vector<vector<int>> ans(grid.begin(), grid.end());
queue<int> q;
vector<int> vis(row * col);
int pos = ID(r0, c0);
q.push(pos); vis[pos] = 1;
while (!q.empty()) {
pos = q.front(); q.pop();
int x = pos / col, y = pos % col;
for (auto& d : direction) {
int i = x + d[0], j = y + d[1];
if (VALID(i, j)) {
if (grid[i][j] != grid[x][y]) {
/* 相邻格子颜色不同 */
ans[x][y] = color;
continue;
}
int npos = ID(i, j);
if (vis[npos] == 0) {
vis[npos] = 1;
q.push(npos);
}
} else {
/* 处于网格边缘 */
ans[x][y] = color;
}
}
}
return ans;
}
}; | true |
9f4213aa05ea69b6c66e9d5a0e8fa085582d98f9 | C++ | xingyingone/algorithm | /树/判断完全二叉树/a.cpp | GB18030 | 1,975 | 3.78125 | 4 | [] | no_license | #include<iostream>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
//
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
typedef TreeNode *BiTree;
//д
int CreateBiTree(BiTree &T)
{
int data;
/*cout<<"ʼ "<<endl;*/
//нֵһַ#ʾ
cin >> data;
if (data == 0)
{
T = NULL;
cout << " " << endl;
}
else
{
T = (BiTree)malloc(sizeof(TreeNode));
//ɸ
T->val = data;
//
cout << " " << endl;
CreateBiTree(T->left);
//
cout << " " << endl;
CreateBiTree(T->right);
}
return 0;
}
//flag_1 ־ ӽڵ Ƿ
//flag_2 ־ Ҷڵ Ƿ
bool chk(TreeNode* root) {
if (root == NULL)
return true;
queue<TreeNode*>iqueue;
iqueue.push(root);
int flag_1 = 0;
int flag_2 = 0;
TreeNode* cur= iqueue.front();
while (iqueue.size()>0) {
cur = iqueue.front();
iqueue.pop();
if (flag_2) {//ҶڵֺҶڵ
if (cur->left || cur->right)
return false;
}
if (cur->left == NULL && cur->right == NULL)//жǷΪҶڵ
flag_2 = 1;
else {//Ҷڵ
if (cur->left == NULL && cur->right != NULL)//еӽڵ
return false;
else if (cur->left != NULL && cur->right == NULL) {//еӽڵ
if (flag_1 == 1)//ӽڵֻܳһ
return false;
flag_1 = 1;
}
if (cur->left != NULL)
iqueue.push(cur->left);
if (cur->right != NULL)
iqueue.push(cur->right);
}
}
return true;
}
void main() {
TreeNode* p;
CreateBiTree(p);
if (chk(p))
cout << "1";
else
cout << "0";
} | true |
db9f79ff540d49b9851e545b9bc70e4fc8c433de | C++ | trunghe/EOlymp | /668_BusesAndAirplanes_Graph.cpp | UTF-8 | 2,758 | 2.796875 | 3 | [] | no_license | /*
* https://www.e-olymp.com/en/problems/668
* Category: Graph
* Solution: Dijkstra
*/
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
typedef pair<int, pii> ipii;
#define FOR(i, a, b) \
for (int i = (a); i < (b); i++)
#define FORE(i, a, b) \
for (int i = (a); i <= (b); i++)
#define MAX_V 1002
int noVertices, maxTickets, source, target, noBuses, noPlanes;
list<pii> busLines[MAX_V];
list<pii> planeFlights[MAX_V];
int dist[MAX_V][12]; // dist[u][t] == min path from source to u with t plane tickets bought
int dijkstra() {
priority_queue<ipii, vector<ipii>, greater<ipii> > minHeap;
FORE(i, 1, noVertices) {
FORE(j, 0, maxTickets) {
dist[i][j] = INT_MAX;
}
}
FORE(j, 0, maxTickets) {
dist[source][j] = 0;
}
minHeap.push(make_pair(0, make_pair(source, 0)));
while (!minHeap.empty()) {
int u = minHeap.top().second.first;
int boughtTickets = minHeap.top().second.second;
if (u == target) {
return dist[u][boughtTickets];
}
minHeap.pop();
for (auto &busLine : busLines[u]) {
int v = busLine.first;
int weight = busLine.second;
if (dist[v][boughtTickets] > dist[u][boughtTickets] + weight) {
dist[v][boughtTickets] = dist[u][boughtTickets] + weight;
minHeap.push(make_pair(dist[v][boughtTickets], make_pair(v, boughtTickets)));
}
}
if (boughtTickets < maxTickets) {
for (auto &planeFlight : planeFlights[u]) {
int v = planeFlight.first;
int weight = planeFlight.second;
if (dist[v][boughtTickets + 1] > dist[u][boughtTickets] + weight) {
dist[v][boughtTickets + 1] = dist[u][boughtTickets] + weight;
minHeap.push(make_pair(dist[v][boughtTickets + 1], make_pair(v, boughtTickets + 1)));
}
}
}
}
return 0;
}
void input() {
cin >> noVertices >> maxTickets >> source >> target;
cin >> noBuses;
int u, v, weight;
FOR(i, 0, noBuses) {
cin >> u >> v >> weight;
busLines[u].emplace_back(make_pair(v, weight));
busLines[v].emplace_back(make_pair(u, weight));
}
cin >> noPlanes;
FOR(i, 0, noPlanes) {
cin >> u >> v >> weight;
planeFlights[u].emplace_back(make_pair(v, weight));
planeFlights[v].emplace_back(make_pair(u, weight));
}
}
int main() {
// ios_base::sync_with_stdio(false);
// cin.tie();
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// freopen("error.txt", "w", stderr);
input();
cout << dijkstra() << endl;
return 0;
}
| true |
2d9ff277d75f06c6ca0132c14491bc9df29df7e3 | C++ | Lookyan/algos | /Treap/main.cpp | UTF-8 | 3,275 | 3.46875 | 3 | [] | no_license | #include <iostream>
using namespace std;
template <class T>
struct CNode
{
CNode(): key(0), left(0), right(0) {}
CNode(T& k): key(k), left(0), right(0) {}
T key;
CNode* left;
CNode* right;
};
template <class T>
class Tree
{
public:
Tree(): root(0) {}
~Tree();
void Add(T& val);
void Remove(T& val);
void inOrderPrint();
int Height();
private:
CNode<T>* root;
void inOrder(CNode<T>* root);
void del(CNode<T>* root);
int height(CNode<T>* root);
CNode<T>* findmin(CNode<T>* p);
CNode<T>* removemin(CNode<T>* p);
CNode<T> *remove(CNode<T>* p, T& k);
};
int main()
{
Tree<int> tree;
int n = 0;
cin >> n;
int value = 0;
for(int i = 0; i < n; i++) {
cin >> value;
tree.Add(value);
}
tree.inOrderPrint();
//cout << tree.Height();
return 0;
}
template <class T>
void Tree<T>::Add(T& val)
{
if(root == 0) {
root = new CNode<T>(val);
return;
}
CNode<T>* toInsert = root;
CNode<T>* prev = 0;
bool isleft = true;
while(true) {
if(toInsert == 0) {
toInsert = new CNode<T>(val);
if(prev != 0) {
if(isleft == true) {
prev->left = toInsert;
} else {
prev->right = toInsert;
}
}
break;
} else {
prev = toInsert;
if(val > toInsert->key) {
toInsert = toInsert->right;
isleft = false;
} else {
toInsert = toInsert->left;
isleft = true;
}
}
}
}
template <class T>
Tree<T>::~Tree()
{
del(root);
}
template <class T>
void Tree<T>::del(CNode<T> *root)
{
if(root != 0) {
del(root->left);
del(root->right);
delete root;
}
}
template <class T>
void Tree<T>::inOrderPrint()
{
inOrder(root);
}
template <class T>
void Tree<T>::inOrder(CNode<T> *root)
{
if(root == 0) return;
inOrder(root->left);
cout << root->key << " ";
inOrder(root->right);
}
template <class T>
int Tree<T>::Height()
{
return height(root);
}
template <class T>
int Tree<T>::height(CNode<T> *root)
{
if(root == 0) {
return 0;
}
return max(height(root->left), height(root->right)) + 1;
}
template <class T>
void Tree<T>::Remove(T &val)
{
root = remove(root, val);
}
template <class T>
CNode<T>* Tree<T>::remove(CNode<T> *p, T& k)
{
if(p == 0) return 0;
if(k < p->key) {
p->left = remove(p->left, k);
} else if(k > p->key) {
p->right = remove(p->right, k);
} else {
//нашли
CNode<T>* q = p->left;
CNode<T>* r = p->right;
delete p;
if(r == 0) {
return q;
}
CNode<T>* min = findmin(r);
min->right = removemin(r);
min->left = q;
return min;
}
return p;
}
template <class T>
CNode<T>* Tree<T>::findmin(CNode<T> *p)
{
return p->left ? findmin(p->left) : p;
}
template <class T>
CNode<T>* Tree<T>::removemin(CNode<T> *p)
{
if(p->left == 0) {
return p->right;
} else {
p->left = removemin(p->left);
return p;
}
}
| true |
0594ae2edc995fbb4ad37698886d54fb4d7c78b4 | C++ | mauriciocele/arap-sr-linearized | /src/HalfEdge/Mesh.cpp | UTF-8 | 11,054 | 2.984375 | 3 | [
"MIT"
] | permissive | /** \file Mesh.cpp Definitions for the Mesh class.
\author Liliya Kharevych
\date March 2006
*/
#include "Mesh.h"
#include <iostream>
#include <fstream>
#include "util.h"
#include <stack>
#include <iomanip>
#include <algorithm>
#include <map>
#include <vector>
#include <assert.h>
using namespace std;
Mesh::Mesh(void)
{
numBoundaryVertices = 0;
}
Mesh::~Mesh(void)
{
clear();
}
void Mesh::clear() {
for (Edge* e : edges) { delete e; }
vertices.clear();
faces.clear();
edges.clear();
}
int Mesh::addVertex(const Eigen::Vector3d & _p) {
Vertex v;
v.p = _p;
v.ID = (int)vertices.size();
vertices.push_back(v);
return v.ID;
}
void Mesh::initFace(const std::vector<int>& faceVerts, int faceID) {
Face* f = &faces[faceID];
f->ID = faceID;
Edge * firstEdge = NULL;
Edge * last = NULL;
Edge * current = NULL;
unsigned int i;
for (i = 0; i < faceVerts.size()-1; i++) {
current = addEdge(faceVerts[i], faceVerts[i+1]);
check_error (!current, "Problem while parsing mesh faces.");
current->face = f;
if (last)
last->next = current;
else
firstEdge = current;
last = current;
}
current = addEdge (faceVerts[i], faceVerts[0]);
check_error (!current, "Problem while parsing mesh faces.");
current->face = f;
last->next = current;
current->next = firstEdge;
f->edge = firstEdge;
}
Edge * Mesh::addEdge (int i, int j) {
Edge eTmp;
eTmp.vertex = &vertices[i];
Edge eTmpPair;
eTmpPair.vertex = &vertices[j];
eTmp.pair = &eTmpPair;
Mesh::EdgeSet::iterator eIn = edges.find(&eTmp);
Edge * e;
if (eIn != edges.end()){
e = *eIn;
if (e->face != NULL)
return NULL;
}
else {
e = new Edge();
Edge * pair = new Edge();
e->vertex = &vertices[i];
pair->vertex = &vertices[j];
pair->pair = e;
e->pair = pair;
edges.insert(e);
edges.insert(pair);
pair->vertex->edge = pair;
}
return e;
}
void Mesh::computeNormals()
{
map< int, Eigen::Vector3d > normals;
for (Face& face : faces) {
Eigen::Vector3d u = face.edge->next->vertex->p - face.edge->vertex->p;
Eigen::Vector3d v = face.edge->next->next->vertex->p - face.edge->vertex->p;
Eigen::Vector3d n = u.cross(v).normalized();
normals.insert( pair<int, Eigen::Vector3d>(face.ID, n) );
}
for (Vertex& vertex : vertices) {
int valence = 0;
vertex.n = Eigen::Vector3d(0,0,0);
for( Vertex::EdgeAroundIterator around = vertex.iterator(); !around.end(); around++ )
{
if(around.edge_out()->face)
{
int faceId = around.edge_out()->face->ID;
vertex.n += normals[faceId];
valence++;
}
}
vertex.n /= (double)valence;
vertex.n.normalize();
}
}
/** Called after the mesh is created to link boundary edges */
void Mesh::linkBoundary() {
for (Edge* edge : edges) {
if (!edge->face)
edge->vertex->edge = edge;
}
Edge *next, *beg;
for (Vertex& vertex : vertices) {
if (vertex.isBoundary()) {
beg = vertex.edge;
next = beg;
while (beg->pair->face)
beg = beg->pair->next;
beg = beg->pair;
beg->next = next;
numBoundaryVertices++;
}
}
}
/** Computes information about the mesh:
Number of boundary loops,
Number of connected components,
Genus of the mesh.
Only one connected compoment with 0 or 1 boundary loops can be parameterize.
Singularities should be assigned in such a way that Gauss-Bonet theorem is satisfied.
*/
void Mesh::computeMeshInfo() {
cout << "Topological information about the mesh:" << endl;
// Number of boundary loops
for (Edge* edge : edges) {
edge->check = false;
}
numBoundaryLoops = 0;
for (Edge* edge : edges) {
Edge * e = edge;
if (e->face)
e->check = true;
else if (!e->check) {
Edge * beg = NULL;
while (e != beg) {
if (!beg) beg = e;
check_error(!e, "Building the mesh failed, probem with input format.");
e->check = true;
e = e->next;
}
numBoundaryLoops++;
}
}
cout << "Mesh has " << numBoundaryLoops << " boundary loops." << endl;
// Number of connected components
numConnectedComponents = 0;
for (Face& face : faces) {
face.check = false;
}
stack<Edge *> toVisit;
for (Face& face : faces) {
if (!face.check) {
numConnectedComponents++;
toVisit.push(face.edge);
while (!toVisit.empty()) {
Face * fIn = toVisit.top()->face;
toVisit.pop();
fIn->check = true;
Face::EdgeAroundIterator iter = fIn->iterator();
for (; !iter.end(); iter++)
if (iter.edge()->pair->face && !iter.edge()->pair->face->check)
toVisit.push(iter.edge()->pair);
}
}
}
cout << "Mesh has " << numConnectedComponents << " connected components." << endl;
// Genus number
check_error(numConnectedComponents == 0, "The mesh read is empty.");
numGenus =
(1 - (numVertices() - numEdges() + numFaces() + numBoundaryLoops ) / 2) / numConnectedComponents;
cout << "Mesh is genus " << numGenus << "." << endl;
}
/** Check if all the vertices in the mesh have at least on edge coming out of them */
bool Mesh::checkVertexConection() {
bool conectedVert = true;
for (Vertex& vertex : vertices)
vertex.check = false;
for (Face& face : faces) {
Face::EdgeAroundIterator around = face.iterator();
for (;!around.end();around++)
around.vertex()->check = true;
}
for (Vertex& vertex : vertices) {
if (!vertex.check) {
cerr << "Vertex " << vertex.ID << " is not connected." << endl;
conectedVert = false;
}
}
return conectedVert;
}
/** Manifoldness check: only one disk should be adjusted on any vertex */
bool Mesh::checkManifold() {
bool manifold = true;
for (Edge* edge : edges)
edge->check = false;
for (Vertex& vertex : vertices) {
Vertex::EdgeAroundIterator around = vertex.iterator();
for (;!around.end();around++)
around.edge_out()->check = true;
}
for (Edge* edge : edges) {
if (!edge->check) {
cerr << "Mesh is not manifold - more then one disk at vertex "
<< edge->vertex->ID << endl;
manifold = false;
break;
}
}
return manifold;
}
void Mesh::CenterAndNormalize()
{
double maxX, maxY, maxZ, minX, minY, minZ;
maxX = maxY = maxZ = -1e38;
minX = minY = minZ = 1e38;
for (Vertex& vertex : vertices)
{
if(vertex.p.x() > maxX) maxX = vertex.p.x();
if(vertex.p.y() > maxY) maxY = vertex.p.y();
if(vertex.p.z() > maxZ) maxZ = vertex.p.z();
if(vertex.p.x() < minX) minX = vertex.p.x();
if(vertex.p.y() < minY) minY = vertex.p.y();
if(vertex.p.z() < minZ) minZ = vertex.p.z();
}
Eigen::Vector3d min(minX,minY,minZ);
Eigen::Vector3d max(maxX,maxY,maxZ);
Eigen::Vector3d center = min + (max - min) * 0.5;
for (Vertex& vertex : vertices) {
vertex.p -= center;
}
double diag = (max - min).norm() / 2.0;
double scale = 1.0 / diag;
for (Vertex& vertex : vertices) {
vertex.p *= scale;
}
}
/** Loads mesh from obj file
Standard format for OBJ file is
v double double double
v double double double
f int int int
f int int int
Files with vt tags also can be parsed
*/
void Mesh::readOBJ(const char * obj_file) {
string front;
string v = "v", vt = "vt", f = "f";
Eigen::Vector3d vert;
vector<Eigen::Vector3d> uvVec;
char etc;
int id;
struct TempFace {
vector<int> verts;
vector<int> uvs;
int ID;
};
vector<TempFace> tempFaces;
ifstream in(obj_file);
check_error(!in, "Cannot find input obj file.");
bool hasUV = false;
while(!in.eof() || in.peek() != EOF) {
in >> ws; //extract whitespaces
if (in.eof() || in.peek() == EOF)
break;
if (in.peek() == '#') {
in.ignore(300, '\n');
}
else {
in >> front;
if (front == v) {
in >> vert.x() >> vert.y() >> vert.z();
addVertex(vert);
}
else if (front == vt){
in >> vert.x() >> vert.y();
vert.z() = 0;
uvVec.push_back(vert);
hasUV = true;
}
else if (front == f) {
TempFace tempFace;
while (in >> id) {
check_error(id > numVertices(), "Problem with input OBJ file.");
tempFace.verts.push_back(id-1);
bool vtNow = true;
if (in.peek() == '/'){
in >> etc;
if (in.peek() != '/') {
in >> id;
check_warn(id > numVertices(), "Texture coordinate index is greater then number of vertices.");
if (id < numVertices() && hasUV) {
tempFace.uvs.push_back(id-1);
vtNow = false;
}
}
}
if (in.peek() == '/'){
int tmp;
in >> etc;
in >> tmp;
}
if (hasUV && vtNow) {
tempFace.uvs.push_back(id-1);
}
}
in.clear(in.rdstate() & ~ios::failbit);
tempFace.ID = tempFaces.size();
tempFaces.push_back(tempFace);
}
else {
string line;
getline(in, line);
cout << "Warning, line: " << line << " ignored." << endl;
}
}
}
in.close();
faces.resize(tempFaces.size());
for(TempFace& tempFace : tempFaces) {
initFace(tempFace.verts, tempFace.ID);
if (hasUV && tempFace.uvs.size() != 0){
int k = 0;
for (Face::EdgeAroundIterator e = faces[tempFace.ID].iterator(); !e.end(); e++, k++)
e.vertex()->uv = uvVec[tempFace.uvs[k]];
}
}
tempFaces.clear();
// Finnish building the mesh, should be called after each parse.
finishMesh();
}
/* Write mesh in OBJ format to obj_file parameter */
void Mesh::writeOBJ(const char * obj_file) {
ofstream out(obj_file);
check_error (!out, "Cannot find output file.");
for (Vertex& vertex : vertices)
out << "v " << vertex.p << endl;
for (Vertex& vertex : vertices)
out << "vt " << vertex.uv.x() << " " << vertex.uv.y() << endl;
for (Face& face : faces) {
Face::EdgeAroundIterator around = face.iterator();
out << "f";
for ( ; !around.end(); around++)
out << " " << (around.vertex()->ID + 1) << "/" << (around.vertex()->ID + 1);
out << endl;
}
}
/* Write mesh in VT format (only text coodrinates) to vt_file parameter */
void Mesh::writeVT(const char * vt_file) {
ofstream out(vt_file);
check_error (!out, "Cannot find output file.");
for (Vertex& vertex : vertices)
out << "vt " << vertex.uv.x() << " " << vertex.uv.y() << endl;
}
| true |
d1dda45944dd230f9fe692b743850aa846b70a06 | C++ | AndresMontenegroArguello/UTC | /2020/Programación I/Programas/Tareas/Tarea 1/Programas/Ejercicio 05/Tarea01_Ejercicio05_Windows.cpp | UTF-8 | 3,798 | 3.453125 | 3 | [] | no_license | // Tarea01_Ejercicio05_Windows.cpp
// Tarea 01: Ejercicio 05
// Cálculo de Operaciones + Mayor/Menor
// Desarrollado por: Andrés Montenegro
// https://www.amsoftware.co
// https://www.andresmontenegro.co
// Plataforma: Windows
// Bibliotecas
#include <stdio.h>
#include <stdlib.h>
//#include <curses.h> // Utilizo la biblioteca curses.h en lugar de conio.h, ya que actualmente desarrollo en Mac OS X
#include <conio.h> // Utilizo la biblioteca conio.h para compilar en Windows OS
// Variables globales
int n1, n2, mayor, menor; // Variables de tipo entero
float resultado; // Resultado de tipo flotante
char operador = '#', continuar = 'S'; // Variables de tipo caracter. Inicializo las variables para asegurar la posterior ejecución de los ciclos <<While>>
int main()
{
do
{
//system("clear"); // Borrar la pantalla: Utilizo el comando de sistema "clear" para compilar en Mac OS X
system("cls"); // Borrar la pantalla: Utilizo el comando de sistema "cls" para compilar en Windows OS
system("color 5f"); // Configurar color de pantalla: Utilizo el comando de sistema "color 5f" para compilar en Windows OS
printf("\n\t *** Programa de Cálculo de Operaciones ***"); // Imprimir mensaje de Bienvenida
printf("\n\t *** Desarrollado por Andrés Montenegro ***"); // Imprimir mensaje de Desarrollador
printf("\n\t *** https://www.amsoftware.co ***"); // Imprimir mensaje de Desarrollador
printf("\n\t *** https://www.andresmontenegro.co ***"); // Imprimir mensaje de Desarrollador
printf("\n\n Ingrese el primer número entero: "); // Solicitar dato: Primer número
scanf("%i", &n1); // Leer dato: Primer número
printf("\n\n Ingrese el segundo número entero: "); // Solicitar dato: Segundo número
scanf("%i", &n2); // Leer dato: Segundo número
do // Iniciar ciclo de validación de operador matemático (Para evitar el ingreso de valores fuera al rango permitido [+, -, *, /])
{
printf("\n\n Ingrese el operador matemático [+, -, *, /]: "); // Solicitar dato: Operador matemático
scanf("%c", &operador); // Leer dato: Operador matemático
} while (operador != '+' && operador != '-' && operador != '*' && operador != '/');
// Encontrar valores: Mayor/Menor
if (n1 >= n2)
{
mayor = n1;
menor = n2;
}
else
{
mayor = n2;
menor = n1;
}
// Realizar operación seleccionada
if (operador == '+')
resultado = mayor + menor;
else if (operador == '-')
resultado = mayor - menor;
else if (operador == '*')
resultado = mayor * menor;
else if (operador == '/')
resultado = mayor / menor;
//system("clear"); // Borrar la pantalla: Utilizo el comando de sistema "clear" para compilar en Mac OS X
system("cls"); // Borrar la pantalla: Utilizo el comando de sistema "cls" para compilar en Windows OS
printf("\n\t *** Programa de Cálculo de Operaciones ***"); // Imprimir mensaje de Bienvenida
printf("\n\t *** Desarrollado por Andrés Montenegro ***"); // Imprimir mensaje de Desarrollador
printf("\n\t *** https://www.amsoftware.co ***"); // Imprimir mensaje de Desarrollador
printf("\n\t *** https://www.andresmontenegro.co ***"); // Imprimir mensaje de Desarrollador
printf("\n\n\t %i %c %i = %.2f", mayor, operador, menor, resultado); // Imprimir resultado
printf("\n\n\n\t ¿Desea realizar otra operación [S/N]?"); // Imprimir mensaje para continuar
do
{
scanf("%c", &continuar); // Leer dato: Continuar
} while (continuar != 'S' && continuar != 's' && continuar != 'N' && continuar != 'n'); // Iniciar ciclo de validación para continuar
} while (continuar == 'S' || continuar == 's');
//system("clear"); // Borrar la pantalla: Utilizo el comando de sistema "clear" para compilar en Mac OS X
system("cls"); // Borrar la pantalla: Utilizo el comando de sistema "cls" para compilar en Windows OS
return 0;
} | true |
8959c7991da28b9bd65e0336679f8c147648b6d0 | C++ | RenatoBrittoAraujo/Competitive-Programming | /URI-Online-Judge/2235.cpp | UTF-8 | 313 | 2.90625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int a,b,c;
cin>>a>>b>>c;
bool s=false;
if(a==b||a==c||b==c)s=true;
else{
if(c>b){int t=c;c=b;b=t;}
if(b>a){int t=a;a=b;b=t;}
if(a==b+c)s=true;
}
if(s)cout << "S\n";
else cout << "N\n";
return 0;
}
| true |
702e0ff216b55b78533ada7fbec93bec1d98217f | C++ | KrKush23/LeetCode | /Problems/0303. Range Sum Query - Immutable.cpp | UTF-8 | 472 | 3.171875 | 3 | [
"MIT"
] | permissive | class NumArray {
vector<int> preSum{};
public:
NumArray(vector<int>& nums) {
int n = nums.size();
preSum.resize(n+1);
for(int i=0;i<n;i++){
preSum[i+1] = preSum[i] + nums[i];
}
}
int sumRange(int i, int j) {
return preSum[j+1] - preSum[i];
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(i,j);
*/
| true |
0fc7ba0b15bc9527bad733627c761f0c10512948 | C++ | Cnd96/comp | /travelling.cpp | UTF-8 | 3,853 | 3.71875 | 4 | [] | no_license | #include "bits/stdc++.h"
using namespace std;
int noCities; // integer variable to for number of cities
int mindis = INT_MAX; //minimum distance (answer) initialized by maximum integer value
bool visited[10000];// boolean array to check the visited nodes in the graph
int randomNumber;//integer variable hold random numbers
vector<vector<int>> distanceData; // 2D vector hold distance between cities
//Method to generate distance between cities. Takes number of cities as the arguement
void generateDistance(int n){
//Assinging distance equals zero for all the cities
for (int i = 0; i < n; i++)
{
vector<int> vec(n, 0);
distanceData.push_back(vec);
}
//Generating random numbers and assinging as the distance between two cities in the 2D vector distanceData
for (int i = 0; i < distanceData.size()-1; i++)
for (int j= i+1; j < distanceData[i].size(); j++){
randomNumber = (rand() % 300) + 1;
distanceData[i][j]=randomNumber;
distanceData[j][i]=randomNumber;
}
// Displaying the distance matrix. Not neccasary for calculating minimum distance.
// Just to display the randomly generated distance and verify.
for (int i = 0; i < distanceData.size(); i++)
{
cout<<"[";
for (int j= 0; j < distanceData[i].size(); j++)
cout<<distanceData[i][j]<<",";
cout<<"],\n";
}
}
//Method to calculate the minimum distance
//Take the current city in the graph, current distance travled and number of current visited cities as the arguement
void calculateDistance(int i, int currentdistance, int t)
{
//Making the current city as visited in the visited boolean array
visited[i] = true;
// Incrementing the current number of visited cities
t++;
//Check whether all the cities are visited
if (t == noCities)
{
/*
If all the cities are visited add the distance between current city and starting city to the current distance
and assigning the minimum value between current distance and current minimum distance to current minimum distance
*/
mindis = min(mindis, currentdistance + distanceData[i][0]);
// making current city as unvisited for backtrack
visited[i] = false;
return;
}
//Iterating over all the cities to check the unvisited cities
for (int j = 0; j < noCities; j++)
{
// checking whether a city is not visited
if (visited[j] == false)
{
/* checking whether the sum of current distance travelled and the distance between current city to the next unvisited city
is greater than current minimum distance.
This validation is to stop unneccasary recursive calls.
*/
if ( (currentdistance+ distanceData[i][j])>= mindis)
{
// making current city as unvisited for backtrack and returnig without making a recursive call to next unvisited city
visited[i] = false;
return;
}
/*
moving to the next unvisited city
*/
calculateDistance(j, currentdistance + distanceData[i][j], t);
}
}
// making current city as unvisited for backtrack
visited[i] = false;
}
int main()
{
srand((unsigned)time(NULL));
memset(visited, false, sizeof(visited));
cout<<"Enter no of cities :";
cin>>noCities;
cout<<"\n";
cout<<"Distance Matrix"<<"\n";
generateDistance(noCities);
const clock_t begin_time = clock();
//calling calculateDistance function
calculateDistance(0, 0, 0);
cout << "\nMinimum Distance :";
cout << mindis<<"\n";
cout << "Time taken :"<<(float( clock () - begin_time )/CLOCKS_PER_SEC)<<"seconds";
return 0;
}
| true |
54f0a19d1b35735c965cfe4e6c7207ab6d15d12a | C++ | fotopretty/SIM900-lib | /SIM900.h | UTF-8 | 8,410 | 2.890625 | 3 | [
"MIT"
] | permissive | /** SIM900 Basic communication library for SIM900 gsm module.
*
* This library provide easy way to make GET and POST petitions to a web server. Use to interactue Arduino with restful apis, webs, etc.
*
* Released under MIT license.
*
* @author Miquel Vento (http://www.emevento.com)
* @version 1.0 24/03/2015
*
*/
#pragma once
#ifndef __Connection_h__
#define __Connection_h__
#include <Arduino.h>
class Connection
{
public:
/** \brief Constructuor
*
* @param IN pin code of the SIM
* @param IN apn name of your provider
* @param IN apn user of your provider. Usually is ""
* @param IN apn password of your privider. Usually is ""
* @param IN enable pin for power on the board.
* @param IN serial port of your arduino.
* @param IN baudRate for communications. Defaults 115200.
*/
Connection( const char * pinCode,
const char * apnName,
const char * apnUser = "",
const char * apnPass = "",
const uint8_t & enablePin = 2,
HardwareSerial &serialPort = Serial,
uint32_t baudRate = 115200 );
/** \brief Configure module to make connections.
* Is necessary to executate every time after power on or reboot the module.
*/
bool Configuration();
/** \brief Make a Get petition to the server and receive data
* IMPORTANT! REMEMBER DELETE bodyReply content when you dont need more.
*
* Request example www.example.com/api/europe/madrid/time
*
* @param IN Server domain or public IP. e.g. www.example.com OR 216.58.210.164
* @param IN Server path eg: api
* @param IN Server url eg: europe/madrid/time
* @param OUT Http Reply of the request: e.g. 200, 404, etc.
* @param OUT Reply of the request. The variable is initialized inside of method. REMEMBER DELETE when you don't need.
* @param IN Server port. The default value is 80
*
* @return true if the operation ends ok
*/
bool Get( const char * host,
const char * path,
const char * url,
uint16_t & headerHttpReply,
char *& bodyReply,
const int port = 80 );
/** \brief Make a Post petition to the server
*
* Request example www.example.com/api/europe/madrid/time
*
* @param IN Server domain or public IP. e.g. www.example.com OR 216.58.210.164
* @param IN Server path eg: api
* @param IN Server url eg: europe/madrid/time
* @param IN data to send. eg: {"hour":10,"minutes":21,"seconds":13}
* @param OUT Http Reply of the request: e.g. 200, 404, etc.
* @param IN Server port. The default value is 80
*
* @return true if the operation ends ok
*/
bool Post( const char * host,
const char * path,
const char * url,
const char * data,
uint16_t & headerHttpReply,
const int port = 80 );
/** \brief Turn on the GPRS module.
*
*/
void PowerOn();
/** \brief Turns off the GPRS module
*
*/
void PowerOff();
protected:
/** \brief Check if the GPRS module is on.
*
* @return true if the module is on
*/
bool IsPowered();
/** \brief Enables SIM900 AT command echo
*
*/
void EchoOn( );
/** \brief Disables SIM900 AT Command echo
*
*/
void EchoOff( );
/** \brief Introduces the pin code if is necessary
*
*/
bool AT_CPIN();
/** \brief Check the status of the ME registration
*
* -Correct Answers
* +CREG: 0,1 -> Registered, home network
* +CREG: 0,5 -> Registered, roaming
* -Waiting Answers
* +CREG: 0,0 -> Not registered, MT is not currently searching
* +CREG: 0,2 -> Not registered, MT is currently searching
* +CREG: 0,4 -> Unknow
*
* @return true if the action ends OK
*/
bool AT_CREG();
/** \brief Check the state of the bearer
*
* @return true if is opened
*/
bool IsBearerOpen();
/** \brief Bearer settings for applications based on ip
*
* @return true if the action ends OK
*/
bool OpenBearer();
/** \brief Update the information of the APN provider. This action is only necessary if you changes the SIM service provider
*
* @return true if the info is introduced and storaged correctly
*/
bool UpdateBearerInfo();
/** \brief Makes a Get petition
*
*/
bool AT_HTTPACTION_GET( uint16_t & httpHeader );
/** \brief Makes a Post petition
*
*/
bool AT_HTTPACTION_POST( uint16_t & httpHeader );
/** \brief Sends the content for POST petition
*
* @param IN size of the data
* @param IN timeout for the operation
*
* @return true if the operation ends correctly
*/
bool AT_HTTPDATA( const int & size,
const int & timeout );
/** \brief Set the http parameters
*
* @param IN host of the server
* @param IN path of the url
* @param IN the other part of the url
*
* @return true if the operation ends correctly
*/
bool AT_HTTPPARA_URL( const char * host,
const char * path,
const char * url );
/** \brief Receive the httpheader of a GET or POST petition
*
* Reply example: +HTTPACTION:1,201,0
*
* @param IN expected answere (HTTPACTION:*,)
* @param OUT httpHeader received for operation
* @param IN timeout for the operation
*
* @return true if the operation ends correctly
*/
bool GetHttpHeader( const char * expected_answer,
uint16_t & httpHeader,
const uint16_t & timeout );
/** \brief Calculates if time for operation is run out
*
* @return true after timing out
*/
bool TimeOut( const uint32_t & previousTime,
const uint16_t & timeOut );
/** \brief Get the size of the received data from server.
* Execute this method INMEDIATLY after AT+HTTPREAD operation
*/
uint16_t GetReceiveDataSize( const uint16_t & timeout );
/** \brief Waits for serial data, in accotated time.
*
*/
bool WaitingSerialAvailable( const uint32_t & previousTime,
const uint16_t & timeout );
/** \brief Receive data from server after Get request.
* Get the data after send AT+HTTPREAD command
*
* @param OUT bodyReply string of server answer
*
* @return true if operation finish ok
*/
bool ReceiveData( char *& bodyReply,
const uint16_t & timeout );
/** \brief Cleans Serial input buffer.
*
*/
void CleanSerialBuffer();
/** \brief Send AT commmand and check the answer
*
* @return 0 if the recuest isn't correct
*/
int8_t SendATcommand( const char* ATcommand,
const char* expectedAnswer,
const unsigned int & timeout );
/** \brief Send AT command and check the two possible answers
*
* @return the number of the answer or 0 if it don't exist
*/
int8_t SendATcommand( const char* ATcommand,
const char* expectedAnswer1,
const char* expectedAnswer2,
const unsigned int & timeout );
/** \brief Send AT command and check the N possible answers
*
* @param IN ATcommand AT command to send
* @param IN expectedAnswers String array for posibles answers
* @param IN totalAnswers size of expectedAnswers array
* @param IN timeout max size for finish the operation
*
* @return the number of the answer or 0 if it don't exist
*/
int8_t SendATcommand( const char* ATcommand,
const char ** expectedAnswers,
const int & totalAnwers,
const unsigned int & timeout );
/** \brief Receive the response after AT Command Send.
*
* @param IN expectedAnswers String array for posibles answers
* @param IN totalAnswers size of expectedAnswers array
* @param IN timeout max size for finish the operation
*/
int8_t ReceiveATReply( const char ** expectedAnswers,
const int & totalAnwers,
const unsigned int & timeout );
/** \brief Receive the response after AT Command Send.
*
* @param IN expectedAnswer expected answer to receive
* @param IN timeout max size for finish the operation
*/
int8_t ReceiveATReply( const char * expectedAnswer,
const unsigned int & timeout );
private:
const char * _pinCode;
const char * _apnName;
const char * _apnUser;
const char * _apnPass;
const uint8_t _enablePin;
// Configuration
const int CREG_WAITING_RETRIES;
const int SAPBR_WAITING_RETRIES;
const int CGATT_WAITING_RETRIES;
const int MAX_ATRESPONSE;
HardwareSerial * sim900Serial;
};
#endif
| true |
399fbcba274d8ed86bb65722a30a42973c318d3d | C++ | david990917/CPP-PROGRAMMING | /Textbook/Chapter5/顺序查找.cpp | UTF-8 | 269 | 2.953125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main() {
int idx, x=5;
int array[] = { 2,3,1,7,5,8,9,0,4,6 };
for (idx = 0; idx < 10; idx++) {
if (x == array[idx]) { cout << idx; break; }
}
if (idx == 10) { cout << "Not Found!" << endl; }
return 0;
} | true |
e945a2596a5c7bd925a6392bdd6745490c60c41a | C++ | skynet29/rpi | /utils/src/DThread.cpp | UTF-8 | 1,056 | 3.03125 | 3 | [] | no_license |
#include "DThread.h"
#include "DTimer.h"
#include <unistd.h>
DThread::DThread()
{
handler = NULL;
arg =NULL;
}
void DThread::SetCallback(ThreadHandler handler, void* arg)
{
this->handler = handler;
this->arg = arg;
}
bool DThread::Start()
{
return (pthread_create(&desc, NULL, Handler, this) == 0);
}
void* DThread::Handler(void* arg)
{
((DThread*)arg)->OnRun();
return NULL;
}
void DThread::OnRun()
{
if (handler)
handler(arg);
}
bool DThread::Join()
{
return (pthread_join(desc, NULL) == 0);
}
void DThread::Sleep(int val)
{
sleep(val/1000);
usleep((val%1000)*1000);
}
bool DThread::WaitCond(bool (*CondFunc)(void*), void* arg, int timeout)
{
DTimer timer(timeout);
while (!CondFunc(arg))
{
if (timer.GetRemainingTime() < 0)
{
return false;
}
DThread::Sleep(10);
}
return true;
}
DMutex::DMutex()
{
pthread_mutex_init(&desc, NULL);
}
DMutex::~DMutex()
{
pthread_mutex_destroy(&desc);
}
void DMutex::Lock()
{
pthread_mutex_lock(&desc);
}
void DMutex::Unlock()
{
pthread_mutex_unlock(&desc);
}
| true |
50bfb71f2438e80ea0f689695835ecf31e9f8f53 | C++ | richardcypher/leetcode | /120/main.cpp | UTF-8 | 997 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int minimumTotal(vector<vector<int> >& triangle) {
if(triangle.empty())
return 0;
vector<int> sum(triangle.size(), 0);
sum[0] = triangle[0][0];
for (int i = 1; i < triangle.size(); ++i)
{
for (int j = triangle[i - 1].size(); j >= 0; --j)
{
if(j == triangle[i - 1].size()) {
sum[j] = triangle[i][j] + sum[j - 1];
}
else if(j == 0) {
sum[j] = triangle[i][j] + sum[j];
}
else {
sum[j] = triangle[i][j] + (sum[j] < sum[j - 1] ? sum[j] : sum[j - 1]);
}
}
}
int min = sum[0];
for (int i = 0; i < sum.size(); ++i)
{
if(sum[i] < min)
min = sum[i];
}
return min;
}
int main() {
vector<vector<int> > tria;
vector<int> row;
row.push_back(1);
tria.push_back(row);
cout<<minimumTotal(tria)<<endl;
return 0;
} | true |
c04187a6aa2e5a9d3aa7e93a5046dd96480e5252 | C++ | johnsna7/162_FinalProject | /Game.hpp | UTF-8 | 2,804 | 3.640625 | 4 | [] | no_license | /**************************************************
* File Name: Game.hpp
* Author: Nathan Johnson
* Date: 06.09.2019
* Description: Creates and plays the game
* ************************************************/
#ifndef GAME_HPP
#define GAME_HPP
#include "Player.hpp"
#include "Room.hpp"
#include "menu.hpp"
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
/**************************************************
* Class Name: Game
* What it does: Creates 16 spaces of various
* types as the game board, along with a player.
* Then loops turns where the player moves to
* and interacts with different rooms until
* they either lose or blow up the ship with
* the laser.
* Description: Creates and plays the game
* ************************************************/
class Game
{
private:
// Spaces for the board
Space* r1;
Space* r2;
Space* r3;
Space* r4;
Space* r5;
Space* r6;
Space* r7;
Space* r8;
Space* r9;
Space* r10;
Space* r11;
Space* r12;
Space* r13;
Space* r14;
Space* r15;
Space* r16;
Space* current; // Pointer to space player is in
Player* robot; // Pointer to player's character
bool lost; // true when player loses game
// Initializes Spaces in the game
void makeMap();
public:
// Default constructor
Game();
// Destructor to delete pointers
~Game();
/************************************
* Function Name: play()
* Called By: menu
* Calls: Player functions, turn, win & lose
* Passed: Nothing
* Returns: Nothing
* Description: Plays the game until
* the player wins or loses
* **********************************/
void play();
/************************************
* Function Name: win()
* Called By: play
* Calls: Nothing
* Passed: Nothing
* Returns: Nothing
* Description: Displays winning
* message
* **********************************/
void win();
/************************************
* Function Name: lose()
* Called By: play
* Calls: Player function
* Passed: Nothing
* Returns: Nothing
* Description: Displays losing
* message
* **********************************/
void lose();
/************************************
* Function Name: turn()
* Called By: play
* Calls: move, Player & Space functions
* Passed: Nothing
* Returns: Nothing
* Description: Moves the player to
* a new space and interacts with it
* **********************************/
void turn();
/************************************
* Function Name: move()
* Called By: turn
* Calls: Space functions
* Passed: Nothing
* Returns: Nothing
* Description: Moves player to the
* next Space of their choosing.
* **********************************/
void move();
};
#endif
| true |
777be928cb6821479ed81ef59669daf7d309f3dd | C++ | weakmale/hhabb | /HDU/1234/6491786_WA_0ms_0kB.cpp | UTF-8 | 832 | 2.609375 | 3 | [] | no_license | #include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node{
char id[20];
int h[2];
int m[2];
int s[2];
}stu[1111];
bool cmp(node a,node b){
if(a.h[0]!=b.h[0])
return a.h[0]<b.h[0];
if(a.m[0]!=b.m[0])
return a.m[0]<b.m[0];
if(a.s[0]<b.s[0])
return a.s[0]<b.s[0];
}
bool cmp1(node a,node b){
if(a.h[1]!=b.h[1])
return a.h[1]<b.h[1];
if(a.m[1]!=b.m[1])
return a.m[1]<b.m[1];
if(a.s[1]<b.s[1])
return a.s[1]<b.s[1];
}
int n;
int m;
int main(){
scanf("%d",&n);
while(n--){
memset(stu,0,sizeof(stu));
scanf("%d",&m);
for(int i=0;i<m;i++)
scanf("%s %d:%d:%d %d:%d:%d",stu[i].id,&stu[i].h[0],&stu[i].m[0],&stu[i].s[0],&stu[i].h[1],&stu[i].m[1],&stu[i].s[1]);
sort(stu,stu+m,cmp);
printf("%s ",stu[0].id);
sort(stu,stu+m,cmp1);
printf("%s\n",stu[m-1].id);
}
return 0;
} | true |
7322155bfc90118283b461a444f7a8bc861b5949 | C++ | alexandraback/datacollection | /solutions_5769900270288896_0/C++/Pufforrohk/Bric.cpp | UTF-8 | 893 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <cassert>
using namespace std;
int N,R,C;
int arr[17][17];
int count(){
int c=0;
int b=0;
for(int i=0;i<R;i++){
for(int j=0;j<C;j++){
if(arr[i][j]==1){
c++;
if(arr[i+1][j]==1)
b++;
if(arr[i][j+1]==1)
b++;
}
}
}
if(c==N)
return b;
else
return 10000;
}
int ric(int x,int y){
if(x==0 && y==C){
return count();
}else{
// cout<<x<<" "<<y<<endl;
int nx = (x+1)%R;
int ny = (x==R-1) ? y+1: y;
arr[x][y]=0;
int ans= ric(nx,ny);
arr[x][y]=1;
ans = min(ans,ric(nx,ny));
return ans;
}
}
int solve(){
cin>>R>>C>>N;
assert(R*C<=16);
for(int i=0;i<17;i++){
arr[R][i]=0;
arr[i][C]=0;
}
return ric(0,0);
}
int main(){
int cases;
cin>>cases;
for(int i=0;i<cases;i++){
cout<<"Case #"<<i+1<<": "<<solve()<<endl;
}
return 0;
}
| true |
56960ea2a9d2e4b7161c94fa89153450f39b7a08 | C++ | whing123/C-Coding | /Others/35.cpp | UTF-8 | 535 | 2.796875 | 3 | [] | no_license | /*
聚力与攻击
*/
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main() {
int hp, normal, buffer;
cin >> hp >> normal >> buffer;
vector<int> dp(hp + 1, 0);
for (int i = 1; i <= hp; i++) {
if (i - normal >= 0 && i - buffer >= 0)
dp[i] = min(dp[i - normal] + 1, dp[i - buffer] + 2);
else if (i - normal >= 0)
dp[i] = dp[i - normal] + 1;
else if (i - buffer >= 0)
dp[i] = dp[i - buffer] + 2;
else
dp[i] = 1;
}
cout << dp[hp] << endl;
return 0;
} | true |
08a2eac26ddc5ecfd17cfd93408dc2c7c59bdf31 | C++ | Futsy/Euler | /Problem - 001 to 050/Problem - 029.cpp | UTF-8 | 345 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <set>
int main () {
std::set<double> powers;
for (int i = 2; i <= 100; i++) {
for (int j = 2; j <= 100; j++) {
powers.insert(std::pow(i,j));
}
}
//Sorting doesn't change anything
std::cout << "Solution: " << powers.size() << std::endl;
} | true |
202494eacbb694c2633abfd544f310b05e856c01 | C++ | ribak100/ATM-emulator-system-with-C- | /Exception.cpp | UTF-8 | 1,394 | 3.359375 | 3 | [] | no_license | /*
#include "Exception.h"
#include <iostream>
using namespace std;
NegativeNum::NegativeNum(){}
NegativeNum::NegativeNum(int negativeNum) :negative(negativeNum){}
NegativeNum::get_negative()
{
return negative;
}
TooFewNum::TooFewNum(){}
TooFewNum::TooFewNum(int fewNum) : few(fewNum){}
TooFewNum::get_few()
{
return few;
}
NumberRange::NumberRange(){}
NumberRange::NumberRange(int rangeNum) : range(rangeNum){}
NumberRange::get_range()
{
return range;
}
IntOnly::IntOnly(){}
IntOnly::IntOnly(int IntNum) : Int(IntNum){}
IntOnly::get_Int()
{
return Int;
}
NumSum::NumSum(){}
NumSum::NumSum(int sumNum): sum(sumNum){}
NumSum::get_sum()
{
return sum;
}
catch(NegativeNum neg)
{
cout << neg.get_negative()<<" is not a positive numbers, only positive numbers are allowed"<<endl;
}
catch(TooFewNum few)
{
cout << few.get_few()<<" is too small ,the least allowed is 10 "<<endl;
}
catch(NumberRange rang)
{
cout << rang.get_range()<<" is not allowed , you can only enter numbers in range 0-9"<<endl;
}
catch(IntOnly Int)
{
cout << Int.get_Int()<<" can only be an integer"<<endl;
}
catch(NumSum sum)
{
cout <<"sum can only be greater than "<<sum.get_sum()<<" to be allowed"<<endl;
}
*/
| true |
be39e1160ef64d8eaf1e40a93db2e59151fe0d4c | C++ | cotecsz/WayofOffer | /4_队列/4-1_stl_queue_basic_op.cpp | UTF-8 | 818 | 3.671875 | 4 | [] | no_license | //
// Created by Yang Shuangzhen on 2020/7/17.
//
#include <iostream>
#include <queue>
using namespace std;
/*
* STL Queue 基本操作
* 1. Q.empty() 队列是否为空
* 2. Q.front() 队列队首
* 3. Q.back() 队列队尾
* 4. Q.push(x) 将元素x 添加至队尾
* 5. Q.pop() 弹出队首
* 6. Q.size() 队列长度
*
*/
int main(){
queue<int> myQueue;
if (myQueue.empty()){
cout << "Queue is empty!!!" << endl;
}
myQueue.push(5);
myQueue.push(10);
myQueue.push(15);
cout << "myQueue front is " << myQueue.front() << endl;
cout << "myQueue back is " << myQueue.back() << endl;
cout << "myQueue pop front" << endl;
myQueue.pop();
cout << "myQueue size is " << myQueue.size() << endl;
return 0;
}
| true |
861ff7b8275a9dc85c31e41608b6d33740981ed1 | C++ | MusubiKamishiro/QuickHitShooting | /StageEditer/TestLoader/Target/TargetPosition.cpp | SHIFT_JIS | 3,731 | 2.546875 | 3 | [] | no_license | #include <cmath>
#include "TargetPosition.h"
#include "TargetType.h"
TargetPosition::TargetPosition() : _alphaMax(256)
{
_alpha = 0;
}
TargetPosition::~TargetPosition()
{
}
void TargetPosition::Update(int& wCnt, int& tCnt, const unique_input& input, std::vector<vec_target>& stageData)
{
if (input->IsTrigger(KEY_INPUT_SPACE))
{
tCnt = 0;
wCnt = 0;
Editer::Instance().ChagneState(new TargetType());
return;
}
ChangeWave(wCnt, (int)stageData.size(), input);
ChangeTarget(tCnt, (int)stageData[wCnt].size(), input);
DataConfig(wCnt, tCnt, input, stageData);
}
void TargetPosition::DataConfig(const int& wCnt, const int& tCnt,const unique_input& input, std::vector<vec_target>& stageData)
{
if (input->IsMouseTrigger(MOUSE_INPUT_LEFT))
{
Vector2<int> mPos;
GetMousePoint(&mPos.x, &mPos.y);
mPos -= Vector2<int>(_targetSize / 2, _targetSize / 2);
if (CheckTargetRange(mPos))
{
stageData[wCnt][tCnt].pos = mPos;
}
}
}
/// Izuʒu͈͓ł邩̔擾p
bool TargetPosition::CheckTargetRange(const Vector2<int>& pos) const
{
return (pos.x >= 0 && pos.x < Editer::Instance().GetScreenSize().x &&
pos.y >= 96 && pos.y < Editer::Instance().GetScreenSize().y - 100 - (_targetSize / 2));
}
void TargetPosition::Draw(const int& wCnt, const int& tCnt, const std::vector<vec_target> stageData)
{
/// n
SetDrawBlendMode(DX_BLENDMODE_ALPHA, 100);
DrawBox(0, 0, Editer::Instance().GetScreenSize().x, 96,
0xdddddd, true);
DrawBox(0, 96, Editer::Instance().GetScreenSize().x, Editer::Instance().GetScreenSize().y - 100,
0x00ff00, true);
SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 0);
/// ݂̃[h
SetFontSize(48);
_text = "Position Config";
_drawPos.x = 0;
_drawPos.y = 0;
DrawString(_drawPos.x, _drawPos.y, _text.c_str(), 0x228b22);
/// EF[u
_text = "Wave Count";
GetDrawStringSize(&_strSize.x, &_strSize.y, nullptr, _text.c_str(), strlen(_text.c_str()));
_drawPos.x = (Editer::Instance().GetScreenSize().x / 2) - (_strSize.x / 2);
_drawPos.y = 0;
DrawString(_drawPos.x, _drawPos.y, _text.c_str(), 0x00008b);
_text = std::to_string(wCnt + 1) + " / " + std::to_string(stageData.size());
GetDrawStringSize(&_strSize.x, &_strSize.y, nullptr, _text.c_str(), strlen(_text.c_str()));
_drawPos.x = (Editer::Instance().GetScreenSize().x / 2) - (_strSize.x / 2);
_drawPos.y = _strSize.y;
DrawString(_drawPos.x, _drawPos.y, _text.c_str(), 0x00008b);
/// I
_text = "Target Count";
GetDrawStringSize(&_strSize.x, &_strSize.y, nullptr, _text.c_str(), strlen(_text.c_str()));
_drawPos.x = Editer::Instance().GetScreenSize().x - _strSize.x;
_drawPos.y = 0;
DrawString(_drawPos.x, _drawPos.y, _text.c_str(), 0x000000);
_text = std::to_string(tCnt + 1) + " / " + std::to_string(stageData[wCnt].size());
GetDrawStringSize(&_strSize.x, &_strSize.y, nullptr, _text.c_str(), strlen(_text.c_str()));
_drawPos.x = Editer::Instance().GetScreenSize().x - (Editer::Instance().GetScreenSize().x / 10) - (_strSize.x / 2);
_drawPos.y = _strSize.y;
DrawString(_drawPos.x, _drawPos.y, _text.c_str(), 0x000000);
/// SĂ̓I\
for (int i = 0; i < stageData[wCnt].size(); ++i)
{
DrawExtendGraph(stageData[wCnt][i].pos.x, stageData[wCnt][i].pos.y,
stageData[wCnt][i].pos.x + _targetSize, stageData[wCnt][i].pos.y + _targetSize,
_imageID[stageData[wCnt][i].type], true);
}
/// ݒ蒆̍W
_alpha = (_alpha + 10) % (_alphaMax * 2);
SetDrawBlendMode(DX_BLENDMODE_ALPHA, abs(_alpha - _alphaMax));
DrawCircle(stageData[wCnt][tCnt].pos.x + _targetSize / 2,
stageData[wCnt][tCnt].pos.y + _targetSize / 2, _targetSize / 2,
0xffffd1, true);
SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 0);
} | true |
9520b54044bd4392cf6975e77737c2a01674f6c1 | C++ | araluce/Proyecto_Imagenes | /src/negativo.cpp | UTF-8 | 883 | 3.28125 | 3 | [] | no_license | /**
* @file negativo.cpp
* @brief Fichero principal que se ocupa de recoger información para cambiar una imagen a negativo
*
* Permite pasar a negativo imágenes de tipo PGM
*
*/
#include <iostream>
#include <stdlib.h>
#include "imagen.h"
#include "transformar.h"
using namespace std;
int main( int argc, char *argv[] ){
if( argc != 3 ){
cerr << "\n\aError al insertar argumentos.Lea las instrucciones de uso:";
cout << "\n Orden: <programa> <nombre_imagen_entrada.pgm> <nombre_imagen_salida.pgm>";
exit(1);
}
else{
Imagen imagen;
if( imagen.LeerImagen( argv[1] ) )
Negativo( imagen );
else{
cerr << "\n\aError en la lectura" << endl;
exit(2);
}
if( !imagen.EscribirImagen( argv[2] ) ){
cerr << "\n\aError en la escritura" << endl;
exit(3);
}
}
return 0;
}
/* Fin Fichero: negativo.cpp */
| true |
4d78ddc178e528ba5ce1002e3fc988ff5e0c56fb | C++ | tycho/crisscross | /source/crisscross/compare.h | UTF-8 | 1,898 | 2.953125 | 3 | [] | no_license | /*
* CrissCross
* A multi-purpose cross-platform library.
*
* A product of Uplink Laboratories.
*
* (c) 2006-2022 Steven Noonan.
* Licensed under the New BSD License.
*
*/
#ifndef __included_cc_compare_h
#define __included_cc_compare_h
#include <crisscross/cc_attr.h>
#include <crisscross/debug.h>
namespace CrissCross
{
namespace Data
{
/*! \brief Function for generic data comparison. */
/*!
* Can compare any class with the less-than and greater-than operators, as well as C-style strings.
* \param _first The item to compare to _second. Must have comparison operators > and < implemented.
* \param _second The item to compare to _first. Must have comparison operators > and < implemented.
* \return 0 if the items are equal, -1 if _first is less than _second, and 1 if _first is greater than _second.
*/
template <class T>
__inline int Compare(T const &_first, T const &_second)
{
if (_first < _second)
return -1;
else if (_first > _second)
return 1;
else
return 0;
}
/*! \brief C-style string CrissCross::Data::Compare function. */
template <>
int Compare<char *>(char *const &_first, char *const &_second);
/*! \brief C-style string CrissCross::Data::Compare function. */
template <>
int Compare<const char *>(const char *const &_first, const char *const &_second);
/*! \brief An STL-compatible comparator class which makes use of Compare */
template <class T>
class LessThanComparator
{
public:
bool operator()(T const &_first, T const &_second) const
{
return Compare<T>(_first, _second) < 0;
}
};
/*! \brief An STL-compatible comparator class which makes use of Compare */
template <class T>
class GreaterThanComparator
{
public:
bool operator()(T const &_first, T const &_second) const
{
return Compare<T>(_first, _second) > 0;
}
};
}
}
#endif
| true |
e0724be82143872f5776b42add611137178c078e | C++ | leomaurodesenv/contest-codes | /contests/uri/uri-1129.cpp | UTF-8 | 1,163 | 2.765625 | 3 | [
"MIT"
] | permissive | #include <stdlib.h>
#include <stdio.h>
using namespace std;
int main(int argc, char *argv[])
{
int a[5];
int n, resp, error;
char r[6] = {'A', 'B', 'C', 'D', 'E', '*'};
// <= 127 preto
// > 127 branco
while(1){
scanf("%d", &n);
if(n == 0)
break;
for(int c=0; c<n; c++){
for(int i=0; i<5; i++){
scanf("%d", &a[i]);
}
resp = 5;
error = 0;
for(int i=0; i<5; i++){
if(a[i] <= 127){
a[i] = 1;
for(int j=0; j<i; j++){
if(resp == j)
error = 1;
}
resp = i;
}
else
a[i] = 0;
//printf("A:%d \n", a[i]);
}
//printf("Error:%d \n", error);
//printf("R:%d \n", resp);
if(error == 1){
resp = 5;
}
printf("%c\n", r[resp]);
}
}
//system("pause");
return 0;
}
| true |
f9a1a9f4757d00b1184670eec7c24ec1ef529eb8 | C++ | ymahinc/MyTypon | /sources/layers/movelayerundocommand.cpp | UTF-8 | 637 | 2.78125 | 3 | [] | no_license | #include "movelayerundocommand.h"
#include <QDebug>
MoveLayerUndoCommand::MoveLayerUndoCommand(LayersStack *stack, Layer *layer, bool up)
: m_stack(stack), m_layer(layer), m_up(up){
if ( up )
setText(QObject::tr("Move %1 layer up").arg(layer->name()));
else
setText(QObject::tr("Move %1 layer down").arg(layer->name()));
}
void MoveLayerUndoCommand::undo(){
if ( m_up )
m_stack->moveLayerDown(m_layer);
else
m_stack->moveLayerUp(m_layer);
}
void MoveLayerUndoCommand::redo(){
if ( m_up )
m_stack->moveLayerUp(m_layer);
else
m_stack->moveLayerDown(m_layer);
}
| true |
635da031b36d1d6644928826c0204e25911673d3 | C++ | aman1228/LeetCode | /Algorithms/split-array-with-equal-sum.cpp | UTF-8 | 1,658 | 3.703125 | 4 | [] | no_license | // 548. Split Array with Equal Sum
// https://leetcode.com/problems/split-array-with-equal-sum/
/*
Given an array with n integers, you need to find if there are triplets (i, j, k) which satisfies following conditions:
0 < i, i + 1 < j, j + 1 < k < n - 1
Sum of subarrays (0, i - 1), (i + 1, j - 1), (j + 1, k - 1) and (k + 1, n - 1) should be equal.
where we define that subarray (L, R) represents a slice of the original array starting from the element indexed L to the element indexed R.
Example:
Input: [1,2,1,2,1,2,1]
Output: True
Explanation:
i = 1, j = 3, k = 5.
sum(0, i - 1) = sum(0, 0) = 1
sum(i + 1, j - 1) = sum(2, 2) = 1
sum(j + 1, k - 1) = sum(4, 4) = 1
sum(k + 1, n - 1) = sum(6, 6) = 1
Note:
1 <= n <= 2000.
Elements in the given array will be in range [-1,000,000, 1,000,000].
*/
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
bool splitArray(vector<int>& nums) {
int sz = nums.size(), i, j, k, a, b;
vector<int> A;
A.push_back(0);
unordered_set<int> B;
for (const auto & i : nums) {
A.push_back(A.back() + i);
}
for (j = 3; j <= sz - 4; ++j) {
B.clear();
for (i = 1; i <= j - 2; ++i) {
a = A[i] - A[0];
b = A[j] - A[i + 1];
if (a == b) {
B.insert(a);
}
}
for (k = j + 2; k <= sz - 2; ++k) {
a = A[k] - A[j + 1];
b = A[sz] - A[k + 1];
if (a == b and B.count(a)) {
return true;
}
}
}
return false;
}
};
int main(void) {
Solution solution;
vector<int> nums;
bool result;
nums = {1, 2, 1, 2, 1, 2, 1};
result = solution.splitArray(nums);
cout << boolalpha << result << '\n';
return 0;
} | true |
b57c18d594dd722681a080ab99ec802432733492 | C++ | JoanK11/FIB-PRO1-Programacio-I | /X50401_en-Null_triplets.cc | UTF-8 | 547 | 3.03125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int n, total = 0;
cin >> n;
for (int i = 0; i < n; ++i) { // Nombre de casos
int times, last, previous, next, counter = 0;
cin >> times >> last >> previous;
for (int j = 2; j < times; ++j) { // Nombres per cada cas
cin >> next;
if (last + next == previous)
++counter, ++total;
last = previous, previous = next;
}
cout << counter << endl;
}
cout << "Total: " << total << endl;
}
| true |
8c5b4404fac51431bb797aec7251c6216852063c | C++ | chrzhang/abc | /geometry/rectangleArea/main.cpp | UTF-8 | 984 | 3.6875 | 4 | [] | no_license | #include <iostream>
#include <cassert>
#include <algorithm>
// Find the combined area of two rectangles
// The lower left of the first rectangle is at (A,B), the upper right at (C,D)
// The lower left of the other rectangle is at (E,F), the upper right at (G,H)
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
// Add the areas of the rectangles and subtract the overlap
int a1 = (C - A) * (D - B);
int a2 = (G - E) * (H - F);
int sum = a1 + a2;
if (a1 && a2 && !((G <= A) || (E >= C) || (F >= D) || (H <= B))) {
sum -= (std::min(C, G) - std::max(A, E)) *
(std::min(H, D) - std::max(F, B));
}
return sum;
}
int main() {
assert(computeArea(-3, 0, 3, 4, 0, -1, 9, 2) == 6 * 4 + 9 * 3 - 6);
assert(computeArea(0, -1, 9, 2, -3, 0, 3, 4) == 6 * 4 + 9 * 3 - 6);
assert(computeArea(0, 0, 0, 0, 0, -1, 9, 2) == 9 * 3);
assert(computeArea(-1, -1, 1, 1, -1, -1, 1, 1) == 2 * 2);
return 0;
}
| true |
8c8658084de83e04b72bbe56cba5d863aefbbea8 | C++ | theanarkh/read-just-0.1.4-code | /modules/encode/encode.cc | UTF-8 | 8,749 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "encode.h"
size_t just::encode::hex_decode(char* buf,
size_t len,
const char* src,
const size_t srcLen) {
size_t i;
for (i = 0; i < len && i * 2 + 1 < srcLen; ++i) {
unsigned a = unhex(src[i * 2 + 0]);
unsigned b = unhex(src[i * 2 + 1]);
if (!~a || !~b)
return i;
buf[i] = (a << 4) | b;
}
return i;
}
size_t just::encode::base64_decoded_size(const char* src, size_t size) {
if (size == 0)
return 0;
if (src[size - 1] == '=')
size--;
if (size > 0 && src[size - 1] == '=')
size--;
return base64_decoded_size_fast(size);
}
bool just::encode::base64_decode_group_slow(char* dst, const size_t dstlen,
const char* src, const size_t srclen,
size_t* const i, size_t* const k) {
uint8_t hi;
uint8_t lo;
#define V(expr) \
for (;;) { \
const uint8_t c = src[*i]; \
lo = unbase64(c); \
*i += 1; \
if (lo < 64) \
break; /* Legal character. */ \
if (c == '=' || *i >= srclen) \
return false; /* Stop decoding. */ \
} \
expr; \
if (*i >= srclen) \
return false; \
if (*k >= dstlen) \
return false; \
hi = lo;
V(/* Nothing. */);
V(dst[(*k)++] = ((hi & 0x3F) << 2) | ((lo & 0x30) >> 4));
V(dst[(*k)++] = ((hi & 0x0F) << 4) | ((lo & 0x3C) >> 2));
V(dst[(*k)++] = ((hi & 0x03) << 6) | ((lo & 0x3F) >> 0));
#undef V
return true; // Continue decoding.
}
size_t just::encode::base64_decode_fast(char* dst, const size_t dstlen,
const char* src, const size_t srclen,
const size_t decoded_size) {
const size_t available = dstlen < decoded_size ? dstlen : decoded_size;
const size_t max_k = available / 3 * 3;
size_t max_i = srclen / 4 * 4;
size_t i = 0;
size_t k = 0;
while (i < max_i && k < max_k) {
const uint32_t v =
unbase64(src[i + 0]) << 24 |
unbase64(src[i + 1]) << 16 |
unbase64(src[i + 2]) << 8 |
unbase64(src[i + 3]);
// If MSB is set, input contains whitespace or is not valid base64.
if (v & 0x80808080) {
if (!base64_decode_group_slow(dst, dstlen, src, srclen, &i, &k))
return k;
max_i = i + (srclen - i) / 4 * 4; // Align max_i again.
} else {
dst[k + 0] = ((v >> 22) & 0xFC) | ((v >> 20) & 0x03);
dst[k + 1] = ((v >> 12) & 0xF0) | ((v >> 10) & 0x0F);
dst[k + 2] = ((v >> 2) & 0xC0) | ((v >> 0) & 0x3F);
i += 4;
k += 3;
}
}
if (i < srclen && k < dstlen) {
base64_decode_group_slow(dst, dstlen, src, srclen, &i, &k);
}
return k;
}
size_t just::encode::base64_decode(char* dst, const size_t dstlen,
const char* src, const size_t srclen) {
const size_t decoded_size = base64_decoded_size(src, srclen);
return base64_decode_fast(dst, dstlen, src, srclen, decoded_size);
}
size_t just::encode::base64_encode(const char* src,
size_t slen,
char* dst,
size_t dlen) {
// We know how much we'll write, just make sure that there's space.
dlen = base64_encoded_size(slen);
unsigned a;
unsigned b;
unsigned c;
unsigned i;
unsigned k;
unsigned n;
static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
i = 0;
k = 0;
n = slen / 3 * 3;
while (i < n) {
a = src[i + 0] & 0xff;
b = src[i + 1] & 0xff;
c = src[i + 2] & 0xff;
dst[k + 0] = table[a >> 2];
dst[k + 1] = table[((a & 3) << 4) | (b >> 4)];
dst[k + 2] = table[((b & 0x0f) << 2) | (c >> 6)];
dst[k + 3] = table[c & 0x3f];
i += 3;
k += 4;
}
if (n != slen) {
switch (slen - n) {
case 1:
a = src[i + 0] & 0xff;
dst[k + 0] = table[a >> 2];
dst[k + 1] = table[(a & 3) << 4];
dst[k + 2] = '=';
dst[k + 3] = '=';
break;
case 2:
a = src[i + 0] & 0xff;
b = src[i + 1] & 0xff;
dst[k + 0] = table[a >> 2];
dst[k + 1] = table[((a & 3) << 4) | (b >> 4)];
dst[k + 2] = table[(b & 0x0f) << 2];
dst[k + 3] = '=';
break;
}
}
return dlen;
}
void just::encode::HexEncode(const FunctionCallbackInfo<Value> &args) {
Isolate *isolate = args.GetIsolate();
Local<Context> context = isolate->GetCurrentContext();
Local<ArrayBuffer> absource = args[0].As<ArrayBuffer>();
std::shared_ptr<BackingStore> source = absource->GetBackingStore();
Local<ArrayBuffer> abdest = args[1].As<ArrayBuffer>();
std::shared_ptr<BackingStore> dest = abdest->GetBackingStore();
int len = source->ByteLength();
if (args.Length() > 2) {
len = args[2]->Uint32Value(context).ToChecked();
}
int off = 0;
if (args.Length() > 3) {
off = args[3]->Uint32Value(context).ToChecked();
}
char* dst = (char*)dest->Data() + off;
size_t bytes = hex_encode((const char*)source->Data(), len,
dst, dest->ByteLength() - off);
args.GetReturnValue().Set(Integer::New(isolate, bytes));
}
void just::encode::HexDecode(const FunctionCallbackInfo<Value> &args) {
Isolate *isolate = args.GetIsolate();
Local<Context> context = isolate->GetCurrentContext();
Local<ArrayBuffer> absource = args[0].As<ArrayBuffer>();
std::shared_ptr<BackingStore> source = absource->GetBackingStore();
Local<ArrayBuffer> abdest = args[1].As<ArrayBuffer>();
std::shared_ptr<BackingStore> dest = abdest->GetBackingStore();
int len = source->ByteLength();
if (args.Length() > 2) {
len = args[2]->Uint32Value(context).ToChecked();
}
int off = 0;
if (args.Length() > 3) {
off = args[3]->Uint32Value(context).ToChecked();
}
char* dst = (char*)dest->Data() + off;
size_t bytes = hex_decode(dst, dest->ByteLength() - off, (const char*)source->Data(), len);
args.GetReturnValue().Set(Integer::New(isolate, bytes));
}
void just::encode::Base64Encode(const FunctionCallbackInfo<Value> &args) {
Isolate *isolate = args.GetIsolate();
Local<Context> context = isolate->GetCurrentContext();
Local<ArrayBuffer> absource = args[0].As<ArrayBuffer>();
std::shared_ptr<BackingStore> source = absource->GetBackingStore();
Local<ArrayBuffer> abdest = args[1].As<ArrayBuffer>();
std::shared_ptr<BackingStore> dest = abdest->GetBackingStore();
int len = source->ByteLength();
if (args.Length() > 2) {
len = args[2]->Uint32Value(context).ToChecked();
}
size_t dlen = base64_encoded_size(len);
size_t bytes = base64_encode((const char*)source->Data(), len,
(char*)dest->Data(), dlen);
args.GetReturnValue().Set(Integer::New(isolate, bytes));
}
void just::encode::Base64Decode(const FunctionCallbackInfo<Value> &args) {
Isolate *isolate = args.GetIsolate();
Local<Context> context = isolate->GetCurrentContext();
Local<ArrayBuffer> absource = args[0].As<ArrayBuffer>();
std::shared_ptr<BackingStore> source = absource->GetBackingStore();
Local<ArrayBuffer> abdest = args[1].As<ArrayBuffer>();
std::shared_ptr<BackingStore> dest = abdest->GetBackingStore();
int len = source->ByteLength();
if (args.Length() > 2) {
len = args[2]->Uint32Value(context).ToChecked();
}
int dlen = dest->ByteLength();
size_t bytes = base64_decode((char*)dest->Data(), dlen, (const char*)source->Data(), len);
args.GetReturnValue().Set(Integer::New(isolate, bytes));
}
void just::encode::Init(Isolate* isolate, Local<ObjectTemplate> target) {
Local<ObjectTemplate> module = ObjectTemplate::New(isolate);
SET_METHOD(isolate, module, "hexEncode", HexEncode);
SET_METHOD(isolate, module, "hexDecode", HexDecode);
SET_METHOD(isolate, module, "base64Encode", Base64Encode);
SET_METHOD(isolate, module, "base64Decode", Base64Decode);
SET_MODULE(isolate, target, "encode", module);
}
| true |
cfd97e75e32620b16e15896778130ff3cf73f425 | C++ | NicoAcosta/utn-ayed | /1er-cuatrimestre/ejercicios/33 MCD/33 MCD/main.cpp | UTF-8 | 729 | 3.375 | 3 | [] | no_license | //
// main.cpp
// 33 MCD
//
// Created by Nico on 12/06/2019.
// Copyright © 2019 Nicolás Acosta. All rights reserved.
//
#include <iostream>
using namespace std;
int mcd(int a, int b) {
int r;
while (1 == 1) {
r = a%b;
if (!r) {
return b;
}
a = b;
b = r;
}
return 0;
}
int main() {
int n1, n2;
do {
do {
cout << "Ingrese dos números:" << endl << endl;
cin >> n1 >> n2;
} while (!n1 || !n2);
cout << endl << "MCD de " << n1 << " y " << n2 << ": " << mcd(n1, n2) << "." << endl << endl;
} while (1 == 1);
return 9;
}
| true |
8b810d1110a89569313e71c8ce49b2191453b4b1 | C++ | studentstuff/rendercore | /Render.cpp | UTF-8 | 786 | 2.59375 | 3 | [] | no_license | #include "Render.h"
namespace Render
{
void RenderQueue::PushRenderObj(RenderObject* robj, glm::mat4 viewProjMat)
{
// TMP : hardcoded GatherRenderOps
RenderOp rop = robj->rop;
rop.MVP = viewProjMat*robj->frame.modelMatrix;
rop.vertexArray = robj->vertexarray;
rop.program = robj->program;
renderOps.push_back(rop);
}
void RenderQueue::Reset()
{
renderOps.clear();
}
void RenderQueue::Render()
{
for (auto& rop : renderOps)
{
Execute(rop, 1);
}
}
void RenderAll(Camera& cam, std::vector<RenderObject*> objects)
{
RenderQueue rq;
for (auto& ro : objects)
{
glm::mat4 viewProjMat = cam.projMat * cam.viewMat;
if (cam.FrustumTest(ro))
{
rq.PushRenderObj(ro, viewProjMat);
}
}
rq.Sort();
rq.Render();
rq.Reset();
}
} | true |
4c5f39e8193a201386af754fedb97b7dd57e55e5 | C++ | clover7kso/Woony-s-Algorithm-WorkSpace | /7193. 승현이의 수학공부/7193. 승현이의 수학공부/main.cpp | UTF-8 | 377 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main(void)
{
int testCase;
cin >> testCase;
for (int t = 0; t < testCase; t++)
{
long long N;
string X;
cin >> N;
cin >> X;
long long result = 0;
for (int i = 0; i < X.length(); i++)
result += (X.at(i) - 48);
result = result % (N - 1);
cout << "#" << t+1 << " " << result << endl;
}
} | true |
7b8380fb7ca55d5b22f1f32b390ea983005b7898 | C++ | TheLurkingCat/TIOJ | /1544.cpp | UTF-8 | 506 | 3.21875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
using namespace std;
int main() {
string str1, str2;
int t;
cin >> t;
while (t--) {
cin >> str1 >> str2;
if (str1.length() > str2.length()) {
cout << "0\n";
} else if (str1.length() < str2.length()) {
cout << "1\n";
} else {
if (str1.compare(str2) > 0) {
cout << "0\n";
} else {
cout << "1\n";
}
}
}
return 0;
}
| true |
e3679884f3d8a2fd8ee998adbfb243024c10de9d | C++ | chandl34/public | /personal/c++/TacticsEditor/LevelMap.h | UTF-8 | 2,730 | 2.546875 | 3 | [] | no_license | /*
* LevelMap.h
* Pirate Tactics
*
* Created by Jonathan Chandler on 2/18/10.
* Copyright 2010 __MyCompanyName__. All rights reserved.
*
*/
#ifndef LEVEL_MAP_H_
#define LEVEL_MAP_H_
#include "Screen.h"
#include "Camera.h"
#include "BlockCursor.h"
#include "Object.h"
class GridBlock;
class LevelMap : public BaseScreen{
public:
LevelMap();
~LevelMap();
void init();
//--- GENERAL ---//
static GridBlock* getBlockByIso(GLshort, GLshort);
static GridBlock* getBlockByPath(GLshort, GLshort);
static GridBlock* getBlockBy3D(GLshort, GLshort);
static GridBlock* getSelectedBlock();
static void moveCursor(GLshort);
//---- DRAW ----//
void draw(bool); // Defined in LevelMapDraw.mm
static void refresh();
//--- CONTROLS ---//
void keyDown(GLshort);
void push(GLshort, const Coord2d<GLshort>&);
void move(GLshort, const Coord2d<GLshort>&);
bool release(GLshort, const Coord2d<GLshort>&);
private:
//--- GENERAL ---//
static Camera camera;
static GridBlock* gridBlock[MAP_BLOCK_X][MAP_BLOCK_Y];
static GridBlock* sBlock; // Selected gridBlock
static BlockCursor cursor;
static void selectBlock(GridBlock*);
GridBlock* getBlockByOffset(GLshort, GLshort) const;
static void centerView(GLshort, GLshort);
//---- DRAW ----//
Coord2d<GLshort> bl; // Previous bottom left corner stored
GLuint** groundStripVert; // Vertical strips of ground, used for faster drawing
GLuint groundStripTexCoord; // Texture coordinates for ground
GLuint staticObjTexVert;
GLuint staticObjTexCoord;
static bool redraw; // Redraw the entire map, if true
static bool store; // Store the map, if true
static bool resort;
GLuint screenTex; // glReadPixels texture of the screen's ground
void* screenData; // Pixel data generated from glReadPixels
ObjectList objList;
void drawWithBuffers(bool); // Fastest form of drawing
void drawWithHalfBlend(bool); // Medium spend drawing - kept for testing purposes
void drawWithFullBlend(bool); // Slow drawing speed - kept for testing purposes
void createScreenTex(); // glReadPixels to store the current screen
void drawScreenTex(); // Draw the previously stored screen glReadPixels data
void drawOverlays(bool);
void drawObjects(bool); // Gather, sort, and draw objects on screen
//--- TOUCH ---//
GLshort touchCount;
Coord2d<GLshort> startPoint[2]; // Where touch started
Coord2d<GLshort> lastPoint[2]; // Where touch ended
bool drag; // If touch is a drag
double actionDelay; // Time it takes for a 'touch' to become a 'press'
double timePushed; // Time touch began
};
#endif
| true |
ced97d5f56e6cfcaa7cede7607058a01b98a3cba | C++ | ComputerScience1-Period-2/program-problem-1-taileanguyen | /displaytext/displaytext/Source.cpp | UTF-8 | 767 | 3.40625 | 3 | [] | no_license | /*
Tailea Nguyen-9/21/17 2nd
Assignment Name: Display Text
Introdution into C++ IDE Visual Studios 2015
Create New Project and Display Text to Console
*/
// Libraries
#include <iostream> //* gives access to cin, cout, endl, <<, >>, boolalpha, noboolalpha
#include <conio.h> //* gives access to _kbhit() for pause()
// Namespaces
using namespace std; //*
// Functions()
void pause() {
cout << "Press any key to continue . . .";
while (!_kbhit());
_getch();
cout << '\n';
}
// MAIN
void main() { // *
char text_l = 'l';
// Display Text
cout << 'H' << 'e' << 'l' << 'l' << 'o' << " World!" << endl;
pause(); // pauses to see the displayed text
// return statment closes the console and ends the program
return;
} | true |
f3369c6108710c5832091a2906453da67e0ff209 | C++ | BreakEngine/Break-0.0 | /inc/Transform.h | UTF-8 | 1,216 | 3 | 3 | [] | no_license | #pragma once
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include "GlobalDefinitions.h"
namespace Break
{
namespace Graphics
{
/**
* \brief reperesents a transformation matrix of an object
* \author Moustapha Saad
*/
class BREAK_API_EX Transform
{
protected:
///transformation matrix
glm::mat4 matrix;
public:
///postion vector
glm::vec3 position;
///rotation quaternion
glm::quat rotation;
///scale vector
glm::vec3 scale;
///default constructor
Transform(const glm::vec3 pos = glm::vec3(0),
const glm::quat rot = glm::quat(),
glm::vec3 scle = glm::vec3(1,1,1));
///copy constructor
Transform(const Transform& val);
///transformation matrix getter
glm::mat4 getMatrix();
/**
* \brief rotates the object around some axis
* \param axis the axis that this object will rotate around it
* \param angle the angle it will rotate in degrees
* \author Moustapha Saad
*/
void rotate(const glm::vec3 axis, float angle);
///moves the object in some direction by some amount
void move(const glm::vec3 dir, float val);
///returns a look at roataion vecto
glm::vec4 getLookAt(glm::vec3 point,glm::vec3 up);
};
}
} | true |
e7211c0756d4e0deade3ea3d51d3442294bf14b1 | C++ | KieranWebber/ROS-Instinct | /ros_instinct_core/include/ros_instinct_core/planner_utility.h | UTF-8 | 2,638 | 3 | 3 | [
"MIT"
] | permissive | #pragma once
#include <instinct/Instinct.h>
#include <iosfwd>
#include <sstream>
/**
* Static utility functions to aid with the operation of the Instinct Planner
*/
class PlannerUtility
{
private:
/**
* Basic alias for string startsWith
*
* @param line String to check against
* @param start Sequence string is required to start with
* @return True if line starts with start
*/
static inline bool startsWith(const std::string& line, const char* start)
{
return line.rfind(start, 0) == 0;
}
public:
/**
* Loads an Instinct plan from text into the provided planner.
*
* Ignores all comments.
* Adapted from https://github.com/rwortham/Instinct-RobotWorld/blob/master/InstinctRobotWorld.cpp
*
* @param pPlan Planner to load the plan into
* @param pNames Names buffer array - Must be precreated large enough to avoid an overflow
* @param planText Plan file as a text string separated with newlines
* @param bufferSize Size of the buffer to use when receiving planner loading messages
*/
static void loadPlan(Instinct::CmdPlanner* pPlan, Instinct::Names* pNames, const char* planText,
int bufferSize = 100)
{
char msgBuffer[bufferSize];
std::stringstream planStream(planText);
std::string planLine;
while (std::getline(planStream, planLine))
{
// Ignore comments or empty lines
if (planLine.length() == 0 || startsWith(planLine, "//"))
{
continue;
}
// If the line still has a carriage return remove it
if (planLine.back() == '\r')
{
planLine.pop_back();
}
if (startsWith(planLine, "PLAN"))
{
std::string commandContents = planLine.substr(5);
// c_str is null terminated by default (C++11)
if (!(pPlan->executeCommand(commandContents.c_str(), msgBuffer, sizeof(msgBuffer))))
{
throw "Error executing command!";
}
}
else if (startsWith(planLine, "PELEM"))
{
char nameBuffer[20];
unsigned int uiID;
if (sscanf(planLine.c_str(), "PELEM %[^=]=%u", nameBuffer, &uiID) == 2)
{
pNames->addElementName(uiID, nameBuffer);
}
else
{
throw "Invalid named element format!";
}
}
}
}
}; | true |
8f18f1ad8967635cd42da72caac0edf6a840dbdc | C++ | Jinsab/Forest | /숫자 합치기.cpp | UTF-8 | 329 | 2.84375 | 3 | [] | no_license | #include <stdio.h>
int i, n, arr[1000], *p, sum, x=1, t=0;
input()
{
p=arr;
scanf("%d", &n);
for(i=1; i<=n; i++)
{
scanf("%d", p+i);
t++;
}
}
process()
{
for(i=1; i<=n; i++)
{
sum += *(p+t)*x;
x = x*10;
t--;
}
}
output()
{
printf("%d", sum);
}
main()
{
input();
process();
output();
return 0;
}
| true |
15d71c44ea94218b953b78f1c2d9e63a597c2efd | C++ | foxostro/PinkTopaz | /src/include/Renderer/OpenGL/CommandQueue.hpp | UTF-8 | 2,121 | 3.234375 | 3 | [
"MIT"
] | permissive | //
// CommandQueue.hpp
// PinkTopaz
//
// Created by Andrew Fox on 2/24/17.
//
//
#ifndef CommandQueue_hpp
#define CommandQueue_hpp
#include "Renderer/OpenGL/OpenGLException.hpp"
#include <vector>
#include <mutex>
#include <thread>
#include <string>
#include <functional>
#include <spdlog/spdlog.h>
// Exception for when the command queue attempts to execute on the wrong thread.
class CommandQueueInappropriateThreadOpenGLException : public OpenGLException
{
public:
CommandQueueInappropriateThreadOpenGLException()
: OpenGLException("This command queue can only be executed on the " \
"thread on which it was constructed. This is " \
"expected to be the OpenGL thread.")
{}
};
// Queues OpenGL API calls to be made at a later time on the proper thread.
// The OpenGL API must only be accessed from a blessed render thread. To fit
// this into the modern world of multithreaded applications, we use the
// CommandQueue to queue up commands to be run on that thread later.
class CommandQueue
{
public:
CommandQueue(std::shared_ptr<spdlog::logger> log);
~CommandQueue() = default;
// Cancel all tasks with the specified ID. Cancelled tasks are simply never
// executed. Once a task begins executing, it cannot be cancelled.
void cancel(unsigned id);
// Immediately execute all commands in the command queue.
void execute();
// Add a task to the command queue for later execution.
// The specified ID allows the task to be cancelled later via cancel().
void enqueue(unsigned id, const std::string &label, std::function<void()> &&task);
// Add a queue to the command queue for later execution.
void enqueue(CommandQueue &otherQueue);
private:
std::thread::id _mainThreadId;
std::mutex _queueLock;
// The queue stores information about the task to execute.
struct Task
{
unsigned id;
std::string label;
std::function<void()> fn;
};
typedef std::vector<Task> Queue;
Queue _queue;
std::shared_ptr<spdlog::logger> _log;
};
#endif /* CommandQueue_hpp */
| true |
3cb256512cfa67375e7fdc428411fe79bb07df91 | C++ | Raymenes/Rui_Zeng_Portfolio | /Tower_Defense/TowerDefense/Source/CannonTower.cpp | UTF-8 | 1,026 | 2.515625 | 3 | [] | no_license | //
// CannonTower.cpp
// Game-mac
//
// Created by Rui Zeng on 10/3/15.
// Copyright © 2015 Sanjay Madhav. All rights reserved.
//
#include "CannonTower.hpp"
#include "Game.h"
#include "Math.h"
#include "CannonBall.hpp"
IMPL_ACTOR(CannonTower, Tower);
CannonTower::CannonTower(Game& game)
:Tower(game)
{
auto mesh = game.GetAssetCache().Load<Mesh>("Meshes/Cannon.itpmesh2");
mCannon = Actor::Spawn(mGame);
mMeshComponent = MeshComponent::Create(*mCannon);
mCannon->AddComponent(mMeshComponent);
mMeshComponent->SetMesh(mesh);
TimerHandle th;
mGame.GetGameTimerManager().SetTimer(th, this, &CannonTower::AttackEnemy, 2.0f, true);
}
void CannonTower::AttackEnemy()
{
Enemy* target = mGame.GetWorld().GetClosestEnemy(GetPosition(), 150.0f);
if (target != nullptr) {
float angle = ComputAngleToTarget(*target);
mCannon->SetRotation(angle);
auto ball = CannonBall::Spawn(mGame);
ball->SetPosition(GetPosition());
ball->SetRotation(angle);
}
}
| true |
1084148d1d3112e144f072ce05df63593f80662b | C++ | serge-sans-paille/pythran | /pythran/pythonic/numpy/atleast_3d.hpp | UTF-8 | 2,583 | 2.84375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | #ifndef PYTHONIC_NUMPY_ATLEAST3D_HPP
#define PYTHONIC_NUMPY_ATLEAST3D_HPP
#include "pythonic/include/numpy/atleast_3d.hpp"
#include "pythonic/numpy/asarray.hpp"
PYTHONIC_NS_BEGIN
namespace numpy
{
template <class T>
typename std::enable_if<
types::is_dtype<T>::value,
types::ndarray<T, types::pshape<std::integral_constant<long, 1>,
std::integral_constant<long, 1>,
std::integral_constant<long, 1>>>>::type
atleast_3d(T t)
{
return {types::pshape<std::integral_constant<long, 1>,
std::integral_constant<long, 1>,
std::integral_constant<long, 1>>(),
t};
}
template <class T>
auto atleast_3d(T const &t) -> typename std::enable_if<
(!types::is_dtype<T>::value) && (T::value == 1),
types::ndarray<typename T::dtype,
types::pshape<std::integral_constant<long, 1>,
typename std::tuple_element<
0, typename T::shape_t>::type,
std::integral_constant<long, 1>>>>::type
{
auto r = asarray(t);
return r.reshape(
types::pshape<std::integral_constant<long, 1>,
typename std::tuple_element<0, typename T::shape_t>::type,
std::integral_constant<long, 1>>(
std::integral_constant<long, 1>(), r.template shape<0>(),
std::integral_constant<long, 1>()));
}
template <class T>
auto atleast_3d(T const &t) -> typename std::enable_if<
(!types::is_dtype<T>::value) && (T::value == 2),
types::ndarray<
typename T::dtype,
types::pshape<
typename std::tuple_element<0, typename T::shape_t>::type,
typename std::tuple_element<1, typename T::shape_t>::type,
std::integral_constant<long, 1>>>>::type
{
auto r = asarray(t);
return r.reshape(
types::pshape<typename std::tuple_element<0, typename T::shape_t>::type,
typename std::tuple_element<1, typename T::shape_t>::type,
std::integral_constant<long, 1>>(
r.template shape<0>(), r.template shape<1>(),
std::integral_constant<long, 1>()));
}
template <class T>
auto atleast_3d(T const &t) ->
typename std::enable_if<(!types::is_dtype<T>::value) && T::value >= 3,
decltype(asarray(t))>::type
{
return asarray(t);
}
}
PYTHONIC_NS_END
#endif
| true |
9b370d2c99df556e102778e48c92d0d49f8d96d0 | C++ | boulayb/-EPITECH-2-Plazza | /includes/Log.hpp | UTF-8 | 238 | 2.5625 | 3 | [] | no_license | #ifndef LOG_HPP
#define LOG_HPP
#include <string>
#include <fstream>
class Log
{
public:
Log(std::string const &pathToFile);
~Log();
void writeToFile(std::string const &line);
private:
std::fstream _file;
};
#endif
| true |
31b234a0ce90130ddd8f328a88f5ed4810af057a | C++ | bluddy/K3-Core | /runtime/cpp/dataspace/SortedDS.hpp | UTF-8 | 3,031 | 2.953125 | 3 | [] | no_license | #include <set>
#include <algorithm>
namespace K3 {
template <typename Elem>
class SortedDS : public StlDS<Elem, std::multiset> {
// Iterator Types
typedef typename std::multiset<Elem>::iterator iterator_type;
typedef typename std::multiset<Elem>::const_iterator const_iterator_type;
public:
SortedDS(Engine * eng) : StlDS<Elem, std::multiset>(eng) {}
template<typename Iterator>
SortedDS(Engine * eng, Iterator start, Iterator finish)
: StlDS<Elem,std::multiset>(eng,start,finish) {}
SortedDS(const SortedDS& other) : StlDS<Elem,std::multiset>(other) {}
SortedDS(StlDS<Elem,std::multiset> other) : StlDS<Elem,std::multiset>(other) {}
SortedDS(std::multiset<Elem> container) : StlDS<Elem, std::multiset>(container) {}
typedef StlDS<Elem, std::multiset> super;
// Need to convert from StlDS to SortedDS
template<typename NewElem>
SortedDS<NewElem> map(F<NewElem(Elem)> f) {
StlDS<NewElem, std::multiset> s = super::map(f);
return SortedDS<NewElem>(s);
}
SortedDS filter(F<bool(Elem)> pred) {
super s = super::filter(pred);
return SortedDS(s);
}
std::tuple< SortedDS, SortedDS > split() {
tuple<super, super> tup = super::split();
SortedDS ds1 = SortedDS(get<0>(tup));
SortedDS ds2 = SortedDS(get<1>(tup));
return std::make_tuple(ds1, ds2);
}
SortedDS combine(SortedDS other) const {
super s = super::combine(other);
return SortedDS(s);
}
std::shared_ptr<Elem> min() {
std::multiset<Elem> x = this->getContainer();
auto it = std::min_element(x.begin(), x.end());
std::shared_ptr<Elem> result = nullptr;
if (it != x.end()) {
result = make_shared<Elem>(*it);
}
return result;
}
std::shared_ptr<Elem> max() {
std::multiset<Elem> x = this->getContainer();
auto it = std::max_element(x.begin(), x.end());
std::shared_ptr<Elem> result = nullptr;
if (it != x.end()) {
result = make_shared<Elem>(*it);
}
return result;
}
std::shared_ptr<Elem> lowerBound(Elem e) {
std::multiset<Elem> x = this->getContainer();
auto it = std::lower_bound(x.begin(), x.end(), e);
std::shared_ptr<Elem> result = nullptr;
if (it != x.end()) {
result = make_shared<Elem>(*it);
}
return result;
}
std::shared_ptr<Elem> upperBound(Elem e) {
std::multiset<Elem> x = this->getContainer();
auto it = std::upper_bound(x.begin(), x.end(), e);
std::shared_ptr<Elem> result = nullptr;
if (it != x.end()) {
result = make_shared<Elem>(*it);
}
return result;
}
SortedDS slice(Elem a, Elem b) {
std::multiset<Elem> x = this->getContainer();
SortedDS<Elem> result = SortedDS<Elem>(this->getEngine());
for (Elem e : x) {
if (e >= a && e <= b) {
result.insert(e);
}
if (e > b) {
break;
}
}
return result;
}
};
}
| true |
a5d30ad83be1ec16a5815ea1f2275e0257957cb3 | C++ | 0x3337/iitu-contester | /problems/week-11/1105.cpp | UTF-8 | 324 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
string str;
getline(cin, str);
str.erase(unique(str.begin(), str.end()), str.end());
if(str[0] == ' ') str.erase(str.begin());
if(str[str.length() - 1] == ' ') str.erase(str.end() - 1);
cout << str << '\n';
return 0;
} | true |
a7b6c645c076ccf24ae5ec25a7465e194b01d0c5 | C++ | vincentlai97/SP2-11 | /Application/Source/MySceneInitCollisionBox.cpp | UTF-8 | 2,942 | 2.640625 | 3 | [] | no_license | #include "MyScene.h"
void MyScene::InitCollisionBox()
{
CollisionBox* collisionBox;
//Exterior Hitbox
collisionBox = new CollisionBox(Vector3(0, -0.5, 400), 1800, 1, 1800); //Bottom
v.push_back(collisionBox);
collisionBox = new CollisionBox(Vector3(0, 500, 1000), 200, 200, 200); //Front
v.push_back(collisionBox);
//Interior Hitbox
collisionBox = new CollisionBox(Vector3(0, 115, 300.5), 800, 90, 1); // Front Top
v.push_back(collisionBox);
collisionBox = new CollisionBox(Vector3(235, 80, 300.5), 330, 160, 1); // Front Right
v.push_back(collisionBox);
collisionBox = new CollisionBox(Vector3(-235, 80, 300.5), 330, 160, 1); // Front Left
v.push_back(collisionBox);
collisionBox = new CollisionBox(Vector3(0, 80, -300.5), 800, 160, 1); // Back
v.push_back(collisionBox);
collisionBox = new CollisionBox(Vector3(0, -0.5, 0), 800, 1, 600); // Bottom
v.push_back(collisionBox);
collisionBox = new CollisionBox(Vector3(0, 160.5, 0), 800, 1, 600); // Top
v.push_back(collisionBox);
collisionBox = new CollisionBox(Vector3(0, 80, 0), 800, 20, 600); // Middle
v.push_back(collisionBox);
collisionBox = new CollisionBox(Vector3(-400.5, 80, 0), 1, 160, 600); // Left
v.push_back(collisionBox);
collisionBox = new CollisionBox(Vector3(400.5, 80, 0), 1, 160, 600); // Right
v.push_back(collisionBox);
collisionBox = new CollisionBox(Vector3(80, 10, 295), 10, 20, 10); // Fence
v.push_back(collisionBox);
collisionBox = new CollisionBox(Vector3(50, 10, 235), 70, 20, 10); // Fence
v.push_back(collisionBox);
collisionBox = new CollisionBox(Vector3(-50, 10, 235), 70, 20, 10); // Fence
v.push_back(collisionBox);
collisionBox = new CollisionBox(Vector3(-80, 10, 270), 10, 20, 60); // Fence
v.push_back(collisionBox);
doorArea = CollisionBox(Vector3(0, 35, 300), 140, 70, 100);
fenceArea = CollisionBox(Vector3(0, 35, 265), 150, 70, 70);
//Elevator Hitbox
collisionBox = new CollisionBox(Vector3(-370, 32.5, 170), 50, 35, 10); //Elevator on Level One
v.push_back(collisionBox);
collisionBox = new CollisionBox(Vector3(-370, 32.5, 130), 50, 35, 10);
v.push_back(collisionBox);
collisionBox = new CollisionBox(Vector3(-370, 112.5, 170), 50, 35, 10); //Elevator on Level Two
v.push_back(collisionBox);
collisionBox = new CollisionBox(Vector3(-370, 112.5, 130), 50, 35, 10);
v.push_back(collisionBox);
elevatorUp = CollisionBox(Vector3(-380, 10, 150), 40, 20, 30);
elevatorDown = CollisionBox(Vector3(-380, 100, 150), 40, 20, 30);
elevatorArea = CollisionBox(Vector3(-360, 80, 150), 80, 160, 30);
//Escalator Hitbox
collisionBox = new CollisionBox(Vector3(-290, 45, 260), 140, 90, 80); // Travelator
v.push_back(collisionBox);
collisionBox = new CollisionBox(Vector3(-290, 45, 260), 160, 150, 20); // Travelator Handle
v.push_back(collisionBox);
travelatorUp.push_back(CollisionBox(Vector3(-290, 45, 280), 150, 90, 20));
travelatorDown.push_back(CollisionBox(Vector3(-295, 50, 240), 150, 90, 20));
} | true |
bef7bb1dd0d1d4667756642ad74a2726a61911fb | C++ | kberba/zoo-tycoon | /Penguin.hpp | UTF-8 | 1,013 | 3.28125 | 3 | [] | no_license | /*********************************************************************
** Author: Karen Berba
** Date: 1/27/19
** Description:
Header for Penguin class
Inherits from Animal class. Has a default constructor and a custom constructor that takes in an integer age.
NOTES:
- Penguin cost $1,000
- Penguins have 5 babies
- Penguins have a feeding cost that is the same as the base cost
- A penguin’s payoff per day is 10% of their cost per animal
*********************************************************************/
#ifndef PENGUIN_HPP
#define PENGUIN_HPP
#include "Animal.hpp"
/*
source(s):
https://www.learncpp.com/cpp-tutorial/114-constructors-and-initialization-of-derived-classes/
https://stackoverflow.com/questions/7405740/how-can-i-initialize-base-class-member-variables-in-derived-class-constructor
*/
// Penguin class declaration - child class of Animal
class Penguin : public Animal {
public:
// default constructor
Penguin();
// custom constructor
Penguin(int pAge);
};
#endif
| true |
517c1d49ec62367e68425d461c5454146058b697 | C++ | phoenixGit228/cpp | /cpp_primer_plus_6th/chapter04/p4-13-1.cpp | UTF-8 | 839 | 3.421875 | 3 | [] | no_license | // ///////////////////////////////////////////////////////
// 名称: 4.13.cpp
// 描述:
// 日期: 2021-06-17 09:27:27
// ///////////////////////////////////////////////////////
#include <iostream>
#include <string>
int main()
{
using namespace std;
cout << "What is your fist name? ";
const int ArSize = 80;
char first_name[ArSize];
cin.getline(first_name, ArSize);
cout << "What is your last name? ";
char last_name[ArSize];
cin.get(last_name,ArSize).get();
cout << "What letter grade do you deserve? ";
char grade;
cin >> grade;
cout << "What is your age? ";
int age;
cin >> age;
cout << "Name: " << last_name << ", " << first_name << endl;
cout << "Grade: " << char(grade + 1) << endl;
cout << "Age: " << age << endl;
return 0;
}
| true |
c22bc566af550399b4b1d7ef95ff1e8d61c1acbc | C++ | hclife/code-base | /lang/cpp/vtable1.cpp | UTF-8 | 1,548 | 3.578125 | 4 | [] | no_license | #include <iostream>
#include <cstdio>
typedef void (*fun_pointer)(void);
using namespace std;
class Test {
public:
Test() {
cout<<"Test()."<<endl;
}
virtual void print() {
cout<<"Test::Virtual void print1()."<<endl;
}
virtual void print2() {
cout<<"Test::virtual void print2()."<<endl;
}
};
class TestDrived:public Test {
public:
static int var;
TestDrived() {
cout<<"TestDrived()."<<endl;
}
virtual void print() {
cout<<"TestDrived::virtual void print1()."<<endl;
}
virtual void print2() {
cout<<"TestDrived::virtual void print2()."<<endl;
}
void GetVtblAddress() {
cout<<"vtbl address:"<<(int*)this<<endl;
}
void GetFirstVtblFunctionAddress() {
cout<<"First vbtl funtion address:"<<
(int*)*(int*)this+0 << endl;
}
void GetSecondVtblFunctionAddress() {
cout<<"Second vbtl funtion address:"<<
(int*)*(int*)this+1 << endl;
}
void CallFirstVtblFunction() {
fun = (fun_pointer)* ( (int*) *(int*)this+0 );
cout<<"CallFirstVbtlFunction:"<<endl;
fun();
}
void CallSecondVtblFunction() {
fun = (fun_pointer)* ( (int*) *(int*)this+1 );
cout<<"CallSecondVbtlFunction:"<<endl;
fun();
}
private:
fun_pointer fun;
};
int TestDrived::var = 3;
int main() {
cout<<"sizeof(int):"<<sizeof(int)<<
"sizeof(int*)"<<sizeof(int*)<<endl;
fun_pointer fun = NULL;
TestDrived a;
a.GetVtblAddress();
cout<<"The var's address is:"<<&TestDrived::var<<endl;
a.GetFirstVtblFunctionAddress();
a.GetSecondVtblFunctionAddress();
a.CallFirstVtblFunction();
a.CallSecondVtblFunction();
return 0;
}
| true |
9ebcdb11275e185bc00031c774f4758c8e965faa | C++ | baepiff/checkersLite | /CheckersLite/Game.cpp | UTF-8 | 1,620 | 3.171875 | 3 | [] | no_license | #include "stdafx.h"
#include "Game.h"
Game::Game(void) {
this->currentPlayerColor = PIECE_COLOR::BLACK;
this->ended = false;
this->view = ViewFactory::createView(VIEW_TYPE::CONSOLE_VIEW);
this->io = IOFactory::createIO(IO_TYPE::CONSOLE_IO);
this->blackPlayer = PlayerFactory::createPlayer(PLAYER_TYPE::COMPUTER, this->view);
this->whitePlayer = PlayerFactory::createPlayer(PLAYER_TYPE::HUMAN, this->view);
}
Game::~Game(void) {
delete this->view;
delete this->io;
delete this->blackPlayer;
delete this->whitePlayer;
}
void Game::start() {
view->draw();
startGame();
}
void Game::startGame() {
int count = 0;
while(ended == false) {
IPlayer* player = currentPlayerColor == PIECE_COLOR::WHITE ? whitePlayer : blackPlayer;
bool result = player->play();
if (!result) break;
currentPlayerColor = currentPlayerColor == PIECE_COLOR::WHITE ? PIECE_COLOR::BLACK : PIECE_COLOR::WHITE;
if (gameFinished()) ended = true;
}
printResult();
system("pause");
}
bool Game::gameFinished() {
if (Board::getInstance()->getBlackCount() == 0 ||
Board::getInstance()->getBlackCount() == 0 ) {
return true;
}
return false;
}
void Game::end() {
ended = true;
}
void Game::printResult() {
uint blackNum = Board::getInstance()->getBlackCount();
uint whiteNum = Board::getInstance()->getWhiteCount();
ostringstream message;
message << "BLACK : " << blackNum << " WHITE : " << whiteNum << "\n";
if (blackNum > whiteNum) message << "BLACK PLAYER WIN!!!\n";
else if (blackNum < whiteNum) message << "WHITE PLAYER WIN!!!\n";
else message << "THE GAME IS DRAW!!!\n";
io->showMessage(message.str());
} | true |
55f12dc53937b03def1c62127757aef4c2809696 | C++ | Breush/lava | /examples/sill/vr-sandbox.cpp | UTF-8 | 3,454 | 2.859375 | 3 | [
"MIT"
] | permissive | /**
* Shows the different integrated meshes.
*/
#include "./ashe.hpp"
using namespace lava;
int main(void)
{
ashe::Application app;
auto& engine = app.engine();
// Ground
{
auto& entity = engine.make<sill::Entity>();
auto& meshComponent = entity.make<sill::MeshComponent>();
sill::makers::planeMeshMaker({10, 10})(meshComponent);
entity.make<sill::ColliderComponent>();
entity.get<sill::ColliderComponent>().addInfinitePlaneShape();
entity.get<sill::PhysicsComponent>().dynamic(false);
}
// Spawning random cubes
std::vector<sill::Entity*> cubes;
for (auto i = 0u; i < 10u; ++i) {
auto cubeSize = (2 + rand() % 20) / 40.f;
auto& cubeEntity = engine.make<sill::Entity>();
auto& cubeMeshComponent = cubeEntity.make<sill::MeshComponent>();
sill::makers::boxMeshMaker(cubeSize)(cubeMeshComponent);
cubeEntity.get<sill::TransformComponent>().translate({(rand() % 5) / 10.f - 0.2f, // X
(rand() % 5) / 10.f - 0.2f, // Y
0.3f + (rand() % 20) / 10.f});
cubeEntity.make<sill::ColliderComponent>();
cubeEntity.get<sill::ColliderComponent>().addBoxShape({0.f, 0.f, 0.f}, cubeSize);
cubeEntity.make<sill::AnimationComponent>();
cubes.emplace_back(&cubeEntity);
}
// We bind our VR actions
engine.input().bindAction("trigger", VrButton::Trigger, VrDeviceType::RightHand);
// Behavior entity
{
auto& entity = engine.make<sill::Entity>();
auto& behaviorComponent = entity.make<sill::BehaviorComponent>();
behaviorComponent.onUpdate([&](float /* dt */) {
static sill::Entity* grabbedCube = nullptr;
if (!engine.vr().deviceValid(VrDeviceType::RightHand)) return;
const auto& handTransform = engine.vr().deviceTransform(VrDeviceType::RightHand);
// When the user uses the trigger, we find the closest cube nearby, and grab it.
if (engine.input().justDown("trigger")) {
float minDistance = 1000.f;
for (auto cube : cubes) {
auto cubeTranslation = cube->get<sill::TransformComponent>().translation();
auto distance = glm::distance(cubeTranslation, handTransform.translation);
if (distance < minDistance) {
minDistance = distance;
grabbedCube = cube;
}
}
// We will animate the world transform over 300ms.
grabbedCube->get<sill::AnimationComponent>().start(sill::AnimationFlag::WorldTransform, 0.3f, false);
}
else if (engine.input().justUp("trigger")) {
grabbedCube->get<sill::AnimationComponent>().stop(sill::AnimationFlag::WorldTransform);
grabbedCube = nullptr;
}
// Update cube to us whenever it is in grabbing state.
if (grabbedCube != nullptr) {
grabbedCube->get<sill::AnimationComponent>().target(sill::AnimationFlag::WorldTransform, handTransform);
// @fixme Would love to be able to get velocity of the hand,
// and apply it to the cube!
}
});
}
app.engine().run();
return EXIT_SUCCESS;
}
| true |
c57eab52a75c026ec63242b8fbd725f3c48d2ad5 | C++ | AVGP/wii-spaaace | /source/alien.cpp | UTF-8 | 1,533 | 2.59375 | 3 | [
"MIT"
] | permissive | #include "alien.h"
Alien::Alien(wsp::Image *img) {
SetImage(img);
DefineCollisionRectangle(28, 14, 42, 55);
resetMotion();
resetPosition();
resetShotCountdown();
}
void Alien::setShots(Shot **shots, unsigned int numberOfShots, bool isOwn) {
if(isOwn) {
ownShots = shots;
numOwnShots = numberOfShots;
} else {
enemyShots = shots;
numEnemyShots = numberOfShots;
}
}
void Alien::update() {
Move(motionX, motionY);
if(GetY() < 0) {
SetY(0);
resetMotion();
}
else if(GetY() > 480-GetHeight()) {
SetY(480-GetHeight());
resetMotion();
}
int i;
for(i=0;i<numEnemyShots;i++) {
if(enemyShots[i]->isFired() == false) continue;
if(CollidesWith(enemyShots[i])) {
enemyShots[i]->remove();
resetPosition();
resetMotion();
resetShotCountdown();
score++;
break;
}
}
if(--lockMotionFrames == 0) resetMotion();
if(GetX() < 0) resetPosition();
if(--nextShotCountdown == 0) {
resetShotCountdown();
for(i=0;i<numOwnShots;i++) {
if(ownShots[i]->isFired() == false) {
ownShots[i]->fire(GetX(), GetY() + (GetHeight() / 2) - 10, -6);
break;
}
}
}
}
void Alien::resetMotion() {
motionX = -4;
motionY = rand()%10 - 5;
lockMotionFrames = Alien::LOCK_MOTION_FRAME_COUNT;
}
void Alien::resetPosition() {
SetPosition(640 + (rand()%Alien::MAX_OFFSCREEN_OFFSET), rand() % (480-GetHeight()));
}
void Alien::resetShotCountdown() {
nextShotCountdown = 80 + rand()%41;
}
const int Alien::MAX_OFFSCREEN_OFFSET = 640;
const int Alien::LOCK_MOTION_FRAME_COUNT = 100;
| true |
bfea5f9d3c1fa1b540ab5dee2d9b106136784df7 | C++ | AMarchionna/Metodos-TP2 | /src/knn.cpp | UTF-8 | 1,673 | 3.0625 | 3 | [] | no_license | #include <algorithm>
//#include <chrono>
#include <iostream>
#include <vector>
#include "knn.h"
#include "time.h"
using namespace std;
KNNClassifier::KNNClassifier(unsigned int n_neighbors)
{
cout << "Clasificador inicializado con k=" << n_neighbors << "..." << endl;
neighbors = n_neighbors;
}
void KNNClassifier::fit(SparseMatrixA X, Matrix y)
{
X_mine = X;
y_mine = y;
}
VectorA KNNClassifier::distance_to_row(VectorA v){
auto V = VectorA(X_mine.rows());
for(int i=0; i<X_mine.rows(); i++) {
V(i) = (X_mine.row(i)-v.transpose()).norm();
}
vector<pair<double,int> > index(X_mine.rows());
for(int i=0; i<(int)index.size(); i++) index[i] = {V(i), i};
sort(index.begin(), index.end());
auto Res = VectorA(X_mine.rows());
for (int i = 0; i < X_mine.rows(); ++i)
Res(i) = index[i].second;
return Res;
}
int KNNClassifier::predict_row(VectorA v) {
auto dist = distance_to_row(v);
auto vecinos = VectorA(neighbors);
for(int i=0; i < (int)neighbors; i++){
int s = dist(i);
vecinos(i) = y_mine(s);
}
int ceros = 0; int unos = 0;
for(int i=0; i<(int)neighbors; i++){
if(vecinos(i) == 0) ceros ++;
else if (vecinos(i) == 1) unos ++;
}
assert(unos+ceros==neighbors);
if(ceros > unos){
return 0;
}
if (unos > ceros){
return 1;
}
srand(time(NULL));
return rand() % 2;
}
VectorA KNNClassifier::predict(SparseMatrixA X)
{
// Creamos vector columna a devolver
auto ret = VectorA(X.rows());
Matrix Y = Matrix(X);
cout << "Calculando predicciones..." << endl;
for (unsigned k = 0; k < X.rows(); ++k)
{
auto v = VectorA(X.row(k));
ret(k) = predict_row(v);
}
return ret;
}
| true |
21cb1bb88d3609fc10fd65e77182b54bd5bf5552 | C++ | mbuszka/university_mia | /alfabet.cpp | UTF-8 | 588 | 2.75 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char word[55];
int max (int *lis, int idx) {
int t = 0;
for (int i = 0; i < idx; i ++) {
t = t < lis[i] ? lis[i] : t;
}
return t;
}
int main () {
int r = scanf("%s", word);
int n = strlen(word);
int *lis = (int *) calloc(26, sizeof(int));
for (int i = 0; i < n; i ++) {
int off = word[i] - 'a';
// printf("off %d\n", off);
int m = max(lis, off);
// printf("m %d\n", m);
lis[off] = m >= lis[off] ? m + 1 : lis[off];
}
printf("%d", 26 - max(lis, 26));
free(lis);
return 0;
} | true |
c9345ecf3b927c4e5fabf6106870139cde944678 | C++ | LaurenRolan/Cpp | /TP4/include/Lanceur.h | UTF-8 | 359 | 2.796875 | 3 | [] | no_license | /* Author: Lauren Sampaio
* File: Lanceur.h
*/
#ifndef LANCEUR_H
#define LANCEUR_H
#include <iostream>
#include "Obstacle.h"
using namespace std;
class Lanceur {
private:
Obstacle * _premier;
public:
Lanceur( Obstacle *premier );
Lanceur( );
~Lanceur();
void lancer( int place );
void setPremier( Obstacle *premier );
void afficher( int place );
};
#endif | true |
18ddf5ba9dbf0a7edc272db651a494ecf071a3a7 | C++ | razmik1996/JustExercises | /AbstractEmployeePolimorph/AbstractEmployeePolimorph/Employee.h | UTF-8 | 521 | 3.140625 | 3 | [] | no_license | #pragma once
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <string>
using std::string;
class Employee
{
public:
Employee(const string&, const string&, const string&);
void setFirstName(const string&);
string getFirstName() const;
void setLastName(const string&);
string getLastName() const;
void setSSN(const string&);
string getSSN() const;
virtual double earnings() const = 0;
virtual void print() const;
~Employee();
private:
string firstName;
string SSN;
string lastName;
};
#endif // !EMPLOYEE_H | true |
ab9730a01cf3480429f87a57ed3b04483a7dbb69 | C++ | thirtiseven/projecteuler | /104.cc | UTF-8 | 898 | 2.75 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <algorithm>
#include <string>
const int maxn = 1e7;
bool is_pandigital(int x) {
std::string s = std::to_string(x);
// std::cout << "int " << x << '\n';
std::sort(s.begin(), s.end());
if (s == "123456789") {
return true;
}
return false;
}
int f_last[maxn];
long long f_first[maxn];
void gao() {
f_first[1] = f_first[2] = f_last[1] = f_last[2] = 1;
for (int i = 3; i < maxn; i++) {
f_first[i] = f_first[i-1] + f_first[i-2];
f_last[i] = (f_last[i-1] + f_last[i-2]) % 1000000000;
if (f_first[i] > 100000000 && f_last[i] > 100000000 && is_pandigital(f_last[i])) {
double t = (i * 0.20898764024997873 - 0.3494850021680094);
if (is_pandigital((long long)pow(10, t - (long long)t + 8))) {
std::cout << i << '\n';
break;
}
}
}
}
int main(int argc, char *argv[]) {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
gao();
} | true |
676c50ddc7064fae76b9ba2cc51e70e67c7dc513 | C++ | ayyzenn/CL118_Programming-Fundamentals---Lab | /Lab_Tasks/6(2)/Question7.cpp | UTF-8 | 422 | 3.34375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int num1 = 0;
int num2 = 0;
int num3 = 0;
////////////
cout<<"Enter three numbers!"<<endl;
////////////
cout<<"Enter first number: ";
cin>>num1;
cout<<"Enter second number: ";
cin>>num2;
cout<<"Enter third number: ";
cin>>num3;
cout<<num1<<num2<<num3<<endl;
cout<<num3<<num2<<num1<<endl;
} | true |
25db4ac523807f00199026aca76163a677080b27 | C++ | ntornqvi/SailingBoat | /src/logger.cc | UTF-8 | 1,113 | 2.796875 | 3 | [
"MIT"
] | permissive | #include <cstdio>
#include <string>
#include "../include/logger.h"
#include "../include/io.h"
Logger::Logger(std::string path) {
file_path_ = path;
remove(path.c_str());
}
void Logger::LogData(Log packet) {
log_.entry_id = packet.entry_id;
log_.latitude = packet.latitude;
log_.longitude = packet.longitude;
log_.timestamp = packet.timestamp;
available_ = true;
}
void Logger::Publish() {
if (available_) {
nlohmann::json json_obj;
json_obj["entry_id"] = log_.entry_id;
json_obj["latitude"] = log_.latitude;
json_obj["longitude"] = log_.longitude;
json_obj["timestamp"] = log_.timestamp;
IO io;
io.WriteFile(json_obj, file_path_);
available_ = false;
}
}
void Logger::PublishWaypoint(GPSData from, GPSData to, std::string message) {
nlohmann::json json_obj;
json_obj["at_lat"] = from.latitude;
json_obj["at_long"] = from.longitude;
json_obj["dest_lat"] = to.latitude;
json_obj["dest_long"] = to.longitude;
json_obj["message"] = message;
json_obj["time"] = from.timestamp;
IO io;
io.WriteFile(json_obj, file_path_);
available_ = false;
}
| true |
58f81175ba74a9b213ac05a606e2587b7688ba21 | C++ | tardate/LittleArduinoProjects | /playground/Audio/SimpleSamplePlayer/SimpleSamplePlayer.ino | UTF-8 | 1,200 | 2.625 | 3 | [
"MIT"
] | permissive | /*
Audio/SimpleSamplePlayer
Playing short audio samples on an Arduino using some PWM tricks from the PCM library.
For info and circuit diagrams see https://github.com/tardate/LittleArduinoProjects/tree/master/playground/Audio/SimpleSamplePlayer
*/
#include <PCM.h>
/* include one (and only one) sample definition */
// #include "sample_arduino_duemilanove.h"
// #include "sample_pop.h"
#include "sample_phone.h"
/* playback control variables */
const int DEBOUNCE_MILLISECONDS = 1000;
const int PLAY_BUTTON_PIN = 2;
volatile bool playback_flag = false;
/*
* Command: play button interrupt handler
*/
void flagPlaybackInterrupt() {
playback_flag = true;
}
/*
* Command: enable hardware interrupt from play button
*/
void enablePlaybackInterrupt() {
pinMode(PLAY_BUTTON_PIN, INPUT_PULLUP);
delay(200);
attachInterrupt(digitalPinToInterrupt(PLAY_BUTTON_PIN), flagPlaybackInterrupt, FALLING);
}
/*
* Command: play the sample
*/
void play_sample() {
startPlayback(sample, sizeof(sample));
delay(DEBOUNCE_MILLISECONDS);
}
void setup() {
enablePlaybackInterrupt();
}
void loop() {
if (playback_flag) {
play_sample();
playback_flag = false;
}
}
| true |
82a3b636fd77f0a6f83663c109a324946b227a63 | C++ | ken-pang/TeachingTools | /mindmap/mindbaseview.cpp | UTF-8 | 310 | 2.53125 | 3 | [] | no_license | #include "mindbaseview.h"
#include "mindnodeview.h"
void MindBaseView::setParent(MindNodeView *parent)
{
parent_ = parent;
}
bool MindBaseView::hasParent(MindNodeView * parent) const
{
MindNodeView * p = parent_;
while (p && p != parent) {
p = p->parent_;
}
return p == parent;
}
| true |
3d8136c42d2d561f3cff61c204b3594a032911f1 | C++ | cllx/Undergraduate-course | /数据结构/栈和队列/04+栈和队列/4-1/algo3-2.cpp | GB18030 | 1,171 | 3.75 | 4 | [] | no_license | #include <stdio.h>
#include <malloc.h>
typedef char ElemType;
typedef struct linknode
{
ElemType data; //
struct linknode *next; //ָ
} LiStack;
void InitStack(LiStack *&s) //ʼջs
{ s=(LiStack *)malloc(sizeof(LiStack));
s->next=NULL;
}
void DestroyStack(LiStack *&s) //ջ
{ LiStack *p=s,*q=s->next;
while (q!=NULL)
{ free(p);
p=q;
q=p->next;
}
free(p); //ʱpָβڵ,ͷռ
}
bool StackEmpty(LiStack *s) //жջǷΪ
{
return(s->next==NULL);
}
void Push(LiStack *&s,ElemType e) //ջ
{ LiStack *p;
p=(LiStack *)malloc(sizeof(LiStack));
p->data=e; //½ԪeӦĽڵ*p
p->next=s->next; //*pڵΪʼڵ
s->next=p;
}
bool Pop(LiStack *&s,ElemType &e) //ջ
{ LiStack *p;
if (s->next==NULL) //ջյ
return false;
p=s->next; //pָʼڵ
e=p->data;
s->next=p->next; //ɾ*pڵ
free(p); //ͷ*pڵ
return true;
}
bool GetTop(LiStack *s,ElemType &e) //ȡջԪ
{ if (s->next==NULL) //ջյ
return false;
e=s->next->data;
return true;
}
| true |
bbddb284d952103fb3e2d763d34af8b84dc3e95d | C++ | hl0071/cloudyclouds | /cloudyclouds/Camera.cpp | UTF-8 | 1,338 | 2.875 | 3 | [] | no_license | #include "stdafx.h"
#include "Camera.h"
const float Camera::rotSpeed = 0.01f;
const float Camera::moveSpeed = 16.0f;
Camera::Camera() :
lastMousePosX(0),
lastMousePosY(0),
rotX(0.0f),
rotY(0.0f),
cameraPosition(2.f)
{
}
Camera::~Camera()
{
}
void Camera::update(float timeSinceLastFrame)
{
int newMousePosX, newMousePosY;
glfwGetMousePos(&newMousePosX, &newMousePosY);
rotX += -rotSpeed * (newMousePosX - lastMousePosX);
rotY += rotSpeed * (newMousePosY - lastMousePosY);
float forward = (glfwGetKey(GLFW_KEY_UP) == GLFW_PRESS || glfwGetKey('w') == GLFW_PRESS) ? 1.0f : 0.0f;
float back = (glfwGetKey(GLFW_KEY_DOWN) == GLFW_PRESS || glfwGetKey('s') == GLFW_PRESS) ? 1.0f : 0.0f;
float left = (glfwGetKey(GLFW_KEY_LEFT) == GLFW_PRESS || glfwGetKey('a') == GLFW_PRESS) ? 1.0f : 0.0f;
float right = (glfwGetKey(GLFW_KEY_RIGHT) == GLFW_PRESS || glfwGetKey('d') == GLFW_PRESS) ? 1.0f : 0.0f;
cameraDirection = Vector3(sinf(rotX) * cosf(rotY), sinf(rotY), cosf(rotX) * cosf(rotY));
Vector3 cameraLeft = Vector3::cross(cameraDirection, Vector3(0,1,0));
cameraPosition += ((forward - back) * cameraDirection + (right -left) * cameraLeft) * moveSpeed * timeSinceLastFrame;
matrix = Matrix4::camera(cameraPosition, cameraPosition + cameraDirection);
lastMousePosX = newMousePosX;
lastMousePosY = newMousePosY;
} | true |
08e8184e9ef1c6fc6709979406d6d5d9ace69f1f | C++ | alisw/AliRoot | /TEvtGen/Tauola/TauolaHEPEVTParticle.cxx | UTF-8 | 7,904 | 2.78125 | 3 | [] | permissive | #include "TauolaHEPEVTParticle.h"
#include "TauolaLog.h"
namespace Tauolapp
{
TauolaHEPEVTParticle::~TauolaHEPEVTParticle()
{
// Cleanup particles that do not belong to event
for(unsigned int i=0;i<cache.size();i++)
if(cache[i]->m_barcode<0)
delete cache[i];
}
TauolaHEPEVTParticle::TauolaHEPEVTParticle(int pdgid, int status, double px, double py, double pz, double e, double m, int ms, int me, int ds, int de){
m_px = px;
m_py = py;
m_pz = pz;
m_e = e;
m_generated_mass = m;
m_pdgid = pdgid;
m_status = status;
m_first_mother = ms;
m_second_mother = me;
m_daughter_start = ds;
m_daughter_end = de;
m_barcode = -1;
m_event = NULL;
}
void TauolaHEPEVTParticle::undecay(){
Log::Info()<<"TauolaHEPEVTParticle::undecay not implemented for HEPEVT"<<endl;
}
void TauolaHEPEVTParticle::setMothers(vector<TauolaParticle*> mothers){
// If this particle has not yet been added to the event record
// then add it to the mothers' event record
if(m_barcode<0 && mothers.size()>0)
{
TauolaHEPEVTEvent *evt = ((TauolaHEPEVTParticle*)mothers[0])->m_event;
evt->addParticle(this);
}
if(mothers.size()>2) Log::Fatal("TauolaHEPEVTParticle::setMothers: HEPEVT does not allow more than two mothers!");
if(mothers.size()>0) m_first_mother = mothers[0]->getBarcode();
if(mothers.size()>1) m_second_mother = mothers[1]->getBarcode();
}
void TauolaHEPEVTParticle::setDaughters(vector<TauolaParticle*> daughters){
// This particle must be inside some event record to be able to add daughters
if(m_event==NULL) Log::Fatal("TauolaHEPEVTParticle::setDaughters: particle not inside event record.");
int beg = 65535, end = -1;
for(unsigned int i=0;i<daughters.size();i++)
{
int bc = daughters[i]->getBarcode();
if(bc<0) Log::Fatal("TauolaHEPEVTParticle::setDaughters: all daughters has to be in event record first");
if(bc<beg) beg = bc;
if(bc>end) end = bc;
}
if(end == -1) beg = -1;
m_daughter_start = beg;
m_daughter_end = end;
}
std::vector<TauolaParticle*> TauolaHEPEVTParticle::getMothers(){
std::vector<TauolaParticle*> mothers;
TauolaParticle *p1 = NULL;
TauolaParticle *p2 = NULL;
if(m_first_mother>=0) p1 = m_event->getParticle(m_first_mother);
if(m_second_mother>=0) p2 = m_event->getParticle(m_second_mother);
if(p1) mothers.push_back(p1);
if(p2) mothers.push_back(p2);
return mothers;
}
// WARNING: this method also corrects daughter indices
// if such were not defined
std::vector<TauolaParticle*> TauolaHEPEVTParticle::getDaughters(){
std::vector<TauolaParticle*> daughters;
if(!m_event) return daughters;
// Check if m_daughter_start and m_daughter_end are set
// If not - try to get list of daughters from event
if(m_daughter_end<0)
{
int min_d=65535, max_d=-1;
for(int i=0;i<m_event->getParticleCount();i++)
{
if(m_event->getParticle(i)->isDaughterOf(this))
{
if(i<min_d) min_d = i;
if(i>max_d) max_d = i;
}
}
if(max_d>=0)
{
m_daughter_start = min_d;
m_daughter_end = max_d;
m_status = 2;
}
}
// If m_daughter_end is still not set - there are no daughters
// Otherwsie - get daughters
if(m_daughter_end>=0)
{
for(int i=m_daughter_start;i<=m_daughter_end;i++)
{
TauolaParticle *p = m_event->getParticle(i);
if(p==NULL)
{
Log::Warning()<<"TauolaHEPEVTParticle::getDaughters(): No particle with index "<<i<<endl;
return daughters;
}
daughters.push_back(p);
}
}
return daughters;
}
void TauolaHEPEVTParticle::checkMomentumConservation(){
if(!m_event) return;
if(m_daughter_end < 0) return;
TauolaHEPEVTParticle *buf = m_event->getParticle(m_daughter_start);
int first_mother_idx = buf->getFirstMotherIndex();
int second_mother_idx = buf->getSecondMotherIndex();
double px =0.0, py =0.0, pz =0.0, e =0.0;
double px2=0.0, py2=0.0, pz2=0.0, e2=0.0;
for(int i=m_daughter_start;i<=m_daughter_end;i++)
{
buf = m_event->getParticle(i);
px += buf->getPx();
py += buf->getPy();
pz += buf->getPz();
e += buf->getE ();
}
if(first_mother_idx>=0)
{
buf = m_event->getParticle(first_mother_idx);
px2 += buf->getPx();
py2 += buf->getPy();
pz2 += buf->getPz();
e2 += buf->getE();
}
if(second_mother_idx>=0)
{
buf = m_event->getParticle(second_mother_idx);
px2 += buf->getPx();
py2 += buf->getPy();
pz2 += buf->getPz();
e2 += buf->getE();
}
// 3-momentum // test HepMC style
double dp = sqrt( (px-px2)*(px-px2) + (py-py2)*(py-py2) + (pz-pz2)*(pz-pz2) );
// virtuality test as well.
double m1 = sqrt( fabs( e*e - px*px - py*py - pz*pz ) );
double m2 = sqrt( fabs( e2*e2 - px2*px2 - py2*py2 - pz2*pz2 ) );
if( fabs(m1-m2) > 0.0001 || dp > 0.0001*(e+e2))
{
Log::RedirectOutput( Log::Warning()<<"Momentum not conserved in vertex: " );
if(first_mother_idx >=0) m_event->getParticle(first_mother_idx) ->print();
if(second_mother_idx>=0) m_event->getParticle(second_mother_idx)->print();
for(int i=m_daughter_start;i<=m_daughter_end;i++) m_event->getParticle(i)->print();
Log::RevertOutput();
}
}
TauolaHEPEVTParticle * TauolaHEPEVTParticle::createNewParticle(
int pdg_id, int status, double mass,
double px, double py, double pz, double e){
// New particles created using this method are added to cache
// They will be deleted when this particle will be deleted
cache.push_back(new TauolaHEPEVTParticle(pdg_id,status,px,py,pz,e,mass,-1,-1,-1,-1));
return cache.back();
}
bool TauolaHEPEVTParticle::isDaughterOf(TauolaHEPEVTParticle *p)
{
int bc = p->getBarcode();
if(bc==m_first_mother || bc==m_second_mother) return true;
return false;
}
bool TauolaHEPEVTParticle::isMotherOf (TauolaHEPEVTParticle *p)
{
int bc = p->getBarcode();
if(bc>=m_daughter_start && bc<=m_daughter_end) return true;
return false;
}
void TauolaHEPEVTParticle::print(){
char buf[256];
sprintf(buf,"P: (%2i) %6i %2i | %11.4e %11.4e %11.4e %11.4e | %11.4e | M: %2i %2i | D: %2i %2i\n",
m_barcode, m_pdgid, m_status, m_px, m_py, m_pz, m_e, m_generated_mass,
m_first_mother, m_second_mother, m_daughter_start, m_daughter_end);
cout<<buf;
}
/******** Getter and Setter methods: ***********************/
void TauolaHEPEVTParticle::setPdgID(int pdg_id){
m_pdgid = pdg_id;
}
void TauolaHEPEVTParticle::setStatus(int status){
m_status = status;
}
void TauolaHEPEVTParticle::setMass(double mass){
m_generated_mass = mass;
}
int TauolaHEPEVTParticle::getPdgID(){
return m_pdgid;
}
int TauolaHEPEVTParticle::getStatus(){
return m_status;
}
double TauolaHEPEVTParticle::getMass(){
return m_generated_mass;
}
inline double TauolaHEPEVTParticle::getPx(){
return m_px;
}
inline double TauolaHEPEVTParticle::getPy(){
return m_py;
}
double TauolaHEPEVTParticle::getPz(){
return m_pz;
}
double TauolaHEPEVTParticle::getE(){
return m_e;
}
void TauolaHEPEVTParticle::setPx(double px){
m_px = px;
}
void TauolaHEPEVTParticle::setPy(double py){
m_py = py;
}
void TauolaHEPEVTParticle::setPz(double pz){
m_pz = pz;
}
void TauolaHEPEVTParticle::setE(double e){
m_e = e;
}
int TauolaHEPEVTParticle::getBarcode(){
return m_barcode;
}
void TauolaHEPEVTParticle::setBarcode(int barcode){
m_barcode = barcode;
}
void TauolaHEPEVTParticle::setEvent(TauolaHEPEVTEvent *event){
m_event = event;
}
int TauolaHEPEVTParticle::getFirstMotherIndex(){
return m_first_mother;
}
int TauolaHEPEVTParticle::getSecondMotherIndex(){
return m_second_mother;
}
int TauolaHEPEVTParticle::getDaughterRangeStart(){
return m_daughter_start;
}
int TauolaHEPEVTParticle::getDaughterRangeEnd(){
return m_daughter_end;
}
} // namespace Tauolapp
| true |
bdf2b9bf95e8f7cf38ff4d3315f8b2370511d788 | C++ | Altudy/solutionheejoon | /number_counting_project/strategy.cpp | UTF-8 | 9,678 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <math.h>
#include "strategy.h"
using namespace std;
strategy::strategy() : target_num(0), target(NULL), rcv_num(0), snd_num(0), added(0), gap(0), chance(false) {}
// constructor
// 모든 값을 0으로 만든다.
void strategy::readTarget(int num, int* ptrTarget)
{
target = new int[num];
target_num = num;
for (int i = 0; i < num; i++)
{
target[i] = ptrTarget[i];
}
if (target_num > 1)
{
gap = target[1] - target[0];
}
}
void strategy::map_first()
{
if (gap >= 5)
{
for (int k = 0; k < target_num; k++)
{
if (k == 0) // 일부러 지기 위해 질 수 있는 점수에 weight를 준다.
{
int k = 0;
int weight = pow(10, target_num - k - 1); // 가까운 target을 위한 가중치
for (int i = target[k] - 5; i < 100; i++) // 첫 target 이후에도 wieght를 주는 이유는
// target 이후의 가중치가 더 낮을 수 도 있어 지지 않을 때가 발생
for (int j = 1; j <= 5; j++)
win[k][i][j] = weight; // target 포함 아래 5개의 점수를 weight로 초기화
for (int j = 1; j <= 5; j++)
win[k][target[k] - 1][j] = 0;
win[k][target[k] - 4][1] = 0;
win[k][target[k] - 4][5] = 0;
win[k][target[k] - 3][4] = 0;
win[k][target[k] - 3][5] = 0;
win[k][target[k] - 2][3] = 0;
win[k][target[k] - 2][4] = 0;
win[k][target[k] - 2][5] = 0; // target 을 획득할 수는 빼준다.
for (int i = target[k] - 6; i > 0; i--) // 점수를 딸 수 있는 자리에 weight를 넣어준다.
{
if (win[k][i + 1][1] == 0) { win[k][i][1] = weight; win[k][i][2] = weight; }
if (win[k][i + 2][2] == 0) { win[k][i][1] = weight; win[k][i][2] = weight; win[k][i][3] = weight; }
if (win[k][i + 3][3] == 0) { win[k][i][2] = weight; win[k][i][3] = weight; win[k][i][4] = weight; }
if (win[k][i + 4][4] == 0) { win[k][i][3] = weight; win[k][i][4] = weight; win[k][i][5] = weight; }
if (win[k][i + 5][5] == 0) { win[k][i][4] = weight; win[k][i][5] = weight; }
}
}
else
{
int weight = pow(10, target_num - k - 1); // 가까운 target을 위한 가중치
for (int i = target[k] - 5; i <= target[k] - 1; i++)
for (int j = 1; j <= 5; j++)
win[k][i][j] = weight; // target 포함 아래 5개의 점수를 weight로 초기화
win[k][target[k] - 5][1] = 0;
win[k][target[k] - 5][2] = 0;
win[k][target[k] - 5][3] = 0;
win[k][target[k] - 3][1] = 0; // target 을 획득하지 못할 수는 빼준다.
for (int i = target[k] - 6; i > 0; i--) // 점수를 딸 수 있는 자리에 weight를 넣어준다.
{
if (win[k][i + 1][1] == 0) { win[k][i][1] = weight; win[k][i][2] = weight; }
if (win[k][i + 2][2] == 0) { win[k][i][1] = weight; win[k][i][2] = weight; win[k][i][3] = weight; }
if (win[k][i + 3][3] == 0) { win[k][i][2] = weight; win[k][i][3] = weight; win[k][i][4] = weight; }
if (win[k][i + 4][4] == 0) { win[k][i][3] = weight; win[k][i][4] = weight; win[k][i][5] = weight; }
if (win[k][i + 5][5] == 0) { win[k][i][4] = weight; win[k][i][5] = weight; }
}
}
}
}
else if (gap == 0) { // 상대가 target을 하나만 보냈을 때
map_second(); return;
}
else if (gap == 1 || gap == 2) map_one();
else if (gap == 3) map_three();
else if (gap == 4) map_four();
sum();
}
void strategy::map_second()
{
for (int k = 0; k < target_num; k++)
{
int weight = pow(10, target_num - k - 1); // 가까운 target을 위한 가중치
for (int i = target[k] - 5; i <= target[k] - 1; i++)
for (int j = 1; j <= 5; j++)
win[k][i][j] = weight; // target 포함 아래 5개의 점수를 weight로 초기화
win[k][target[k] - 5][1] = 0;
win[k][target[k] - 5][2] = 0;
win[k][target[k] - 5][3] = 0;
win[k][target[k] - 3][1] = 0; // target 을 획득하지 못할 수는 빼준다.
for (int i = target[k] - 6; i > 0; i--) // 점수를 딸 수 있는 자리에 weight를 넣어준다.
{
if (win[k][i + 1][1] == 0) { win[k][i][1] = weight; win[k][i][2] = weight; }
if (win[k][i + 2][2] == 0) { win[k][i][1] = weight; win[k][i][2] = weight; win[k][i][3] = weight; }
if (win[k][i + 3][3] == 0) { win[k][i][2] = weight; win[k][i][3] = weight; win[k][i][4] = weight; }
if (win[k][i + 4][4] == 0) { win[k][i][3] = weight; win[k][i][4] = weight; win[k][i][5] = weight; }
if (win[k][i + 5][5] == 0) { win[k][i][4] = weight; win[k][i][5] = weight; }
}
}
sum();
}
void strategy::map_one()
{
int k = 1;
int weight = pow(10, target_num - k - 1); // 가까운 target을 위한 가중치
for (int i = target[k] - 5; i <= target[k] - 1; i++)
for (int j = 1; j <= 5; j++)
win[k][i][j] = weight; // target 포함 아래 5개의 점수를 weight로 초기화
win[k][target[k] - 5][1] = 0;
win[k][target[k] - 5][2] = 0;
win[k][target[k] - 5][3] = 0;
win[k][target[k] - 3][1] = 0; // target 을 획득하지 못할 수는 빼준다.
for (int i = target[k] - 6; i > 0; i--) // 점수를 딸 수 있는 자리에 weight를 넣어준다.
{
if (win[k][i + 1][1] == 0) { win[k][i][1] = weight; win[k][i][2] = weight; }
if (win[k][i + 2][2] == 0) { win[k][i][1] = weight; win[k][i][2] = weight; win[k][i][3] = weight; }
if (win[k][i + 3][3] == 0) { win[k][i][2] = weight; win[k][i][3] = weight; win[k][i][4] = weight; }
if (win[k][i + 4][4] == 0) { win[k][i][3] = weight; win[k][i][4] = weight; win[k][i][5] = weight; }
if (win[k][i + 5][5] == 0) { win[k][i][4] = weight; win[k][i][5] = weight; }
}
}
void strategy::map_three()
{
int k = 1;
int weight = pow(10, target_num - k - 1); // 가까운 target을 위한 가중치
for (int i = target[k] - 5; i <= target[k] - 1; i++)
for (int j = 1; j <= 5; j++)
win[k][i][j] = weight; // target 포함 아래 5개의 점수를 weight로 초기화
win[k][target[k] - 4][1] = 0;
win[k][target[k] - 4][2] = 0;
win[k][target[k] - 5][3] = 0; // target 을 획득하지 못할 수는 빼준다.
for (int i = target[k] - 6; i > 0; i--) // 점수를 딸 수 있는 자리에 weight를 넣어준다.
{
if (win[k][i + 1][1] == 0) { win[k][i][1] = weight; win[k][i][2] = weight; }
if (win[k][i + 2][2] == 0) { win[k][i][1] = weight; win[k][i][2] = weight; win[k][i][3] = weight; }
if (win[k][i + 3][3] == 0) { win[k][i][2] = weight; win[k][i][3] = weight; win[k][i][4] = weight; }
if (win[k][i + 4][4] == 0) { win[k][i][3] = weight; win[k][i][4] = weight; win[k][i][5] = weight; }
if (win[k][i + 5][5] == 0) { win[k][i][4] = weight; win[k][i][5] = weight; }
}
}
void strategy::map_four()
{
int k = 1;
int weight = pow(10, target_num - k - 1); // 가까운 target을 위한 가중치
for (int i = target[k] - 5; i <= target[k] - 1; i++)
for (int j = 1; j <= 5; j++)
win[k][i][j] = weight; // target 포함 아래 5개의 점수를 weight로 초기화
win[k][target[k] - 5][1] = 0;
win[k][target[k] - 5][2] = 0;
win[k][target[k] - 5][3] = 0; // target 을 획득하지 못할 수는 빼준다.
for (int i = target[k] - 6; i > 0; i--) // 점수를 딸 수 있는 자리에 weight를 넣어준다.
{
if (win[k][i + 1][1] == 0) { win[k][i][1] = weight; win[k][i][2] = weight; }
if (win[k][i + 2][2] == 0) { win[k][i][1] = weight; win[k][i][2] = weight; win[k][i][3] = weight; }
if (win[k][i + 3][3] == 0) { win[k][i][2] = weight; win[k][i][3] = weight; win[k][i][4] = weight; }
if (win[k][i + 4][4] == 0) { win[k][i][3] = weight; win[k][i][4] = weight; win[k][i][5] = weight; }
if (win[k][i + 5][5] == 0) { win[k][i][4] = weight; win[k][i][5] = weight; }
}
}
void strategy::sum()
{
for (int k = 0; k < target_num; k++)
for (int i = 1; i <= 100; i++)
for (int j = 1; j <= 5; j++)
vic[i][j] += win[k][i][j];
}
void strategy::receive(int num)
{
rcv_num = num;
added = rcv_num - snd_num;
if (rcv_num >= target[0] && snd_num < target[0]) chance = true;
}
int strategy::send()
{
if (snd_num == 0)
{ //시작할 경우.
snd_num = rcv_num + start();
return snd_num;
}
int min(10000000); // 가장 점수를 딸 수 없는 수.
int add(0); // 더할 수
if (added != 1)
{
if (vic[rcv_num + (added - 1)][added - 1] < min)
{
min = vic[rcv_num + (added - 1)][added - 1];
add = added - 1;
}
}
if (vic[rcv_num + added][added] < min)
{
min = vic[rcv_num + added][added];
add = added;
}
if (added != 5)
{
if (vic[rcv_num + (added + 1)][added + 1] < min)
{
min = vic[rcv_num + (added + 1)][added + 1];
add = added + 1;
}
}
if ((chance && min != 10) || (chance && min != 0))
use_chance(add);
snd_num = rcv_num + add;
return snd_num;
}
int strategy::start()
{
int min(10000000);
int best(0); // 보내기 가장 좋은 수. 가장 작은 수. 점수를 딸 수 없는 수.
for (int i = 1; i <= 5; i++)
{
if (vic[added + i][i] < min)
{
min = vic[added + i][i];
best = i;
}
}
return best;
}
void strategy::use_chance(int& add)
{
for (int i = 1; i <= 5; i++)
{
if ((vic[rcv_num + i][i] == 10) || (vic[rcv_num + i][i] == 0))
{
chance = false;
add = i;
}
}
}
strategy::~strategy()
{ // 소멸자
delete[] target;
target = NULL;
}
void strategy::print()
{
for (int i = 1; i <= 100; i++)
{
cout << i << "\t";
for (int j = 1; j <= 5; j++)
cout << vic[i][j] << "\t";
cout << endl;
}
}
| true |
76cde7745b9832d6bd8dd4b1d334d86dc6f13cde | C++ | deepakdpyqaz/competitiveprogramming | /pascaltriangle.cpp | UTF-8 | 756 | 3.953125 | 4 | [] | no_license | /*
Given an integer N, print Pascal Triangle upto N rows.
Input Format
Single integer N.
Constraints
N <= 10
Output Format
Print pascal triangle.
Sample Input
4
Sample Output
1
1 1
1 2 1
1 3 3 1
*/
#include <iostream>
using namespace std;
int factorial(int n)
{
int i=1;
int fact=1;
for(int i= n;i>1;i--)
{
fact*=i;
}
return fact;
}
int combination(int n, int r)
{
return factorial(n)/(factorial(r)*factorial(n-r));
}
int main()
{
int n;
cin>>n;
for(int i=0;i<=n;i++)
{
for(int j=n;j>i;j--){
cout<<" ";
}
for(int j=0;j<=i;j++)
{
cout<<combination(i,j)<<" ";
}
cout<<endl;
}
return 0;
} | true |
70415f7919c1a3e461c0047300d97e07f4c4c28a | C++ | ibanknatoPrad/ferriswheel | /ferriswheel.cpp | UTF-8 | 11,693 | 2.5625 | 3 | [] | no_license | /*
* ferriswheel.cpp
*
* Implementation of a ferris wheel that rotates about its pivot.
* Includes lighting.
*
* Author: Luke Lovett
* Began: Tue Oct 30 17:09:04 EDT 2012
*
* */
#include <GL/glut.h>
#include <GL/glui.h>
#include <math.h>
#include "ferriswheel.h"
/* constants */
#define PI 3.1415926535
#define WHEEL_SIZE 10.0f
#define WHEEL_INNER_SIZE WHEEL_SIZE/1.2
#define WHEEL_DEPTH 2.0f
#define WHEEL_POINTS 8
#define BENCH_WIDTH 5.0f
#define BENCH_HEIGHT 4.0f
#define BENCH_DEPTH 2.0f
#define BASE_HEIGHT 10.0f
#define BASE_WIDTH 2.0f
#define BASE_DEPTH 4.0f
#define RECURSIVE_SHRINK 3.0f
/* global variables */
GLfloat Theta = 0.5f;
GLfloat Speed = 0.1f;
int RecursiveDepth = 0;
GLfloat EyeX, EyeY, EyeZ;
GLfloat LookAtX, LookAtY, LookAtZ;
GLfloat TORSO_RADIUS = 2.0;
GLfloat TORSO_HEIGHT = 6.0;
GLfloat HEADX = 0.0, HEADY = 7.5;
GLfloat HEAD_RADIUS = 2.0;
GLfloat ARM_RADIUS = 0.4;
GLfloat UPPER_ARM_LENGTH = 3.0, LOWER_ARM_LENGTH = 3.0;
GLfloat LUAX = -2.0, LUAY = 5.0, LLAY = -3.0;
GLfloat RUAX = 2.0, RUAY = 5.0, RLAY = -3.0;
GLfloat LEG_RADIUS = 0.4;
GLfloat UPPER_LEG_LENGTH = 4.0, LOWER_LEG_LENGTH = 4.0;
GLfloat LULX = -2.0, LULY = 0.0, LLLY = -4.0;
GLfloat RULX = 2.0, RULY = 0.0, RLLY = -4.0;
/* various materials */
mProps redPlasticMaterials = {
{0.3, 0.0, 0.0, 1.0},
{0.9, 0.0, 0.0, 1.0},
{0.8, 0.6, 0.6, 1.0},
32.0
};
mProps bluePlasticMaterials = {
{ 0.0, 0.0, 0.3, 1.0 },
{ 0.0, 0.0, 0.9, 1.0 },
{ 0.7, 0.7, 0.9, 1.0 },
40.0
};
mProps spindleMats = {
{ 0.0, 0.3, 0.0, 1.0 },
{ 0.0, 0.9, 0.0, 1.0 },
{ 0.0, 0.7, 0.0, 1.0 },
40.0
};
mProps benchMats = {
{ 0.4, 0.4, 0.0, 1.0 },
{ 0.4, 0.4, 0.0, 1.0 },
{ 0.8, 0.8, 0.0, 1.0 },
40.0
};
/* various lighting */
lProps whiteLighting = {
{0.0, 0.0, 0.0, 1.0},
{1.0, 1.0, 1.0, 1.0},
{1.0, 1.0, 1.0, 1.0}
};
lProps coloredLighting = {
{0.2, 0.0, 0.0, 1.0},
{0.0, 1.0, 0.0, 1.0},
{0.0, 0.0, 1.0, 1.0}
};
GLfloat light0_pos[4] = {4.0, 10.0, 20.0, 0.0};
mProps *currentMaterials;
lProps *currentLighting;
GLfloat theta[] = {65.0, 0.0, 0.0, -42.0, -12.0, -33.0, -48.0,18.0, 74.0, -14.0, 11.0};
GLUquadricObj *p, *q;
int main_window;
void init() {
/* setup some globals */
EyeX = 50.0f;
EyeY = 10.0f;
EyeZ = 0.0f;
glClearColor(1.0, 1.0, 1.0, 1.0);
glColor3f(0.0, 0.0, 0.0);
look(0);
}
void look(int id) {
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(EyeX, EyeY, EyeZ,
LookAtX, LookAtY, LookAtZ,
0.0, 1.0, 0.0);
}
void reshape(int w, int h) {
glViewport(0, 0, w, h);
float aspect = w*1.0/h;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, aspect, 0.5, 200.0);
glMatrixMode(GL_MODELVIEW);
glutSetWindow(main_window);
glutPostWindowRedisplay(main_window);
}
void box(GLfloat width, GLfloat height, GLfloat depth) {
glBegin(GL_QUADS);
glNormal3f(0, -1, 0);
glVertex3f(0, 0, 0);
glVertex3f(width, 0, 0);
glVertex3f(width, 0, depth);
glVertex3f(0, 0, depth);
glNormal3f(0, 0, -1);
glVertex3f(0, 0, 0);
glVertex3f(0, height, 0);
glVertex3f(width, height, 0);
glVertex3f(width, 0, 0);
glNormal3f(-1, 0, 0);
glVertex3f(0, 0, 0);
glVertex3f(0, 0, depth);
glVertex3f(0, height, depth);
glVertex3f(0, height, 0);
glNormal3f(1, 0, 0);
glVertex3f(width, 0, 0);
glVertex3f(width, 0, depth);
glVertex3f(width, height, depth);
glVertex3f(width, height, 0);
glNormal3f(0, 1, 0);
glVertex3f(0, height, 0);
glVertex3f(width, height, 0);
glVertex3f(width, height, depth);
glVertex3f(0, height, depth);
glNormal3f(0, 0, 1);
glVertex3f(0, 0, depth);
glVertex3f(width, 0, depth);
glVertex3f(width, height, depth);
glVertex3f(0, height, depth);
glEnd();
}
void bench( float shrink ) {
setMaterial( &benchMats );
glPushMatrix();
glTranslatef(0, 0, -shrink*BENCH_DEPTH);
box(shrink*BENCH_WIDTH, shrink*BENCH_HEIGHT, shrink*BENCH_DEPTH);
glPopMatrix();
box(shrink*BENCH_WIDTH, shrink*BENCH_HEIGHT/2, shrink*BENCH_DEPTH);
}
void wheelBase() {
setMaterial( &redPlasticMaterials );
glPushMatrix();
glBegin(GL_QUADS);
glNormal3f(0, -1, 0);
glVertex3f(0, 0, -BASE_DEPTH/2);
glVertex3f(BASE_WIDTH, 0, -BASE_DEPTH/2);
glVertex3f(BASE_WIDTH, 0, BASE_DEPTH/2);
glVertex3f(0, 0, BASE_DEPTH/2);
glNormal3f(0, -BASE_DEPTH/2, -BASE_HEIGHT);
glVertex3f(0, 0, -BASE_DEPTH/2);
glVertex3f(BASE_WIDTH, 0, -BASE_DEPTH/2);
glVertex3f(BASE_WIDTH, BASE_HEIGHT, 0);
glVertex3f(0, BASE_HEIGHT, 0);
glNormal3f(0, BASE_DEPTH/2, BASE_HEIGHT);
glVertex3f(0, 0, BASE_DEPTH/2);
glVertex3f(BASE_WIDTH, 0, BASE_DEPTH/2);
glVertex3f(BASE_WIDTH, BASE_HEIGHT, 0);
glVertex3f(0, BASE_HEIGHT, 0);
glEnd();
glBegin(GL_TRIANGLES);
glNormal3f(-1, 0, 0);
glVertex3f(0, 0, -BASE_DEPTH/2);
glVertex3f(0, 0, BASE_DEPTH/2);
glVertex3f(0, BASE_HEIGHT, 0);
glNormal3f(1, 0, 0);
glVertex3f(BASE_WIDTH, 0, -BASE_DEPTH/2);
glVertex3f(BASE_WIDTH, 0, BASE_DEPTH/2);
glVertex3f(BASE_WIDTH, BASE_HEIGHT, 0);
glEnd();
glPopMatrix();
}
void recWheelSide( float shrink ) {
setMaterial( &bluePlasticMaterials );
glPushMatrix();
gluCylinder(p, shrink*WHEEL_SIZE, shrink*WHEEL_SIZE, shrink*WHEEL_DEPTH, WHEEL_POINTS, 8);
gluCylinder(p, shrink*WHEEL_INNER_SIZE, shrink*WHEEL_INNER_SIZE, shrink*WHEEL_DEPTH, WHEEL_POINTS, 8);
glPushMatrix();
glTranslatef(0.0, 0.0, shrink*WHEEL_DEPTH);
gluDisk(p, shrink*WHEEL_INNER_SIZE, shrink*WHEEL_SIZE, WHEEL_POINTS, 8);
glPopMatrix();
glPushMatrix();
glRotatef(180.0f, 0.0, 1.0, 0.0);
gluDisk(p, shrink*WHEEL_INNER_SIZE, shrink*WHEEL_SIZE, WHEEL_POINTS, 8);
glPopMatrix();
/* begin spindles */
setMaterial( &spindleMats );
GLfloat spindleLength = WHEEL_SIZE/1.1;
glPushMatrix();
glRotatef(90.0, 0, 1, 0);
glTranslatef(-shrink*WHEEL_DEPTH/2, 0, 0);
for ( int i=0; i<WHEEL_POINTS; i++ ) {
glPushMatrix();
glRotatef(i*360.0/WHEEL_POINTS, 1, 0, 0);
gluCylinder(p, shrink*WHEEL_DEPTH/4, shrink*WHEEL_DEPTH/4, shrink*spindleLength, WHEEL_POINTS, 8);
glPopMatrix();
}
glPopMatrix();
/* end spindles */
glPopMatrix();
}
void recWheel( int depth, float shrink, float netRotation ) {
setMaterial( &bluePlasticMaterials );
/* sides of the wheel */
glPushMatrix();
glRotatef(90.0, 0, 1, 0);
recWheelSide( shrink );
glPopMatrix();
glPushMatrix();
glTranslatef(shrink*(WHEEL_DEPTH + BENCH_WIDTH), 0, 0);
glRotatef(90.0, 0, 1, 0);
recWheelSide( shrink );
glPopMatrix();
/* end wheel sides */
/* axle */
glPushMatrix();
glRotatef(90.0, 0, 1, 0);
gluCylinder(p, shrink*0.75, shrink*0.75, shrink*(2*WHEEL_DEPTH + BENCH_WIDTH), 8, 8);
glPopMatrix();
/* end axle */
if ( depth == 0 ) {
/* benches */
for ( int i=0; i<WHEEL_POINTS; i++ ) {
GLfloat phi = i*360.0/WHEEL_POINTS;
glPushMatrix();
glRotatef(phi, 1, 0, 0);
glTranslatef(shrink*WHEEL_DEPTH, 0, shrink*WHEEL_INNER_SIZE);
glPushMatrix();
glRotatef(-Theta-phi-netRotation, 1, 0, 0);
bench( shrink );
glPopMatrix();
glPopMatrix();
}
} else {
/* recursive call to make more wheels */
for ( int i=0; i<WHEEL_POINTS; i++ ) {
GLfloat phi = i*360.0/WHEEL_POINTS;
glPushMatrix();
glRotatef(phi, 1, 0, 0);
GLfloat xOffset = shrink*(WHEEL_DEPTH + BENCH_WIDTH/2);
xOffset -= (shrink/RECURSIVE_SHRINK)*(WHEEL_DEPTH + BENCH_WIDTH/2);
glTranslatef(xOffset, 0, shrink*WHEEL_INNER_SIZE);
/* axle to hold smaller wheel */
setMaterial( &spindleMats );
glPushMatrix();
glTranslatef(-xOffset, 0, 0);
glRotatef(90.0, 0, 1, 0);
gluCylinder(p, (shrink/RECURSIVE_SHRINK)*0.75, (shrink/RECURSIVE_SHRINK)*0.75, shrink*(2*WHEEL_DEPTH + BENCH_WIDTH), 8, 8);
glPopMatrix();
/* end smaller-axle */
glPushMatrix();
glRotatef((depth%2 == 0? 2 : -2)*Theta, 1, 0, 0);
recWheel( depth-1, shrink/RECURSIVE_SHRINK,
netRotation+(depth%2 == 0? 2 : -2)*Theta+phi );
glPopMatrix();
glPopMatrix();
}
}
/* end benches */
}
void display() {
glutSetWindow(main_window);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
/* ferris wheel base */
wheelBase();
glPushMatrix();
glTranslatef(2*WHEEL_DEPTH + BASE_WIDTH + BENCH_WIDTH, 0, 0);
wheelBase();
glPopMatrix();
/* end ferris wheel base */
/* wheel */
glPushMatrix();
glTranslatef(BASE_WIDTH, BASE_HEIGHT, 0);
glRotatef(Theta, 1, 0, 0);
// wheel();
recWheel( RecursiveDepth, 1.0, 0.0 );
glPopMatrix();
/* end wheel */
glutSwapBuffers();
}
void setMaterial( mProps *props ) {
currentMaterials = props;
glMaterialfv(GL_FRONT, GL_AMBIENT, currentMaterials->ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, currentMaterials->diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, currentMaterials->specular);
glMaterialf(GL_FRONT, GL_SHININESS, currentMaterials->shininess);
}
void update() {
Theta += Speed/10.0;
display();
}
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(650, 650);
glutInitWindowPosition(50, 50);
main_window = glutCreateWindow("Ferris Wheel");
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_NORMALIZE);
p = gluNewQuadric();
q = gluNewQuadric();
glutReshapeFunc(reshape);
glutDisplayFunc(display);
init();
glEnable(GL_LIGHT0);
setMaterial( &redPlasticMaterials );
currentLighting = &whiteLighting;
glLightfv(GL_LIGHT0, GL_AMBIENT, currentLighting->ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, currentLighting->diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, currentLighting->specular);
glLightfv(GL_LIGHT0, GL_POSITION, light0_pos);
GLUI *control_panel = GLUI_Master.create_glui( "Controls",0, 50, 700 );
new GLUI_Button(control_panel, "Quit", 0, (GLUI_Update_CB)exit);
new GLUI_Column(control_panel, true);
GLUI_Rollout *eyePosRollout = new GLUI_Rollout(control_panel, "Camera Position", false);
GLUI_Rollout *lookAtRollout = new GLUI_Rollout(control_panel, "Lookat Point", false);
GLUI_Spinner *epxSpin = new GLUI_Spinner(eyePosRollout, "Camera X", GLUI_SPINNER_FLOAT, &EyeX, 0, look);
GLUI_Spinner *epySpin = new GLUI_Spinner(eyePosRollout, "Camera Y", GLUI_SPINNER_FLOAT, &EyeY, 0, look);
GLUI_Spinner *epzSpin = new GLUI_Spinner(eyePosRollout, "Camera Z", GLUI_SPINNER_FLOAT, &EyeZ, 0, look);
GLUI_Spinner *laxSpin = new GLUI_Spinner(lookAtRollout, "Lookat X", GLUI_SPINNER_FLOAT, &LookAtX, 0, look);
GLUI_Spinner *laySpin = new GLUI_Spinner(lookAtRollout, "Lookat Y", GLUI_SPINNER_FLOAT, &LookAtY, 0, look);
GLUI_Spinner *lazSpin = new GLUI_Spinner(lookAtRollout, "Lookat Z", GLUI_SPINNER_FLOAT, &LookAtZ, 0, look);
new GLUI_Column(control_panel, true);
GLUI_Spinner *speedSpin = new GLUI_Spinner(control_panel, "Rotation Speed", GLUI_SPINNER_FLOAT, &Speed, 0, (GLUI_Update_CB)NULL);
speedSpin->set_float_limits(-5.0f, 5.0f, GLUI_LIMIT_CLAMP);
GLUI_Spinner *recSpin = new GLUI_Spinner(control_panel, "Recursive Depth", GLUI_SPINNER_INT, &RecursiveDepth, 0, (GLUI_Update_CB)NULL);
recSpin->set_int_limits(0, 5, GLUI_LIMIT_CLAMP);
control_panel->set_main_gfx_window(main_window);
GLUI_Master.set_glutIdleFunc(update);
glutMainLoop();
}
| true |
d11e83d7dff654ae9d8c656ef5f27693b155aad8 | C++ | Anik-Modak/CompetitiveProgramming | /OthersAll/Euclid's Extended Algorithm.cpp | UTF-8 | 476 | 3.640625 | 4 | [] | no_license | #include <iostream>
int xGCD(int a, int b, int &x, int &y)
{
if(b == 0) {
x = 1;
y = 0;
return a;
}
int x1, y1, gcd ;
gcd= xGCD(b, a % b, x1, y1);
x = y1;
y = x1 - (a / b) * y1;
std::cout<<x<<" "<<y<<" ";
return gcd;
}
int main()
{
int a = 10, b = 6, x, y, gcd;
if(a < b) std::swap(a, b);
gcd = xGCD(a, b, x, y);
std::cout << "GCD: " << gcd << ", x = " << x << ", y = " << y << std::endl;
return 0;
}
| true |
ccd509147b007c57e3306b6da67b623b4868d5a3 | C++ | GitShou/FrameWork-NetWork-Client- | /TCPClient_03/C_CLManager.cpp | SHIFT_JIS | 2,323 | 2.578125 | 3 | [] | no_license | #include "C_CLManager.h"
bool C_CLManager::FirstConnection(){
const int SIZE_IPINPUT = 15; // IPAhX͎̕Kvobt@TCY
int sts;
int ch;
bool flg = true;
char svIP[SIZE_IPINPUT];
sockaddr_in svAddr;
LPHOSTENT lphe;
IN_ADDR ip;
// T[o[
printf("T[o[̐ݒJn\n");
printf("T[o[IPAhX͂ĂB");
scanf_s("%s", svIP, SIZE_IPINPUT);
// ͂ꂽݒ肷
svAddr.sin_family = AF_INET;
svAddr.sin_port = htons(SVRPORTNO);
svAddr.sin_addr.s_addr = inet_addr(svIP);
// T[o[ڑv
printf("T[o[ڑJn...\n");
if (this->Connection(&this->m_myTCPSock, &svAddr)){
return true;
}else{
if (this->Connection(&this->m_myUDPSock, &svAddr)) return true;
}
printf("T[o[Ƃ̐ڑm\n");
printf("TCPyUDP\Pbg̒ʐMŒ肵܂\n");
this->CheckingPingTime();
//this->MakeRecvThread();
return false;
}
bool C_CLManager::CheckingPingTime(){
MsgData work;
sockaddr_in fromAddr;
int addrLen = sizeof(sockaddr);
printf("T[o[Ƃ̒ʐMmFs܂B\n");
// UDP\PbgɃT[o[f[^Ă̂ҋ@
recvfrom(this->m_myUDPSock, work.data, sizeof(MsgData), 0, (struct sockaddr *)&fromAddr, &addrLen);
Connection(&m_myUDPSock, &fromAddr); // M̏UDP\Pbg̒ʐMT[o[ƌŒ
// Mf[^ɃT[o[̃_l܂܂Ă̂ŁAǨvZ@ŕϊsԐMivZ̓}NgĒ`Ăj
work.Msg.Body0.rndNo = MAKE_ATTESTATION_NO; // ǨvZ@ŒlύX
send(this->m_myUDPSock, work.data, sizeof(MsgData), 0); // ύXf[^𑗐M
return false;
}
bool C_CLManager::Connection(SOCKET* sock, sockaddr_in* addr){
int sts;
int addrLen = sizeof(sockaddr);
sts = connect(*sock, (struct sockaddr *) addr, addrLen);
if (this->m_commCheck.CheckCommError(sts)){
return true;
}
return false;
}
bool C_CLManager::SendGameData(char* data, int dataSize){
return false;
}
bool C_CLManager::GetNewData(char* buff, int buffSize){
return false;
}
| true |
3978117b5d9411bbd3837aa53d9acf3392381a15 | C++ | Kr31s/getWrecked | /PunchNetwork/PunchNetworkClient/mainClientTest.cpp | ISO-8859-1 | 2,639 | 2.625 | 3 | [] | no_license | //#include "Inc_BWNetworking.h"
//#include "Inc_SmartMacros.h"
//#include "Inc_BWMath.h"
//
//#include <stdexcept>
//#include <thread>
//#include <chrono>
//
//void ClientMethod();
//void ServerMethod();
//unsigned int EncodeMessage(char identifier, char* messageArray);
//void DecodeMessage(char* messageArray);
//
//bool gameIsRunning = true;
//
//void main()
//{
// std::thread t1(ServerMethod);
//
// int i;
// std::cin >> i;
//}
//
//void ClientMethod()
//{
// NetSocketUDP udpSocket;
// NetAddress address(93, 201, 86, 44, 4405);
//
// unsigned char sendArray1[]{ "Netzwerk luft woop woop woop woop woop woop woop" };
// unsigned char sendArray2[]{ "Netzwerk luft!!" };
//
// NetPackage package(&address, sendArray2, sizeof(sendArray2));
//
// Println(BWNet::InitializeSocketLayer().m_errorCode);
// Println(udpSocket.OpenSocket(0).m_errorCode);
// Println(udpSocket.Send(package).m_errorCode);
//}
//
//void ServerMethod()
//{
// NetSocketUDP udpSocket;
// unsigned char receiveArray[4];
//
//
// Print("InitializeSocketLayer: ");
// Println(BWNet::InitializeSocketLayer().m_errorCode);
// Print("OpenSocket 4405: ");
// Println(udpSocket.OpenSocket(4405).m_errorCode);
// Print("Is Socket 4405 open ? ");
// Println(((udpSocket.IsOpen() == 1) ? "true" : "false"));
// Print("Enable Non-Blocking: ");
// Println(udpSocket.EnableNonBlocking().m_errorCode);
//
// ReceiveResult resultUDP;
// int a = 0;
// while (gameIsRunning)
// {
// resultUDP = udpSocket.Receive(receiveArray, 50);
// if (resultUDP.GetPort() != NULL)
// {
// for (int i = 0; i < 50; ++i)
// Print(receiveArray[i]);
//
// DecodeMessage((char*)receiveArray);
// //Println("");
// //Println(resultUDP.GetAdress());
// //Println(resultUDP.GetPort());
// }
// std::this_thread::sleep_for(std::chrono::milliseconds(16));
// }
//}
//
//unsigned int EncodeMessage(char identifier, char* messageArray)
//{
// switch (identifier) {
//
// case 0://Ingame Message
// return messageArray[1] | (messageArray[0] < 12) | (identifier < 25);
// break;
// default:
// throw std::invalid_argument("The identifier is undefined");
// break;
//
// }
// //get identifier
//}
//
//void DecodeMessage(char* messageArray)
//{
// //get identifier
// unsigned char identifier = messageArray[0] > 1;
//
// Println("Identifier: " << identifier);
//
// switch (identifier) {
//
// case 0://Ingame Message
// unsigned int timeFrame = (static_cast<unsigned int>(messageArray[0] < 7) < 5) | (static_cast<unsigned int>(messageArray[1] < 4)) | (static_cast<unsigned int>(messageArray[1] > 4));
// Println("TimeFrame: " << timeFrame);
// break;
// }
// //get identifier
//} | true |
9c208a4d75139503b95248c27565eec106504cb5 | C++ | herbyuan/OpenJudge_Code | /20181110红与黑.cpp | UTF-8 | 1,059 | 3.59375 | 4 | [] | no_license | /*
*程序名:红与黑
*作者:何卓远
*编制时间:2018-11-23
*功能:有一间长方形的房子,地上铺了红色、黑色两种颜色的正方形瓷砖。你站在其中一块黑色的瓷砖上,只能向相邻的四块瓷砖中的黑色瓷砖移动。请写一个程序,计算你总共能够到达多少块黑色的瓷砖。
*/
#include <iostream>
#include <cstring>
using namespace std;
char tiles[21][21];
int W, H;
int move(int x, int y)
{
if (x < 0 || x >= H || y < 0 || y >= W) return 0;
if (tiles[x][y] == '#') return 0;
tiles[x][y] = '#';
return 1 + move(x - 1, y) + move(x + 1, y) + move(x, y + 1) + move(x, y - 1);
}
int main(int argc, char const *argv[])
{
int ans;
while (1)
{
cin >> W >> H;
if (W == 0 && H == 0) return 0;
memset(tiles, 0, sizeof(tiles));
for (int i = 0; i < H; i++)
{
for (int j = 0; j < W; j++)
{
cin >> tiles[i][j];
}
}
for (int i = 0; i < H; i++)
for (int j = 0; j < W; j++)
if (tiles[i][j] == '@')
ans = move(i, j);
cout << ans << endl;
}
return 0;
} | true |
c8f2b3febee82de45367b385c230a45425b23c64 | C++ | likeweilikewei/Algorithm-Data-Structure-Implement | /动态规划/菲波那切数列/fibonacci.cpp | UTF-8 | 1,474 | 3.4375 | 3 | [] | no_license | // 动态规划.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
/*斐波那契数列f(1)=1,f(2)=1*/
#include <iostream>
#include<time.h>
#include"recursion.h"
#include"top_down_dynamic_programming.h"
#include"down_top_dynamic_programming.h"
using namespace std;
int main()
{
//cpu1s运行的时钟周期数,1000表示一个时钟周期是1ms
//cout << CLOCKS_PER_SEC << endl;;
clock_t start, end;
int n = 30;
//得到当前在第几个时钟周期
start = clock();
//cout << start << endl;
int result1 = fib_recursion(n);
end = clock();
//cout << end << endl;
//得到时钟周期数,换算成秒
printf("%d fibonacci result is: %d, recursion cost time: %f seconds.\n", n, result1, (double)(end - start) / CLOCKS_PER_SEC);
start = clock();
int result2 = fib_top_down_dp(n);
end = clock();
printf("%d fibonacci result is: %d, top down cost time: %f seconds.\n", n, result2, (double)(end - start) / CLOCKS_PER_SEC);
/*自底向上动态规划*/
start = clock();
int result3 = fib_down_top_dp(n);
end = clock();
printf("%d fibonacci result is: %d, down to top cost time: %f seconds.\n", n, result3, (double)(end - start) / CLOCKS_PER_SEC);
/*自底向上动态规划,空间优化*/
start = clock();
int result4 = fib_down_to_top_dp_optimize(n);
end = clock();
printf("%d fibonacci result is: %d, down to top optimize cost time: %f seconds.\n", n, result4, (double)(end - start) / CLOCKS_PER_SEC);
}
| true |
6828781f8aba75e6fb7acc63a198a8f7fd3eb300 | C++ | amplab/zipg | /core/include/bitmap.h | UTF-8 | 10,216 | 2.515625 | 3 | [] | no_license | #ifndef BITMAP_H_
#define BITMAP_H_
#include <cstdint>
#include <cassert>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <iostream>
namespace bitmap {
#define GETBIT(n, i) ((n >> i) & 1UL)
#define SETBIT(n, i) n = (n | (1UL << i))
#define CLRBIT(n, i) n = (n & ~(1UL << i))
#define BITS2BLOCKS(bits) \
(((bits) % 64 == 0) ? ((bits) / 64) : (((bits) / 64) + 1))
#define GETBITVAL(data, i) GETBIT((data)[(i) / 64], (i) % 64)
#define SETBITVAL(data, i) SETBIT((data)[(i) / 64], (i) % 64)
#define CLRBITVAL(data, i) CLRBIT((data)[(i) / 64], (i) % 64)
const uint64_t all_set = -1ULL;
static const uint64_t high_bits_set[65] = { 0x0000000000000000ULL,
0x8000000000000000ULL, 0xC000000000000000ULL, 0xE000000000000000ULL,
0xF000000000000000ULL, 0xF800000000000000ULL, 0xFC00000000000000ULL,
0xFE00000000000000ULL, 0xFF00000000000000ULL, 0xFF80000000000000ULL,
0xFFC0000000000000ULL, 0xFFE0000000000000ULL, 0xFFF0000000000000ULL,
0xFFF8000000000000ULL, 0xFFFC000000000000ULL, 0xFFFE000000000000ULL,
0xFFFF000000000000ULL, 0xFFFF800000000000ULL, 0xFFFFC00000000000ULL,
0xFFFFE00000000000ULL, 0xFFFFF00000000000ULL, 0xFFFFF80000000000ULL,
0xFFFFFC0000000000ULL, 0xFFFFFE0000000000ULL, 0xFFFFFF0000000000ULL,
0xFFFFFF8000000000ULL, 0xFFFFFFC000000000ULL, 0xFFFFFFE000000000ULL,
0xFFFFFFF000000000ULL, 0xFFFFFFF800000000ULL, 0xFFFFFFFC00000000ULL,
0xFFFFFFFE00000000ULL, 0xFFFFFFFF00000000ULL, 0xFFFFFFFF80000000ULL,
0xFFFFFFFFC0000000ULL, 0xFFFFFFFFE0000000ULL, 0xFFFFFFFFF0000000ULL,
0xFFFFFFFFF8000000ULL, 0xFFFFFFFFFC000000ULL, 0xFFFFFFFFFE000000ULL,
0xFFFFFFFFFF000000ULL, 0xFFFFFFFFFF800000ULL, 0xFFFFFFFFFFC00000ULL,
0xFFFFFFFFFFE00000ULL, 0xFFFFFFFFFFF00000ULL, 0xFFFFFFFFFFF80000ULL,
0xFFFFFFFFFFFC0000ULL, 0xFFFFFFFFFFFE0000ULL, 0xFFFFFFFFFFFF0000ULL,
0xFFFFFFFFFFFF8000ULL, 0xFFFFFFFFFFFFC000ULL, 0xFFFFFFFFFFFFE000ULL,
0xFFFFFFFFFFFFF000ULL, 0xFFFFFFFFFFFFF800ULL, 0xFFFFFFFFFFFFFC00ULL,
0xFFFFFFFFFFFFFE00ULL, 0xFFFFFFFFFFFFFF00ULL, 0xFFFFFFFFFFFFFF80ULL,
0xFFFFFFFFFFFFFFC0ULL, 0xFFFFFFFFFFFFFFE0ULL, 0xFFFFFFFFFFFFFFF0ULL,
0xFFFFFFFFFFFFFFF8ULL, 0xFFFFFFFFFFFFFFFCULL, 0xFFFFFFFFFFFFFFFEULL,
0xFFFFFFFFFFFFFFFFULL };
static const uint64_t high_bits_unset[65] = { 0xFFFFFFFFFFFFFFFFULL,
0x7FFFFFFFFFFFFFFFULL, 0x3FFFFFFFFFFFFFFFULL, 0x1FFFFFFFFFFFFFFFULL,
0x0FFFFFFFFFFFFFFFULL, 0x07FFFFFFFFFFFFFFULL, 0x03FFFFFFFFFFFFFFULL,
0x01FFFFFFFFFFFFFFULL, 0x00FFFFFFFFFFFFFFULL, 0x007FFFFFFFFFFFFFULL,
0x003FFFFFFFFFFFFFULL, 0x001FFFFFFFFFFFFFULL, 0x000FFFFFFFFFFFFFULL,
0x0007FFFFFFFFFFFFULL, 0x0003FFFFFFFFFFFFULL, 0x0001FFFFFFFFFFFFULL,
0x0000FFFFFFFFFFFFULL, 0x00007FFFFFFFFFFFULL, 0x00003FFFFFFFFFFFULL,
0x00001FFFFFFFFFFFULL, 0x00000FFFFFFFFFFFULL, 0x000007FFFFFFFFFFULL,
0x000003FFFFFFFFFFULL, 0x000001FFFFFFFFFFULL, 0x000000FFFFFFFFFFULL,
0x0000007FFFFFFFFFULL, 0x0000003FFFFFFFFFULL, 0x0000001FFFFFFFFFULL,
0x0000000FFFFFFFFFULL, 0x00000007FFFFFFFFULL, 0x00000003FFFFFFFFULL,
0x00000001FFFFFFFFULL, 0x00000000FFFFFFFFULL, 0x000000007FFFFFFFULL,
0x000000003FFFFFFFULL, 0x000000001FFFFFFFULL, 0x000000000FFFFFFFULL,
0x0000000007FFFFFFULL, 0x0000000003FFFFFFULL, 0x0000000001FFFFFFULL,
0x0000000000FFFFFFULL, 0x00000000007FFFFFULL, 0x00000000003FFFFFULL,
0x00000000001FFFFFULL, 0x00000000000FFFFFULL, 0x000000000007FFFFULL,
0x000000000003FFFFULL, 0x000000000001FFFFULL, 0x000000000000FFFFULL,
0x0000000000007FFFULL, 0x0000000000003FFFULL, 0x0000000000001FFFULL,
0x0000000000000FFFULL, 0x00000000000007FFULL, 0x00000000000003FFULL,
0x00000000000001FFULL, 0x00000000000000FFULL, 0x000000000000007FULL,
0x000000000000003FULL, 0x000000000000001FULL, 0x000000000000000FULL,
0x0000000000000007ULL, 0x0000000000000003ULL, 0x0000000000000001ULL,
0x0000000000000000ULL };
static const uint64_t low_bits_set[65] = { 0x0000000000000000ULL,
0x0000000000000001ULL, 0x0000000000000003ULL, 0x0000000000000007ULL,
0x000000000000000FULL, 0x000000000000001FULL, 0x000000000000003FULL,
0x000000000000007FULL, 0x00000000000000FFULL, 0x00000000000001FFULL,
0x00000000000003FFULL, 0x00000000000007FFULL, 0x0000000000000FFFULL,
0x0000000000001FFFULL, 0x0000000000003FFFULL, 0x0000000000007FFFULL,
0x000000000000FFFFULL, 0x000000000001FFFFULL, 0x000000000003FFFFULL,
0x000000000007FFFFULL, 0x00000000000FFFFFULL, 0x00000000001FFFFFULL,
0x00000000003FFFFFULL, 0x00000000007FFFFFULL, 0x0000000000FFFFFFULL,
0x0000000001FFFFFFULL, 0x0000000003FFFFFFULL, 0x0000000007FFFFFFULL,
0x000000000FFFFFFFULL, 0x000000001FFFFFFFULL, 0x000000003FFFFFFFULL,
0x000000007FFFFFFFULL, 0x00000000FFFFFFFFULL, 0x00000001FFFFFFFFULL,
0x00000003FFFFFFFFULL, 0x00000007FFFFFFFFULL, 0x0000000FFFFFFFFFULL,
0x0000001FFFFFFFFFULL, 0x0000003FFFFFFFFFULL, 0x0000007FFFFFFFFFULL,
0x000000FFFFFFFFFFULL, 0x000001FFFFFFFFFFULL, 0x000003FFFFFFFFFFULL,
0x000007FFFFFFFFFFULL, 0x00000FFFFFFFFFFFULL, 0x00001FFFFFFFFFFFULL,
0x00003FFFFFFFFFFFULL, 0x00007FFFFFFFFFFFULL, 0x0000FFFFFFFFFFFFULL,
0x0001FFFFFFFFFFFFULL, 0x0003FFFFFFFFFFFFULL, 0x0007FFFFFFFFFFFFULL,
0x000FFFFFFFFFFFFFULL, 0x001FFFFFFFFFFFFFULL, 0x003FFFFFFFFFFFFFULL,
0x007FFFFFFFFFFFFFULL, 0x00FFFFFFFFFFFFFFULL, 0x01FFFFFFFFFFFFFFULL,
0x03FFFFFFFFFFFFFFULL, 0x07FFFFFFFFFFFFFFULL, 0x0FFFFFFFFFFFFFFFULL,
0x1FFFFFFFFFFFFFFFULL, 0x3FFFFFFFFFFFFFFFULL, 0x7FFFFFFFFFFFFFFFULL,
0xFFFFFFFFFFFFFFFFULL };
static const uint64_t low_bits_unset[65] = { 0xFFFFFFFFFFFFFFFFULL,
0xFFFFFFFFFFFFFFFEULL, 0xFFFFFFFFFFFFFFFCULL, 0xFFFFFFFFFFFFFFF8ULL,
0xFFFFFFFFFFFFFFF0ULL, 0xFFFFFFFFFFFFFFE0ULL, 0xFFFFFFFFFFFFFFC0ULL,
0xFFFFFFFFFFFFFF80ULL, 0xFFFFFFFFFFFFFF00ULL, 0xFFFFFFFFFFFFFE00ULL,
0xFFFFFFFFFFFFFC00ULL, 0xFFFFFFFFFFFFF800ULL, 0xFFFFFFFFFFFFF000ULL,
0xFFFFFFFFFFFFE000ULL, 0xFFFFFFFFFFFFC000ULL, 0xFFFFFFFFFFFF8000ULL,
0xFFFFFFFFFFFF0000ULL, 0xFFFFFFFFFFFE0000ULL, 0xFFFFFFFFFFFC0000ULL,
0xFFFFFFFFFFF80000ULL, 0xFFFFFFFFFFF00000ULL, 0xFFFFFFFFFFE00000ULL,
0xFFFFFFFFFFC00000ULL, 0xFFFFFFFFFF800000ULL, 0xFFFFFFFFFF000000ULL,
0xFFFFFFFFFE000000ULL, 0xFFFFFFFFFC000000ULL, 0xFFFFFFFFF8000000ULL,
0xFFFFFFFFF0000000ULL, 0xFFFFFFFFE0000000ULL, 0xFFFFFFFFC0000000ULL,
0xFFFFFFFF80000000ULL, 0xFFFFFFFF00000000ULL, 0xFFFFFFFE00000000ULL,
0xFFFFFFFC00000000ULL, 0xFFFFFFF800000000ULL, 0xFFFFFFF000000000ULL,
0xFFFFFFE000000000ULL, 0xFFFFFFC000000000ULL, 0xFFFFFF8000000000ULL,
0xFFFFFF0000000000ULL, 0xFFFFFE0000000000ULL, 0xFFFFFC0000000000ULL,
0xFFFFF80000000000ULL, 0xFFFFF00000000000ULL, 0xFFFFE00000000000ULL,
0xFFFFC00000000000ULL, 0xFFFF800000000000ULL, 0xFFFF000000000000ULL,
0xFFFE000000000000ULL, 0xFFFC000000000000ULL, 0xFFF8000000000000ULL,
0xFFF0000000000000ULL, 0xFFE0000000000000ULL, 0xFFC0000000000000ULL,
0xFF80000000000000ULL, 0xFF00000000000000ULL, 0xFE00000000000000ULL,
0xFC00000000000000ULL, 0xF800000000000000ULL, 0xF000000000000000ULL,
0xE000000000000000ULL, 0xC000000000000000ULL, 0x8000000000000000ULL,
0x0000000000000000ULL };
class Bitmap {
public:
// Type definitions
typedef size_t pos_type;
typedef size_t size_type;
typedef uint64_t data_type;
typedef uint8_t width_type;
// Constructors and Destructors
Bitmap() {
data_ = NULL;
}
Bitmap(size_type num_bits) {
data_ = new data_type[BITS2BLOCKS(num_bits)]();
}
virtual ~Bitmap() {
if (data_ != NULL) {
delete[] data_;
data_ = NULL;
}
}
// Getters
data_type* GetData() {
return data_;
}
void SetBit(pos_type i) {
SETBITVAL(data_, i);
}
void UnsetBit(pos_type i) {
CLRBITVAL(data_, i);
}
bool GetBit(pos_type i) const {
return GETBITVAL(data_, i);
}
// Integer operations
void SetValPos(pos_type pos, data_type val, width_type bits) {
pos_type s_off = pos % 64;
pos_type s_idx = pos / 64;
if (s_off + bits <= 64) {
// Can be accommodated in 1 bitmap block
data_[s_idx] = (data_[s_idx]
& (low_bits_set[s_off] | low_bits_unset[s_off + bits]))
| val << s_off;
} else {
// Must use 2 bitmap blocks
data_[s_idx] = (data_[s_idx] & low_bits_set[s_off]) | val << s_off;
data_[s_idx + 1] =
(data_[s_idx + 1] & low_bits_unset[(s_off + bits) % 64])
| (val >> (64 - s_off));
}
}
data_type GetValPos(pos_type pos, width_type bits) const {
pos_type s_off = pos % 64;
pos_type s_idx = pos / 64;
if (s_off + bits <= 64) {
// Can be read from a single block
return (data_[s_idx] >> s_off) & low_bits_set[bits];
} else {
// Must be read from two blocks
return ((data_[s_idx] >> s_off) | (data_[s_idx + 1] << (64 - s_off)))
& low_bits_set[bits];
}
}
// Serialization/De-serialization
size_type Serialize(std::ostream& out, size_type size) {
size_t out_size = 0;
out.write(reinterpret_cast<const char *>(&size), sizeof(size_type));
out_size += sizeof(size_type);
out.write(reinterpret_cast<const char *>(data_),
sizeof(data_type) * BITS2BLOCKS(size));
out_size += (BITS2BLOCKS(size) * sizeof(uint64_t));
return out_size;
}
size_type Deserialize(std::istream& in) {
size_type size;
in.read(reinterpret_cast<char *>(&size), sizeof(size_type));
sizeof(size_type);
data_ = new data_type[BITS2BLOCKS(size)];
in.read(reinterpret_cast<char *>(data_),
BITS2BLOCKS(size) * sizeof(data_type));
(BITS2BLOCKS(size) * sizeof(data_type));
memset(data_, (BITS2BLOCKS(size) * sizeof(data_type)), 0);
return size;
}
size_type MemoryMap(uint8_t* buf) {
uint8_t *data, *data_beg;
data = data_beg = buf;
uint64_t bitmap_size = *((size_type *) data);
data += sizeof(size_type);
if (bitmap_size) {
data_ = (data_type*) data;
size_type bitmap_size_bytes = (BITS2BLOCKS(bitmap_size) * sizeof(data_type));
data += bitmap_size_bytes;
}
memset(data_, (BITS2BLOCKS(bitmap_size) * sizeof(data_type)), 0);
return data - data_beg;
}
protected:
// Data members
data_type *data_;
};
}
#endif
| true |
d9581eaee3692a436147ee5e8d0180f53151cae9 | C++ | marmysh/FDK | /FDK/LlCommon/PriceEntries.h | UTF-8 | 999 | 2.546875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "PriceEntry.h"
namespace FDK
{
class CPriceEntries
{
public:
LLCOMMON_API CPriceEntries();
LLCOMMON_API CPriceEntries(const CPriceEntries& entries);
LLCOMMON_API CPriceEntries& operator = (const CPriceEntries& entries);
LLCOMMON_API ~CPriceEntries();
public:
inline void Update(const std::string& symbol, const double bid, const double ask)
{
Update(symbol.c_str(), bid, ask);
}
LLCOMMON_API void Update(const char* symbol, const double bid, const double ask);
inline void Remove(const std::string& symbol)
{
Remove(symbol.c_str());
}
LLCOMMON_API void Remove(const char* symbol);
LLCOMMON_API void Clear();
inline Nullable<CPriceEntry> TryGetPriceEntry(const std::string& symbol) const { return TryGetPriceEntry(symbol.c_str()); }
LLCOMMON_API Nullable<CPriceEntry> TryGetPriceEntry(const char* symbol) const;
internal:
const LrpMap(string, CPriceEntry)& GetEntries() const;
private:
LrpMap(string, CPriceEntry) m_entries;
};
} | true |
f8d04f54ecef569060ebda1e40d916381b23a911 | C++ | ananddasani/STL_C-Plus-Plus | /STACK/1_Stack_STL.cpp | UTF-8 | 1,058 | 4.375 | 4 | [
"MIT"
] | permissive | /*
Stacks are a type of container adaptors with LIFO(Last In First Out) type of working,
where a new element is added at one end and (top) an element is removed from that end only.
Stack uses an encapsulated object of either vector or deque (by default) or list (sequential container class) as its underlying container,
providing a specific set of member functions to access its elements.
*/
#include <iostream>
#include <stack>
using namespace std;
void showStack(stack<int> st)
{
while (!st.empty())
{
cout << " " << st.top() << endl;
st.pop();
}
cout << endl;
}
int main()
{
stack<int> st;
//insert elements using push function , pop for remove
for (int i = 1; i < 10; i++)
st.push(i * 10);
cout << "\nSTACK" << endl;
showStack(st);
//check the top element
cout << "Top element :: " << st.top() << endl;
cout << "Size of stack :: " << st.size() << endl;
return 0;
}
/*
TEST CASE
STACK
90
80
70
60
50
40
30
20
10
Top element :: 90
Size of stack :: 9
*/
| true |
32cd0200f6c9e57d72fca6b4795c729a7b9965ce | C++ | Bodheem/ProjetIntegrateur3 | /Client Lourd/Sources/DLL/Memento/Memento.h | UTF-8 | 1,138 | 2.9375 | 3 | [] | no_license | //////////////////////////////////////////////////////////////////////////////
/// @file Memento.h
/// @author The Ballers
/// @date 2015-02-25
/// @version 1.0
///
/// @ingroup Memento
//////////////////////////////////////////////////////////////////////////////
#ifndef __MEMENTO_H__
#define __MEMENTO_H__
#include <map>
class ArbreRenduINF2990;
class NoeudAbstrait;
///////////////////////////////////////////////////////////////////////////
/// @class Memento
/// @brief Structure de donnee qui contient les informations utiles pour sauvegarder l'arbre.
///
/// @author The Ballers
/// @date 2015-02-24
///////////////////////////////////////////////////////////////////////////
class Memento
{
public:
/// Constructeur
Memento(ArbreRenduINF2990* arbreAEnregistrer);
/// Destructeur
~Memento();
/// Obtenir la sauvegarde
std::map<int, NoeudAbstrait*> obtenirSauvegarde() const { return sauvegarde; };
private:
/// Enregistrer l'information des noeuds
void sauvegarder(ArbreRenduINF2990* arbreAEnregistrer);
/// Structure de donnee qui contient l'information des noeuds
std::map<int, NoeudAbstrait*> sauvegarde;
};
#endif | true |
b6c1a5862e62651e50d436e61ae7ce46376e936f | C++ | jinho9317/Algorithm | /소문난 칠공주.cpp | UHC | 1,626 | 3.0625 | 3 | [] | no_license | #include<iostream>
#include<queue>
#include<cstring>
using namespace std;
char arr[5][6];
bool check[5][5], visit[5][5]; // check : ڸ, visit : Ȯ
int result;
int dy[] = { 1,-1,0,0 };
int dx[] = { 0,0,1,-1 };
queue<pair<int, int>> q;
void go() {
int cnt = 0;
while (!q.empty()) {
int y = q.front().first;
int x = q.front().second;
cnt++;
q.pop();
for (int k = 0; k < 4; k++) {
int ny = y + dy[k];
int nx = x + dx[k];
if (ny < 0 || nx < 0 || ny >= 5 || nx >= 5 || !check[ny][nx] || visit[ny][nx]) continue;
visit[ny][nx] = true;
q.push(make_pair(ny, nx));
}
}
if (cnt == 7)
result++;
}
void solve(int num, int cnt, int s) {
// 1. 7 ڸ
// 2. Ȯ
if (cnt >= 7) {
if (s < 4) return;
memset(visit, false, sizeof(visit));
bool done = false;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (!check[i][j]) continue;
visit[i][j] = true;
q.push(make_pair(i, j));
done = true;
break;
}
if (done)
break;
}
go();
return;
}
for (int i = num + 1; i < 25; i++) {
check[i / 5][i % 5] = true;
if (arr[i / 5][i % 5] == 'S')
solve(i, cnt + 1, s + 1);
else
solve(i, cnt + 1, s);
check[i / 5][i % 5] = false;
}
}
int main() {
for (int i = 0; i < 5; i++)
cin >> arr[i];
for (int i = 0; i < 25; i++) {
check[i / 5][i % 5] = true;
if (arr[i / 5][i % 5] == 'S')
solve(i, 1, 1);
else
solve(i, 1, 0);
check[i / 5][i % 5] = false;
}
cout << result << endl;
return 0;
} | true |
95092c357d76db40424533400e4ec4ed9322510a | C++ | prasadnallani/LeetCodeProblems | /Medium/695-MaxAreaOfIsland.cpp | UTF-8 | 2,473 | 3.65625 | 4 | [] | no_license |
/*
* Author: Raghavendra Mallela
*/
/*
* LeetCode 695: Max Area Of Island
*
* You are given an m x n binary matrix grid. An island is a group of 1's
* (representing land) connected 4-directionally (horizontal or vertical.)
* You may assume all four edges of the grid are surrounded by water.
*
* The area of an island is the number of cells with a value 1 in the island.
* Return the maximum area of an island in grid. If there is no island, return 0.
*
* Example 1:
* Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],
* [0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],
* [0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],
* [0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
*
* Output: 6
* Explanation: The answer is not 11, because the island must be connected
* 4-directionally.
*
* Example 2:
* Input: grid = [[0,0,0,0,0,0,0,0]]
* Output: 0
*
* Constraints:
* m == grid.length
* n == grid[i].length
* 1 <= m, n <= 50
* grid[i][j] is either 0 or 1.
*/
/*
* Approach followed is a dfs algo to find area of the island
*/
int dfsarea(vector<vector<int>>& grid, int row, int col) {
// Check the boundary conditions ie.., grid bounds
if (row < 0 || row >= grid.size() || col < 0 || col >= grid[0].size()) {
// out of bounds
return 0;
}
// Check if it is an island or not
if (grid[row][col] == 0) {
// current element is not an island
return 0;
}
// As we need to check 4 sides of an island, Change the current
// island to water so that we can avoid this one as it is already
// visited
grid[row][col] = 0;
// Evaluate the no of islands surounded the current island
// up, down, left, right
int area = 1 + dfsarea(grid, row - 1, col) + dfsarea(grid, row + 1, col)
+ dfsarea(grid, row, col - 1) + dfsarea(grid, row, col + 1);
return area;
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
// Variable to store the max area of the island
int maxarea = 0;
// Traverse the grid
for (int row = 0; row < grid.size(); row++) {
for (int col = 0; col < grid[0].size(); col++) {
// check if the value is an island or not
if (grid[row][col] == 1) {
// Its an island, procced and check the area
maxarea = max(maxarea, dfsarea(grid, row, col));
}
}
}
return maxarea;
}
| true |
016da8063909ae4174645ba00e3f4957c2f96083 | C++ | BelfordZ/cpsc3200 | /awesome-o/acpc/2006/F.cc | UTF-8 | 1,334 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <queue>
#include <cstdio>
using namespace std;
struct Range {
int rook, lo, hi;
};
#define MAX_ROOK 5000
Range xrange[MAX_ROOK], yrange[MAX_ROOK];
int x[MAX_ROOK], y[MAX_ROOK];
int n;
bool operator<(const Range &a, const Range &b)
{
return a.lo < b.lo;
}
class Compare {
public:
bool operator()(const Range &a, const Range &b)
{
return a.hi > b.hi;
}
};
int main(void)
{
int i, bad = 0;
cin >> n;
for (i = 0; i < n; i++) {
xrange[i].rook = yrange[i].rook = i;
cin >> xrange[i].lo >> yrange[i].lo >> xrange[i].hi >> yrange[i].hi;
}
sort(xrange, xrange+n);
sort(yrange, yrange+n);
int xi = 0, yi = 0;
priority_queue< Range, vector<Range>, Compare > xq, yq;
for (i = 1; i <= n && !bad; i++) {
while (xi < n && xrange[xi].lo == i) {
xq.push(xrange[xi++]);
}
while (yi < n && yrange[yi].lo == i) {
yq.push(yrange[yi++]);
}
if (!xq.empty() && i <= xq.top().hi) {
x[xq.top().rook] = i;
xq.pop();
} else {
bad = 1;
}
if (!yq.empty() && i <= yq.top().hi) {
y[yq.top().rook] = i;
yq.pop();
} else {
bad = 1;
}
}
if (bad) {
printf("IMPOSSIBLE\n");
} else {
for (i = 0; i < n; i++) {
printf("%d %d\n", x[i], y[i]);
}
}
return 0;
}
| true |
f867166a446bea7d69bd19660665c9dc7de17232 | C++ | strinsberg/card-game-extravaganza | /include/RummyTable.h | UTF-8 | 1,403 | 3.59375 | 4 | [] | no_license | #ifndef RUMMY_TABLE_H
#define RUMMY_TABLE_H
#include <vector>
#include "Card.h"
/**
* Holds all melds and cards that have been played during a Rummy game.
*
* @author Steven Deutekom
* @date Nov 29 2019
*/
class RummyTable {
public:
RummyTable();
virtual ~RummyTable();
/**
* Add a meld to the table.
* Melds are sets or runs.
*
* @param meld The vector of cards representing a meld.
*/
virtual void addMeld(std::vector<Card*> meld);
/**
* Adds a card to a meld on the table.
* If there is no place to put the card throw an error.
*
* @precondition The card must be playable.
* @param card The card to play.
* @throws unmet_precondition_error if the card cannot be added to any meld.
*/
virtual void addCard(Card* c);
/**
* Returns a pointer to all the melds on the table.
*
* @return A vector of melds.
*/
virtual std::vector<std::vector<Card*>>& getMelds();
/**
* Returns a vector with all the cards and removes them from the table.
*
* @return All the cards on the table.
*/
virtual std::vector<Card*> takeAllCards();
/**
* Ensure that a meld is a valid set or a run.
*
* @return true if the meld is valid, otherwise false.
*/
virtual bool validateMeld(const std::vector<Card*>& meld);
protected:
std::vector<std::vector<Card*>> table;
bool isSet(const std::vector<Card*>& meld);
};
#endif
| true |
ba7edbcc39781f495c70b3bf8862da03747df74b | C++ | kirankhade/Programming-Practice | /Quicksort.cpp | UTF-8 | 763 | 3.1875 | 3 | [] | no_license | #include<iostream>
#include<stdlib.h>
using namespace std;
int a[10]={0,2,5,1,10,12,13,20,56,89};
int partition(int start,int end)
{
int i,j,pivot;
pivot=i=start;
j=end;
if(i<j)
{
while(i<j)
{
while(a[i]<=a[pivot])
i++;
while(a[j]>a[pivot])
j--;
if(i<j)
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
int temp=a[i];
a[i]=a[pivot];
a[pivot]=temp;
}
return i;
}
void Quicksort(int low,int high)
{
if(low<high)
{
int pivot=partition(low,high);
Quicksort(low,pivot-1);
Quicksort(pivot+1,high);
}
}
int main()
{
//int a[10]={0,2,5,1,10,12,13,20,56,89};
Quicksort(0,9);
for(int i=0;i<10;i++)
{
cout<<a[i]<<" ";
}
return 0;
}
| true |
3f8e988685e2fb5d920776aff6baf8ed827b7f00 | C++ | TrevorNewey/cs1410-Inheritance | /employee.cpp | UTF-8 | 333 | 2.796875 | 3 | [] | no_license | //
// Created by WAHUGALA on 10/19/2017.
//
#include "employee.h"
void employee::setData() {
cout<<"\n Enter last name";
cin>>name;
cin.ignore(); //Clears the buffer.
cout<<"\nEnter ID Number: ";
cin>>number;
}
void employee::getData() {
cout<<"\n Name: "<<name;
cout<<"\n IdNumber: "<<number;
}
| true |
147e8dd690c5da3b78d420eee96d968154ff7162 | C++ | iridium-browser/iridium-browser | /buildtools/third_party/libc++/trunk/test/std/utilities/smartptr/unique.ptr/unique.ptr.create/make_unique.array.pass.cpp | UTF-8 | 1,209 | 2.546875 | 3 | [
"NCSA",
"LLVM-exception",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++03, c++11
#include <memory>
#include <string>
#include <cassert>
#include "test_macros.h"
// The only way to create an unique_ptr<T[]> is to default construct them.
class foo {
public:
TEST_CONSTEXPR_CXX23 foo() : val_(3) {}
TEST_CONSTEXPR_CXX23 int get() const { return val_; }
private:
int val_;
};
TEST_CONSTEXPR_CXX23 bool test() {
{
auto p1 = std::make_unique<int[]>(5);
for (int i = 0; i < 5; ++i)
assert(p1[i] == 0);
}
{
auto p2 = std::make_unique<std::string[]>(5);
for (int i = 0; i < 5; ++i)
assert(p2[i].size() == 0);
}
{
auto p3 = std::make_unique<foo[]>(7);
for (int i = 0; i < 7; ++i)
assert(p3[i].get() == 3);
}
return true;
}
int main(int, char**) {
test();
#if TEST_STD_VER >= 23
static_assert(test());
#endif
return 0;
}
| true |
504d76328352b623de4a19590f1586ae28c1848f | C++ | haferflocken/ConductorEngine | /Amp/collection/LinearBlockAllocator.h | UTF-8 | 6,031 | 3.359375 | 3 | [] | no_license | #pragma once
#include <collection/Vector.h>
#include <unit/CountUnits.h>
#include <cstdint>
#include <mutex>
namespace Collection
{
/**
* An allocator that allows fixed size allocations. Implemented as a list of blocks of elements.
* Allocations and frees are thread-safe by mutex. No other methods have guaranteed thread-safety.
*/
class LinearBlockAllocator
{
public:
class iterator;
friend class iterator;
class const_iterator;
friend class const_iterator;
static constexpr size_t k_numElementsPerBlock = 64;
template <typename T>
static LinearBlockAllocator MakeFor()
{
return LinearBlockAllocator(alignof(T), sizeof(T));
}
LinearBlockAllocator() = default;
LinearBlockAllocator(size_t alignmentInBytes, size_t sizeInBytes)
: m_blocks()
, m_mutex()
, m_elementAlignmentInBytes(static_cast<uint32_t>(alignmentInBytes))
, m_elementSizeInBytes(static_cast<uint32_t>(Unit::AlignedSizeOf(sizeInBytes, alignmentInBytes)))
{}
LinearBlockAllocator(LinearBlockAllocator&&);
LinearBlockAllocator& operator=(LinearBlockAllocator&&);
~LinearBlockAllocator();
void* Alloc();
void Free(void* ptr);
bool IsEmpty() const;
iterator begin();
const_iterator begin() const;
const_iterator cbegin() const;
iterator end();
const_iterator end() const;
const_iterator cend() const;
private:
uint8_t& Get(uint32_t blockIndex, uint32_t indexInBlock);
const uint8_t& Get(uint32_t blockIndex, uint32_t indexInBlock) const;
struct Block
{
uint64_t m_vacancyMap{ UINT64_MAX };
void* m_memory{ nullptr };
};
Collection::Vector<Block> m_blocks;
std::mutex m_mutex;
uint32_t m_elementAlignmentInBytes{ 0 };
uint32_t m_elementSizeInBytes{ 0 };
};
class LinearBlockAllocator::iterator
{
public:
using difference_type = int64_t;
using value_type = uint8_t;
using pointer = uint8_t*;
using reference = uint8_t&;
using iterator_category = std::forward_iterator_tag;
iterator()
: m_allocator(nullptr)
, m_blockIndex(0)
, m_indexInBlock(0)
{}
iterator(LinearBlockAllocator& allocator, uint32_t blockIndex, uint32_t indexInBlock)
: m_allocator(&allocator)
, m_blockIndex(blockIndex)
, m_indexInBlock(indexInBlock)
{}
reference operator*() const { return m_allocator->Get(m_blockIndex, m_indexInBlock); }
pointer operator->() const { return &m_allocator->Get(m_blockIndex, m_indexInBlock); }
bool operator==(const iterator& rhs) const { return memcmp(this, &rhs, sizeof(iterator)) == 0; }
bool operator!=(const iterator& rhs) const { return !(*this == rhs); }
iterator& operator++();
iterator operator++(int) { iterator temp = *this; ++*this; return temp; }
private:
LinearBlockAllocator* m_allocator;
uint32_t m_blockIndex;
uint32_t m_indexInBlock;
};
class LinearBlockAllocator::const_iterator
{
public:
using difference_type = int64_t;
using value_type = uint8_t;
using pointer = const uint8_t*;
using reference = const uint8_t&;
using iterator_category = std::forward_iterator_tag;
const_iterator()
: m_allocator(nullptr)
, m_blockIndex(0)
, m_indexInBlock(0)
{}
const_iterator(const LinearBlockAllocator& allocator, uint32_t blockIndex, uint32_t indexInBlock)
: m_allocator(&allocator)
, m_blockIndex(blockIndex)
, m_indexInBlock(indexInBlock)
{}
reference operator*() const { return m_allocator->Get(m_blockIndex, m_indexInBlock); }
pointer operator->() const { return &m_allocator->Get(m_blockIndex, m_indexInBlock); }
bool operator==(const const_iterator& rhs) const { return memcmp(this, &rhs, sizeof(const_iterator)) == 0; }
bool operator!=(const const_iterator& rhs) const { return !(*this == rhs); }
const_iterator& operator++();
const_iterator operator++(int) { const_iterator temp = *this; ++*this; return temp; }
private:
const LinearBlockAllocator* m_allocator;
uint32_t m_blockIndex;
uint32_t m_indexInBlock;
};
}
// Inline implementations: LinearBlockAllocator
namespace Collection
{
inline LinearBlockAllocator::iterator LinearBlockAllocator::begin()
{
return iterator(*this, 0, 0);
}
inline LinearBlockAllocator::const_iterator LinearBlockAllocator::begin() const
{
return const_iterator(*this, 0, 0);
}
inline LinearBlockAllocator::const_iterator LinearBlockAllocator::cbegin() const { return begin(); }
inline LinearBlockAllocator::iterator LinearBlockAllocator::end()
{
return iterator(*this, m_blocks.Size(), 0);
}
inline LinearBlockAllocator::const_iterator LinearBlockAllocator::end() const
{
return const_iterator(*this, m_blocks.Size(), 0);
}
inline LinearBlockAllocator::const_iterator LinearBlockAllocator::cend() const { return end(); }
inline uint8_t& LinearBlockAllocator::Get(uint32_t blockIndex, uint32_t indexInBlock)
{
// Implemented in terms of the const variant.
return const_cast<uint8_t&>(static_cast<const LinearBlockAllocator*>(this)->Get(blockIndex, indexInBlock));
}
inline const uint8_t& LinearBlockAllocator::Get(uint32_t blockIndex, uint32_t indexInBlock) const
{
const uint8_t* const blockMem = reinterpret_cast<const uint8_t*>(m_blocks[blockIndex].m_memory);
return *(blockMem + (m_elementSizeInBytes * indexInBlock));
}
}
// Inline implementations: LinearBlockAllocator::iterator and const_iterator
namespace Collection
{
inline LinearBlockAllocator::iterator& LinearBlockAllocator::iterator::operator++()
{
const auto& blocks = m_allocator->m_blocks;
// Increment to the next non-vacant index.
do
{
++m_indexInBlock;
if (m_indexInBlock >= 64)
{
++m_blockIndex;
m_indexInBlock = 0;
}
} while (m_blockIndex < blocks.Size() && (blocks[m_blockIndex].m_vacancyMap & (1ui64 << m_indexInBlock)) != 0);
return *this;
}
inline LinearBlockAllocator::const_iterator& LinearBlockAllocator::const_iterator::operator++()
{
const auto& blocks = m_allocator->m_blocks;
// Increment to the next non-vacant index.
do
{
++m_indexInBlock;
if (m_indexInBlock >= 64)
{
++m_blockIndex;
m_indexInBlock = 0;
}
} while (m_blockIndex < blocks.Size() && (blocks[m_blockIndex].m_vacancyMap & (1ui64 << m_indexInBlock)) != 0);
return *this;
}
}
| true |
6b05cdd6f586d193dc9bca2913b52fc81974bc1a | C++ | CodingWD/course | /c/yaojianjiao/chapter02/bool.cpp | UTF-8 | 552 | 3.546875 | 4 | [] | no_license | #include <iostream>
using namespace std;
// 定义全局bool型变量
bool b;
int main() {
// 定局部义bool型变量
bool c;
// 不进行初始化,直接输出b
cout<<"b= "<< b <<endl;
cout<<"c= "<< c <<endl;
// 获取bool型变量存储空间大小。
cout<< "bool 类型的存储空间大小是: "
<< sizeof(bool)<<" 字节 "<<endl;
// 输出bool值
b = 0;
cout <<"b= "<< b <<endl;
b = 1;
cout <<"b= "<< b <<endl;
return 0;
}
| true |
c02f2ea304321f2b5ba26532687174d4a8c3aab6 | C++ | sajidazhar/Algorithms | /Dynamic Programming/number_of_ways_to_cover_distance.cpp | UTF-8 | 321 | 2.984375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int countways(int dist)
{
int count[dist+1];
count[0]=1,count[1]=1,count[2]=2;
for(int i=3;i<=dist;i++)
count[i]=count[i-1]+count[i-2]+count[i-3];
return count[dist];
}
int main()
{
int dist=6;
cout<<"total ways is : "<<countways(dist);
return 0;
}
| true |
32d328aebaf5621ad474a283c34255a20950589e | C++ | Jona2010/Lenguaje-de-programacion | /Lab 1/Par e impar.cpp | UTF-8 | 213 | 3.171875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int a;
cout<<"Ingrese un valor:\n";
cin>>a;
if(a%2==0)
{
cout<<a<<" es un numero par"<<endl;
}
else
{
cout<<a<<" es un numero impar"<<endl;
}
}
| true |
775d1757c6eaee36299bb9149e2bd0be6180efb1 | C++ | freezeeyes/ESP32-DevKitC_STUDY | /esp32_led_2/esp32_led_2.ino | UTF-8 | 567 | 3.0625 | 3 | [] | no_license | #define HIGH (1)
#define LOW (0)
#define LED_PIN 22
int flag = HIGH;
void setup()
{
// シリアル通信の通信速度を指定する
Serial.begin(115200);
// LED用のピンを出力モードに指定する
pinMode(LED_PIN, OUTPUT);
}
void loop()
{
// LEDの出力値を切り替える
flag = flag ? LOW : HIGH;
// LED状態を送信する
Serial.println(flag ? "LED ON" : "LED OFF");
// LEDの点灯消灯を制御する
digitalWrite(LED_PIN, flag);
// マイクロ秒指定で1秒間待機する
delayMicroseconds(1000000);
}
| true |
5b533b4f20a5e804bdfd263aae4e8398a18f7fe7 | C++ | Bartek-cloud/cwiczenia | /średnie_medium/AL_06_08 - Egzamin.cpp | UTF-8 | 1,190 | 2.640625 | 3 | [] | no_license | // https://pl.spoj.com/problems/AL_06_08/
#include <bits/stdc++.h>
using namespace std;
const int max_s = 100000;
int n;
int times[max_s], memo[max_s];
/*
1 2 3 4 5 6
6 + solve(5) // 1 2 3 4 5
5 6 + solve(4) // 1 2 3 4
4 5 6 + solve(3) // 1 2 3
*/
//group time + solve(reszty)
int solve(int s)
{
if (s == -1){
return 0;
}
if(memo[s]!=-1){
return memo[s];
}
int group_time=0;
memo[s] = INT_MAX; // numeric_limits<int>::max();
for(int i = s; i >= max(s - n + 1, 0); i--) {
group_time = max(group_time, times[i]);
memo[s] = min(group_time + solve(i-1), memo[s]);
//cerr<<memo[s]<<endl;
}
return memo[s];
}
int main()
{
int t;
scanf("%d", &t);
while (t--) {
int s, start_h, start_m;
scanf("%d %d %02d:%02d", &s, &n, &start_h, &start_m);
times[s];
//times.resize(s);
for (int i = 0; i < s; ++i) {
scanf("%d", times + i);
memo[i] = -1;
}
int exam_time = solve(s-1);
int end_time = (start_h * 60 + start_m + exam_time) % (24 * 60);
printf("%02d:%02d\n", end_time / 60, end_time % 60);
}
return 0;
}
| true |
638fed1a67fea83b5aaca3caa58e4a41db682740 | C++ | ttykkala/recon | /utils/include/GLSLProgram.h | ISO-8859-1 | 1,980 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | /*
Copyright 2016 Tommi M. Tykkl
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.
*/
// Simple class to contain GLSL shaders/programs
#pragma once
#include <GL/glew.h>
#include <stdio.h>
class GLSLProgram
{
public:
// construct program from strings
GLSLProgram(const char *vsource, const char *fsource);
GLSLProgram(const char *vsource, const char *gsource, const char *fsource,
GLenum gsInput = GL_POINTS, GLenum gsOutput = GL_TRIANGLE_STRIP, int nVertices=4);
~GLSLProgram();
void enable();
void disable();
void setUniform1f(const GLchar *name, GLfloat x);
void setUniform2f(const GLchar *name, GLfloat x, GLfloat y);
void setUniform3f(const char *name, float x, float y, float z);
void setUniform4f(const char *name, float x, float y, float z, float w);
void setUniformfv(const GLchar *name, GLfloat *v, int elementSize, int count=1);
void setUniformMatrix4fv(const GLchar *name, GLfloat *m, bool transpose);
void bindTexture(const char *name, GLuint tex, GLenum target, GLint unit);
inline GLuint getProgId()
{
return mProg;
}
private:
GLuint checkCompileStatus(GLuint shader, GLint *status);
GLuint compileProgram(const char *vsource, const char *gsource, const char *fsource,
GLenum gsInput = GL_POINTS, GLenum gsOutput = GL_TRIANGLE_STRIP, int nVertices=4);
GLuint mProg;
};
| true |
b42f529b01de3bf6ab3f992e87f4930916a733d8 | C++ | jmitch98/SolarSystem | /include/SolarSystem.h | UTF-8 | 1,239 | 2.640625 | 3 | [] | no_license | #ifndef SOLARSYSTEM_H
#define SOLARSYSTEM_H
#include "OrbitalBody.h"
#include "Renderer.h"
#define AU 3.0f
#define KM_TO_AU(km) (km * 2) / 16819000.0f
namespace solarsystem {
extern OrbitalBody* sun;
extern OrbitalBody* earth;
extern OrbitalBody* mercury;
extern OrbitalBody* venus;
extern OrbitalBody* mars;
extern OrbitalBody* jupiter;
extern OrbitalBody* saturn;
extern OrbitalBody* uranus;
extern OrbitalBody* neptune;
extern OrbitalBody* pluto;
extern OrbitalBody* compMercury;
extern OrbitalBody* compVenus;
extern OrbitalBody* compEarth;
extern OrbitalBody* compMars;
extern OrbitalBody* compJupiter;
extern OrbitalBody* compSaturn;
extern OrbitalBody* compUranus;
extern OrbitalBody* compNeptune;
extern OrbitalBody* compMoon;
extern OrbitalBody* compSun;
extern OrbitalBody* compPluto;
extern OrbitalBody* OB1;
extern OrbitalBody* OB2;
extern float simulationSpeed;
extern float simulationSpeedMultiplier;
/**
* Inits the solar system objects.
*/
void Init();
/**
* Calls draw on all the solar system bodies by traversing
* the "scene graph" starting with the sun.
*/
void Draw(renderer::Shader shader);
/**
* Frees all the memory the solar system allocated.
*/
void Destroy();
} // namespace solarsystem
#endif
| true |
c304b90e83b0d38bf7c8c64d52ed305afc2aee4c | C++ | xrlrf/DataStructure | /栈和队列/ShareStack/src/ShareStack.cpp | UTF-8 | 1,535 | 3.671875 | 4 | [] | no_license | #include "ShareStack.h"
void InitStack(SqDoubleStack &S) // 初始化一个空栈S
{
S.top1 = -1;
S.top2 = MaxSize;
}
bool StackEmpty(SqDoubleStack S,int stackNum) // 判断一个栈是否为空
{
if(stackNum == 1 && S.top1 == -1)
return true;
else if(stackNum == 2 && S.top2 == MaxSize)
return true;
else
return false;
}
bool Push(SqDoubleStack &S,ElemType x,int stackNum) // 进栈,比之前多了一个stackNum,表示入的是哪一个栈
{
if(S.top1 + 1 == S.top2) // 栈满
return false;
if(stackNum == 1) S.data[++S.top1] = x;
else if(stackNum == 2) S.data[--S.top2] = x;
return true;
}
bool Pop(SqDoubleStack &S,ElemType &x , int stackNum) // 出栈
{
if(StackEmpty(S,stackNum)) return false;
if(stackNum == 1)
x = S.data[S.top1--];
else if(stackNum == 2)
x = S.data[S.top2++];
return true;
}
bool GetTop(SqDoubleStack S,ElemType &x,int stackNum) // 读栈顶元素
{
if(StackEmpty(S,stackNum)) return false;
if(stackNum == 1)
x = S.data[S.top1];
else if(stackNum == 2)
x = S.data[S.top2];
return true;
}
void ClearStack(SqDoubleStack &S,int stackNum) // 销毁栈
{
int i;
if(stackNum == 1)
{
if(!StackEmpty(S,stackNum))
for(i = 0 ; i <= S.top1 ; i++)
S.data[i] = 0;
}else if(stackNum == 2){
if(!StackEmpty(S,stackNum))
for(i = S.top2 ; i < MaxSize ; i++)
S.data[i] = 0;
}
} | true |
7e78594dedbe625d93356d3d706781c2ef52a946 | C++ | algo-gzua/AlgorithmGzua | /SW-Expert-Academy/d4/sw_1226/km/sw_1226.cpp | UHC | 1,358 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <stack>
using namespace std;
struct Node
{
int y;
int x;
};
int main(void)
{
int board[16][16];
bool visit[16][16] = { false, };
int direction[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
for (int t = 1; t <= 10; ++t)
{
int c;
int start_x = 0, start_y = 0;
int end_x = 0, end_y = 0;
int result = 0;
fill(&visit[0][0], &visit[15][15], false);
cin >> c;
for (int i = 0; i < 16; ++i)
{
string s;
cin >> s;
for (int j = 0; j < 16; ++j)
{
board[i][j] = s[j] - '0';
if (board[i][j] == 2)
{
start_x = j;
start_y = i;
}
else if (board[i][j] == 3)
{
end_x = j;
end_y = i;
}
}
}
// dfs
stack<Node> st;
visit[start_y][start_x] = true;
st.push({ start_y, start_x });
while (!st.empty())
{
Node n = st.top();
st.pop();
if (n.x == end_x && n.y == end_y)
{
result = 1;
break;
}
for (int i = 0; i < 4; ++i)
{
int x = n.x + direction[i][0];
int y = n.y + direction[i][1];
// ȳٸ
if (x >= 0 && x < 16 && y >= 0 && y < 16)
{
if (board[y][x] != 1 && !visit[y][x])
{
visit[y][x] = true;
st.push({ y, x });
}
}
}
}
cout << "#" << c << " " << result << "\n";
}
return 0;
} | true |
b71f54c9a1738fb987fe1823bbb16d26d2469c43 | C++ | skizophonic/Generic-C-API | /menus/AccountMenu.h | UTF-8 | 1,270 | 2.984375 | 3 | [] | no_license | #pragma once
#include "BaseMenu.h"
#include "./models/Account.h"
#include "AccountManagement.h"
class AccountMenu : public BaseMenu {
private:
public:
AccountMenu(BaseMenu* baseMenu) : BaseMenu(baseMenu) {}
~AccountMenu() {}
void load() override {
int choice{ 0 };
std::cin >> choice;
switch (choice) {
case 1: {
insertAccount();
reload();
}break;
case 2: {
listAccount();
reload();
}break;
case 3: {
listAllAccounts();
reload();
}break;
case 4: {
deactivateAccount();
reload();
}break;
case 5: {
exportFile();
reload();
}break;
case 0: {
reloadParent();
}break;
}
}
void printOptions() override {
std::cout << "...:: WELCOME TO ACCOUNT MANAGER ::..." << std::endl;
std::cout << std::endl;
std::cout << "...:: ACCOUNTS ::..." << std::endl;
std::cout << std::endl;
std::cout << "Please choose one of the following options: " << std::endl;
std::cout << std::endl;
std::cout << "1. Create a new account" << std::endl;
std::cout << "2. Consult an account" << std::endl;
std::cout << "3. List all accounts" << std::endl;
std::cout << "4. Deactivate an account" << std::endl;
std::cout << "5. Export to file" << std::endl;
std::cout << "0. Exit" << std::endl;
}
}; | true |
34ea378e0674e66e97c536edf422c1891e391c6e | C++ | chillylips76/cis201-examples | /loops/do_while/main.cpp | UTF-8 | 868 | 3.625 | 4 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
char response;
do
{
cout << "Email (type 1)" << endl;
cout << "Web Browser (type 2)" << endl;
cout << "World Domination (type 3)" << endl;
cout << "Quit (type q)" << endl;
cout << ">>>";
cin >> response;
if(response == '1')
{
cout << "Start up email system" << endl;
}
else if (response == '2')
{
cout << "Start up web browser system" << endl;
}
else if (response == '3')
{
cout << "Start up World Domination -- release the drones" << endl;
}
else if (response == 'q' || response == 'Q' )
{
cout << "Quitting" << endl;
}
else
{
cout << "Invalid choice" << endl;
}
}while(response != 'q' && response != 'Q');
return 0;
e
| true |
238e967bb7d7c726e3ee142e39b443d363a3e975 | C++ | ThomasDHZ/RPGGame | /Engine/Vec2.cpp | UTF-8 | 655 | 3.5 | 4 | [] | no_license | #include "Vec2.h"
Vec2::Vec2()
{
x = 0;
y = 0;
}
Vec2::Vec2(int X, int Y)
{
x = X;
y = Y;
}
Vec2::~Vec2()
{
}
void Vec2::SetY(int Y)
{
y = Y;
}
void Vec2::SetX(int X)
{
x = X;
}
Vec2 Vec2::operator+(const Vec2& rhs)
{
Vec2 vec = Vec2(x + rhs.x, y + rhs.y);
return vec;
}
Vec2 Vec2::operator-(const Vec2& rhs)
{
Vec2 vec = Vec2(x - rhs.x, y - rhs.y);
return vec;
}
Vec2& Vec2::operator+=(const Vec2& rhs)
{
return *this = *this + rhs;
}
Vec2& Vec2::operator-=(const Vec2& rhs)
{
return *this = *this - rhs;
}
bool Vec2::operator==(const Vec2& rhs)
{
if (x == rhs.x &&
y == rhs.y)
{
return true;
}
else
{
return false;
}
}
| true |