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
7943f3af19f06dc39a8845f3c92d042bfd1afba8
C++
SundeepK/Splitter
/src/TextureMapper.cpp
UTF-8
4,464
2.796875
3
[]
no_license
#include <TextureMapper.h> TextureMapper::TextureMapper(float scale) : m_scale(scale) { } TextureMapper::~TextureMapper() { } float TextureMapper::fl(float num) { return floor( num * 1000.00 + 0.5 ) / 1000.00; } b2Vec2 TextureMapper::fl(b2Vec2 num) { return b2Vec2(fl( num.x), fl( num.y)); } float TextureMapper::isCollinear(const b2Vec2& p1, const b2Vec2& p2, const b2Vec2& p3) { return round(p1.x*p2.y+p2.x*p3.y+p3.x*p1.y-p1.y*p2.x-p2.y*p3.x-p3.y*p1.x) == 0; } float TextureMapper::getLength(b2Vec2 edge1, b2Vec2 edge2) { return sqrt(pow(edge2.x - edge1.x, 2) + pow(edge2.y - edge1.y, 2)); } void TextureMapper::cacheTextureCoords(const b2Body* parentBody, std::vector<b2Vec2> texCoords) { b2PolygonShape* parentShape =((b2PolygonShape*)parentBody->GetFixtureList()->GetShape()); m_posToTexCoords.clear(); int parentVertexCount = parentShape->GetVertexCount(); for(int i=0; i< parentVertexCount; i++) { b2Vec2 vertex = parentBody->GetWorldPoint((parentShape)->GetVertex(i)); std::pair<b2Vec2,b2Vec2> posToTexPair (fl(m_scale*vertex), texCoords[i]); m_posToTexCoords.insert(posToTexPair); } } b2Vec2 TextureMapper::calculateNewTextCoord(float amountThrough, b2Vec2 texCoordsOfEdge1, b2Vec2 texCoordsOfEdge2) { //interpolated texcoords = (1 - amountThrough) * edge1_textcoords + amountThrough * edge2_texcoords b2Vec2 newTex1 ( texCoordsOfEdge1.x * (1.0f -amountThrough), texCoordsOfEdge1.y * (1.0f -amountThrough)); b2Vec2 newTex2 ( texCoordsOfEdge2.x * amountThrough, texCoordsOfEdge2.y * amountThrough); b2Vec2 newTex = newTex1 + newTex2; return newTex; } float TextureMapper::getPercetangeThrough(b2Vec2 edge1, b2Vec2 edge2 ,b2Vec2 vertexToTexture) { float length = getLength(edge1, edge2); float newVertLength = getLength(vertexToTexture, edge2); return ( 1.0f - (newVertLength / length)); } b2Vec2 TextureMapper::getTexCoordFromParentBody(b2Vec2 vertex, const b2Body* parentBody, std::vector<b2Vec2> parentTexCoords) { b2PolygonShape* parentShape =((b2PolygonShape*)parentBody->GetFixtureList()->GetShape()); int parentVertexCount = parentShape->GetVertexCount(); for(int i=0; i< parentVertexCount; i++) { int i2 = i + 1 < parentVertexCount ? i + 1 : 0; b2Vec2 edge1 = m_scale*parentBody->GetWorldPoint((parentShape)->GetVertex(i)); b2Vec2 edge2 = m_scale*parentBody->GetWorldPoint((parentShape)->GetVertex(i2)); if(isCollinear( edge1, vertex, edge2)) { float amountThrough = getPercetangeThrough(edge1, edge2, vertex); b2Vec2 tex1 = parentTexCoords[i]; b2Vec2 tex2 = parentTexCoords[i2]; return calculateNewTextCoord(amountThrough,tex1, tex2); } } return b2Vec2(0,0); //if we get here then the vertex to texture map is not even part of the parent so incorrect to begin with //TODO handle this edge case in mapSplitBody() function } b2Vec2 TextureMapper::getTexCoordForChildVertex(b2Vec2 vertex, const b2Body* parentBody, std::vector<b2Vec2> parentTexCoords) { if(m_posToTexCoords.find(fl(vertex)) != m_posToTexCoords.end()) { return m_posToTexCoords[fl(vertex)]; } else { return getTexCoordFromParentBody(vertex, parentBody, parentTexCoords); } } std::vector<b2Vec2> TextureMapper::getChildTexCoords(const b2Body* childBody, const b2Body* parentBody, std::vector<b2Vec2> parentTexCoords) { b2PolygonShape* childShape =((b2PolygonShape*)childBody->GetFixtureList()->GetShape()); int childVertexCount = childShape->GetVertexCount(); std::vector<b2Vec2> childTexcoords; for(int i=0; i< childVertexCount; i++) { b2Vec2 childVertex =m_scale*(childShape)->GetVertex(i); childTexcoords.push_back(getTexCoordForChildVertex(childVertex, parentBody, parentTexCoords)); } return childTexcoords; } //does nothing if the number of verticies do not match the number of texcoords std::vector<b2Vec2> TextureMapper::mapSplitBody(const b2Body* childBody, const b2Body* parentBody, std::vector<b2Vec2> texCoords) { b2PolygonShape* parentShape =((b2PolygonShape*)parentBody->GetFixtureList()->GetShape()); std::vector<b2Vec2> childTexcoords; if(parentShape->GetVertexCount() == texCoords.size()) { cacheTextureCoords(parentBody, texCoords); childTexcoords = getChildTexCoords(childBody, parentBody, texCoords); } return childTexcoords; }
true
f25a73e081f9bb31e5a1c7e9e57288cf92d1c098
C++
atharvkaranjkar/Advance-Data-Structures
/8_BloomFilter.cpp
UTF-8
5,240
3.484375
3
[]
no_license
#include <iostream> using namespace std; class BloomFilter { public: bool arr[100]; int filter_size; int filter; BloomFilter(int n) { filter_size = n; for (int i = 0; i < filter_size; i++) { arr[i] = false; } filter = 0; } int hash1(string s) { int hash_val = 0; for (unsigned int i = 0; i < s.length(); i++) { hash_val = hash_val + (int)s[i]; } hash_val = hash_val % filter_size; return hash_val; } int hash2(string s) { int hash_val = 0; for (unsigned int i = 0; i < s.length(); i++) { hash_val = hash_val + ((int)s[i] * 3); } hash_val = hash_val % filter_size; return hash_val; } int hash3(string s) { int hash_val = 0; for (unsigned int i = 0; i < s.length(); i++) { hash_val = hash_val + ((int)s[i] * 5); } hash_val = hash_val % filter_size; return hash_val; } int hash4(string s) { int hash_val = 0; for (unsigned int i = 0; i < s.length(); i++) { hash_val = hash_val + ((int)s[i] * 7); } hash_val = hash_val % filter_size; return hash_val; } void search_data(string s) { int hv1 = hash1(s); int hv2 = hash2(s); int hv3 = hash3(s); int hv4 = hash4(s); cout << "\n Using array \n"; cout << "\n Hash1 : " << hv1 << " Hash2 : " << hv2 << " Hash3 : " << hv3 << " Hash4 : " << hv4; cout << endl << endl; for (int i = 0; i < filter_size; i++) { cout << i << "\t"; } cout << endl; for (int i = 0; i < 10; i++) { cout << arr[i] << "\t"; } for (int i = 10; i < filter_size; i++) { cout << arr[i] << "\t"; } if (arr[hv1] == true && arr[hv2] == true && arr[hv3] == true && arr[hv4] == true) { cout << "\n\nThe data " << s << " may be present"; } else { cout << "\n\n\nThe data " << s << " is not present. It is inserted in the filter "; arr[hv1] = true; arr[hv2] = true; arr[hv3] = true; arr[hv4] = true; cout << endl; for (int i = 0; i < filter_size; i++) { cout << i << "\t"; } cout << endl; for (int i = 0; i < 10; i++) { cout << arr[i] << "\t"; } for (int i = 10; i < filter_size; i++) { cout << arr[i] << "\t"; } } } void search_data1(string s) { int hv1 = hash1(s); int hv2 = hash2(s); int hv3 = hash3(s); int hv4 = hash4(s); cout << "\n\n\n Using variable \n"; int shift_val1 = 1 << (hv1 - 1); int shift_val2 = 1 << (hv2 - 1); int shift_val3 = 1 << (hv3 - 1); int shift_val4 = 1 << (hv4 - 1); cout << "\n Hash1 : " << hv1 << " Hash2 : " << hv2 << " Hash3 :" << hv3 << " Hash4 : " << hv4; cout << endl << endl << "Hash Keys:" << endl; for (int i = filter_size; i > 9; i--) { cout << i << "\t"; } for (int i = 9; i > 0; i--) { cout << i << "\t"; } cout << endl; int temp_val = filter; int ctr = 32; cout << "Hash Values:" << endl; while (ctr > 0) { int t = temp_val; t = t >> (ctr - 1); t = t & 1; cout << t << "\t"; ctr--; } if (((filter & shift_val1) > 0) && ((filter & shift_val2) > 0) && ((filter & shift_val3) > 0) && ((filter & shift_val4) > 0)) { cout << "\n\nThe data " << s << " may be present"; } else { cout << "\n\nThe data " << s << " is not present. It is inserted in the filter "; filter = filter | shift_val1; filter = filter | shift_val2; filter = filter | shift_val3; filter = filter | shift_val4; cout << endl << endl << "Hash Keys:" << endl; for (int i = filter_size; i > 9; i--) { cout << i << "\t"; } for (int i = 9; i > 0; i--) { cout << i << "\t"; } cout << endl << "Hash Values:" << endl; ctr = 32; while (ctr > 0) { int t = filter; t = t >> (ctr - 1); t = t & 1; cout << t << "\t"; ctr--; } } } }; int main() { BloomFilter b(32); string s; int ch; while (1) { cout << "\n Enter the data : "; cin >> s; b.search_data1(s); cout << "\n\n\n Do you want to enter other data :"; cin >> ch; if (ch == 0) break; } return 0; }
true
222d57220aa299dab4e47d29f1e3b77ca9e86c94
C++
VladGuryev/dictionary
/main.cpp
UTF-8
1,297
2.71875
3
[]
no_license
#include <string> #include <experimental/string_view> #include <iostream> #include "translator.h" #include "test_runner.h" #include "profile.h" using namespace std::experimental; using namespace std; void TestSimple () { Translator translator; translator.Add (string ("okno"), string ("window")); translator.Add (string ("stol"), string ("table")); ASSERT_EQUAL(translator.TranslateForward("okno"), "window"); ASSERT_EQUAL(translator.TranslateForward("stol"), "table"); ASSERT_EQUAL(translator.TranslateForward("table"), ""); ASSERT_EQUAL(translator.TranslateForward("window"), ""); ASSERT_EQUAL(translator.TranslateBackward("table"), "stol"); ASSERT_EQUAL(translator.TranslateBackward("window"), "okno"); ASSERT_EQUAL(translator.TranslateBackward("stol"), ""); ASSERT_EQUAL(translator.TranslateBackward("okno"), ""); translator.Add (string ("stol"), string ("table2")); translator.Add (string ("stol"), string ("table3")); ASSERT_EQUAL(translator.TranslateForward("stol"), "table3"); ASSERT_EQUAL(translator.TranslateBackward("table3"), "stol"); } string_view fun(){ string* str = new string("abcd"); string_view sv(*str); delete str; return sv; } int main () { TestRunner tr; RUN_TEST (tr, TestSimple); //cout << fun() << endl; return 0; }
true
4d80d0c690719114990797edff2cf6d872bfc2ce
C++
ilim0t/numerical-analysis
/test/calculation_test.cpp
UTF-8
2,982
3
3
[]
no_license
#include <gtest/gtest.h> #include <complex> #include <iostream> #include <data.hpp> #include <calculation.hpp> TEST(Data_Mat_Calculation, Dot) { EXPECT_EQ(dot(Mat<double, 2, 2>{{1, 2}, {3, 4}}, Mat<double, 2, 2>{{5, 6}, {7, 8}}), (Mat<double, 2, 2>{{19, 22}, {43, 50}})); EXPECT_EQ(dot(Mat<double, 1, 2>{{0.1, 0.4}}, Mat<double, 2, 1>{{0.3}, {0.6}}), 0.27); } TEST(Data_Mat_Calculation, Minus) { EXPECT_EQ((-Mat<double, 2, 2>{{1, 2}, {3, 4}}), (Mat<double, 2, 2>{{-1, -2}, {-3, -4}})); EXPECT_EQ((-Mat<double, 1, 1>{{0}}), 0.); } TEST(Data_Mat_Calculation, Addition) { EXPECT_EQ((Mat<double, 2, 2>{{1, 2}, {3, 4}} + Mat<double, 2, 2>{{1, 1}, {2, 2}}), (Mat<double, 2, 2>{{2, 3}, {5, 6}})); EXPECT_EQ((Mat<double, 1, 1>{{1}} + Mat<double, 1, 1>{{-1}}), 0.); } TEST(Data_Mat_Calculation, Subtraction) { EXPECT_EQ((Mat<double, 2, 2>{{1, 2}, {3, 4}} - Mat<double, 2, 2>{{1, 1}, {2, 2}}), (Mat<double, 2, 2>{{0, 1}, {1, 2}})); EXPECT_EQ((Mat<double, 1, 1>{{1}} - Mat<double, 1, 1>{{-1}}), 2.); } TEST(Data_Mat_Calculation, Conj) { EXPECT_EQ((Mat<double, 2, 2>{{1, 2}, {3, 4}}.conj()), (Mat<std::complex<double>, 2, 2>{{1, 2}, {3, 4}})); EXPECT_EQ((Mat<std::complex<double>, 2, 2>{{std::complex<double>(1, 2), std::complex<double>(3, 4)}, {std::complex<double>(5, 6), std::complex<double>(7, 8)}}.conj()), (Mat<std::complex<double>, 2, 2>{{std::complex<double>(1, -2), std::complex<double>(3, -4)}, {std::complex<double>(5, -6), std::complex<double>(7, -8)}})); } TEST(Data_Mat_Calculation, Adjoint) { EXPECT_EQ((Mat<double, 2, 2>{{1, 2}, {3, 4}}.adjoint()), (Mat<std::complex<double>, 2, 2>{{1, 3}, {2, 4}})); EXPECT_EQ((Mat<std::complex<double>, 2, 2>{{std::complex<double>(1, 2), std::complex<double>(3, 4)}, {std::complex<double>(5, 6), std::complex<double>(7, 8)}}.adjoint()), (Mat<std::complex<double>, 2, 2>{{std::complex<double>(1, -2), std::complex<double>(5, -6)}, {std::complex<double>(3, -4), std::complex<double>(7, -8)}})); }
true
a9dc3c3e5b38bf518e31a5a7028d87aaffd7890e
C++
3for/verifiable-shuffle
/src/G_q.h
UTF-8
1,586
3.296875
3
[ "Apache-2.0" ]
permissive
/* * G_q.h * * Created on: 30.09.2010 * Author: stephaniebayer * * Class describing the group G_q subset of Z_p with prime order q. * */ #ifndef G_q_H_ #define G_q_H_ #include "Cyclic_group.h" #include "Mod_p.h" #include <NTL/ZZ.h> NTL_CLIENT class G_q: public Cyclic_group { private: Mod_p generator; //generator of the group ZZ order; //order of the group ZZ mod; //value of p such that G_q subset of Z_p public: //Constructors and destructor G_q(); G_q(Mod_p gen, long o, long mod); G_q(Mod_p gen,long o, ZZ mod); G_q(Mod_p gen, ZZ o, ZZ mod); G_q(ZZ gen_val, long o, long mod); G_q(ZZ gen_val, long o , ZZ mod); G_q(ZZ gen_val, ZZ o , ZZ mod); G_q(long gen_val, long o, long mod); G_q(long gen_val, long o, ZZ mod); G_q(long gen_val, ZZ o, ZZ mod); G_q(Mod_p gen, long o); G_q(Mod_p gen, ZZ o); G_q(long o,ZZ mod); G_q(ZZ o,ZZ mod); G_q(long o, long mod); virtual ~G_q(); //Access to the variables Mod_p get_gen() const; ZZ get_ord() const; ZZ get_mod()const; //operators void operator =(const G_q& H); friend ostream& operator<<(ostream& os, const G_q& G); //Test if an element is a generator of the group bool is_generator(const Mod_p& el); bool is_generator(const ZZ& x); bool is_generator(const long& x); //returns the identity Mod_p identity(); //returns random an element Mod_p random_el(); Mod_p random_el(int c); //creates an element with value val Mod_p element(ZZ val); Mod_p element(long val); //returns the inverse of an value Mod_p inverse(ZZ x); Mod_p inverse(long x); }; #endif /* G_q_H_ */
true
b39bccb23b12aded338878aa5849fcb64efaac12
C++
NeacsuRadu/Visibility-algorithms
/src/demo/simple_polygon_visibility.cpp
UTF-8
10,222
2.796875
3
[]
no_license
#include "simple_polygon_visibility.h" #include "polygon_helpers.h" simple_polygon_visibility * singleton<simple_polygon_visibility>::instance = nullptr; extern std::string run_type; void simple_polygon_visibility::preprocess_polygons(const std::vector<std::vector<point>>& polygons) { m_polygon = polygons[0]; if (!is_counter_clockwise(m_polygon)) revert_order(m_polygon); } std::vector<triangle*> simple_polygon_visibility::get_visibility(const point& view) { m_display_data_steps.clear(); if (!point_in_polygon(m_polygon, view)) return {}; _shift_polygon_points(view); auto st = _get_visibility_stack(view); std::vector<triangle*> result; point crr = st.top().pt; point last = crr; st.pop(); while (!st.empty()) { result.push_back(get_triangle(view, st.top().pt, crr)); crr = st.top().pt; st.pop(); } result.push_back(get_triangle(view, last, crr)); return result; } void simple_polygon_visibility::_shift_polygon_points(const point& view) { double min = 1000000.0; std::size_t idx_min = 0; point paux { 1000.0, view.y }; m_polygon.push_back(m_polygon[0]); for (std::size_t idx = 0; idx < m_polygon.size() - 1; ++idx) { point intersect = get_segments_intersection(m_polygon[idx], m_polygon[idx + 1], view, paux); if (intersect == error_point) continue; double dist = distance(view, intersect); if (dist < min) { min = dist; idx_min = idx + 1; } } m_polygon.pop_back(); if (idx_min == m_polygon.size()) return; std::vector<point> aux; for (std::size_t idx = idx_min; idx < m_polygon.size(); ++idx) aux.push_back(m_polygon[idx]); for (std::size_t idx = 0; idx < idx_min; ++idx) aux.push_back(m_polygon[idx]); m_polygon.swap(aux); } std::stack<simple_polygon_visibility::stack_data> simple_polygon_visibility::_get_visibility_stack(const point& view) { int idx = 0; int sz = m_polygon.size(); std::stack<stack_data> st; auto v0 = get_lines_intersection(view, {1000.0, view.y}, m_polygon[sz - 1], m_polygon[0]); if (v0 == m_polygon[0]) { st.push({v0, true, index(0, sz)}); idx = 1; } else { st.push({v0, false, index(-1, sz)}); } _save_stack({v0}, view, st); while (idx < sz) { //std::cout << m_polygon[index(idx, sz)].x << " " << m_polygon[index(idx, sz)].y << std::endl; if (test_orientation(view, m_polygon[index(idx - 1, sz)], m_polygon[index(idx, sz)]) != orientation::right) { //std::cout << "vertex is to the left of the previous one, push" << std::endl; st.push({m_polygon[index(idx, sz)], true, idx}); idx ++; _save_stack({st.top().pt}, view, st); continue; } //std::cout << "vertex is to the right of the previous one" << std::endl; if (test_orientation(m_polygon[index(idx - 2, sz)], m_polygon[index(idx - 1, sz)], m_polygon[index(idx, sz)]) == orientation::right) { //std::cout << "vertex is to the right of the -2 -1 line" << std::endl; point curr = m_polygon[index(idx - 1, sz)]; _save_stack({m_polygon[index(idx, sz)]}, view, st); idx ++; while (idx <= sz) { auto intersect = get_lines_intersection(view, curr, m_polygon[index(idx - 1, sz)], m_polygon[index(idx, sz)]); if (intersect != error_point && point_between_segment_vertices(intersect, m_polygon[index(idx - 1, sz)], m_polygon[index(idx, sz)])) { _save_stack({m_polygon[index(idx, sz)]}, view, st); _save_stack({intersect, m_polygon[index(idx - 1, sz)], m_polygon[index(idx, sz)]}, view, st); st.push({intersect, false, idx - 1}); st.push({m_polygon[index(idx, sz)], true, idx}); _save_stack({intersect, m_polygon[index(idx - 1, sz)], m_polygon[index(idx, sz)]}, view, st); break; } idx ++; _save_stack({m_polygon[index(idx - 1, sz)]}, view, st); } idx ++; } else { //std::cout << "vertex is to the left of -2 -1 line" << std::endl; point f1 = m_polygon[index(idx - 1, sz)]; // forward edge point f2 = m_polygon[index(idx, sz)]; while (!st.empty()) { auto data = st.top(); _save_stack({f1, f2, data.pt}, view, st); auto intersection = get_segments_intersection(f1, f2, view, data.pt); if (intersection == error_point) { auto ori = test_orientation(view, m_polygon[index(idx, sz)], m_polygon[index(idx + 1, sz)]); if (ori == orientation::right) { //std::cout << "idx + 1 is to the right of q idx " << std::endl; f1 = f2; f2 = m_polygon[index(idx + 1, sz)]; idx ++; continue; } else { if (test_orientation(f1, f2, m_polygon[index(idx + 1, sz)]) == orientation::right) { //std::cout << "idx + 1 is to the right of idx - 1 idx " << std::endl; auto m = get_lines_intersection(view, f2, data.pt, m_polygon[index(data.index + 1, sz)]); if (m == error_point) throw std::runtime_error("lines do not intersect, error"); st.push({m, false, data.index}); st.push({f2, true, idx}); _save_stack({m, f1, f2, data.pt}, view, st); idx ++; break; } else { //std::cout << "idx + 1 is to the left of idx - 1 idx " << std::endl; idx ++; while (idx < sz) { //std::cout << "while" << std::endl; _save_stack({f1, f2, m_polygon[index(idx, sz)], m_polygon[index(idx + 1, sz)]}, view, st); intersection = get_lines_intersection(view, f2, m_polygon[index(idx, sz)], m_polygon[index(idx + 1, sz)]); if (intersection != error_point && point_between_segment_vertices(intersection, m_polygon[index(idx, sz)], m_polygon[index(idx + 1, sz)])) { f2 = m_polygon[index(idx + 1, sz)]; f1 = m_polygon[index(idx, sz)]; idx ++; break; } idx ++; } } } } else { if (data.is_vertex) { //std::cout << "stack popped" << std::endl; st.pop(); } else { st.pop(); if (point_between_segment_vertices(intersection, data.pt, st.top().pt)) { _save_stack({f1, f2, data.pt, st.top().pt, intersection}, view, st); idx ++; while (idx < sz) { _save_stack({st.top().pt, m_polygon[index(idx - 1, sz)], m_polygon[index(idx, sz)]}, view, st); point z = get_lines_intersection(intersection, st.top().pt, m_polygon[index(idx, sz)], m_polygon[index(idx - 1, sz)]); if (z != error_point && point_between_segment_vertices(z, m_polygon[index(idx, sz)], m_polygon[index(idx - 1, sz)])) { _save_stack({st.top().pt, m_polygon[index(idx - 1, sz)], m_polygon[index(idx, sz)], z}, view, st); st.push({z, false, idx - 1}); st.push({m_polygon[index(idx, sz)], true, idx}); idx++; _save_stack({m_polygon[index(idx - 1, sz)], z}, view, st); break; } idx ++; } break; } else if (point_between_segment_vertices(st.top().pt, intersection, data.pt)) { _save_stack({f1, f2, data.pt, st.top().pt, intersection}, view, st); } } } } } } _save_stack({}, view, st, true); return st; } void simple_polygon_visibility::_save_stack(const std::vector<point>& points, const point& view, std::stack<stack_data> st, bool last_step) { if (run_type != "step") return; std::vector<triangle *> aux; if (st.size() >= 2) { auto first = st.top().pt; auto last = st.top().pt; st.pop(); while (!st.empty()) { aux.push_back(get_triangle(view, st.top().pt, last)); last = st.top().pt; st.pop(); } if (last_step) aux.push_back(get_triangle(view, first, last)); } auto pts = points; pts.push_back(view); m_display_data_steps.push_back({aux, pts}); }
true
8284e74cdb98ba695cb68c8d7155fc12f9401e5f
C++
mateusztasz/HarmonySearchAlgorithm
/Program/include/harmony.hh
UTF-8
1,584
3.03125
3
[]
no_license
#ifndef HARMONY_HH #define HARMONY_HH #include <iostream> #include <string> #include <iomanip> #include <ctime> #include <random> #include <chrono> #include "boundary.hh" using namespace std; /*! * \file * \brief The file contains a definition of Harmony Class. * */ /*! * \brief Models every generated harmonics. */ class Harmony{ private: /*! \brief Represent size of problem (in literature usually names as ,,n''.) */ int _problem_size; /*! \brief A member keeping a value of objective function. */ double _obj_value; /*! \brief A dynamic table with value of all arguments x1,x2,....xn . */ double *VarX; public: /*! \brief Constructor of Harmony. */ Harmony(int &problem_size); /*! \brief Setting value of _obj_value (value of objective functions). */ void SetValue(double val); /*! \brief Returns an _obj_value (value of objective functions). */ double GetValue() const; /*! \brief Returns problem size. */ double GetProblemSize(); /*! \brief Returns an argument of VarX table. * An argument is choosen by numberOfArgument. */ double GetVarX_of(int numberOfArgument); bool SetVarX_of(int numberOfArgument,double value); /*! \brief Initialize VarX with random values in such bounds given as whole table VarLim. */ void InitInBounds(Boundary VarLim[]); void SetVarX_InBounds(int VarIndex, Boundary VarLim[]); /*! \brief to print out whole Harmony. */ void Print(); /*! \brief Desctructor of Harmony. */ ~Harmony(); }; #endif
true
e1d438822e056dfd6039946110297e8112f8bc0d
C++
zwcloud/EmbededListView
/MainListModel.cpp
UTF-8
1,418
2.875
3
[]
no_license
#include "MainListModel.h" #include "MyObject.h" #include "SubListModel.h" void MainListModel::fill(std::vector<MyObject*>& objectList) { beginResetModel(); //clear old sub-models for (SubListModel* model : m_children) { delete model; model = nullptr; } m_children.clear(); //create new sub-models for (int i=0; i<objectList.size(); ++i) { MyObject* obj = objectList[i]; SubListModel* subListModel = new SubListModel(obj); m_children.append(subListModel); } endResetModel(); } int MainListModel::rowCount(const QModelIndex& parent) const { return m_children.size(); } constexpr int ObjNameRole = Qt::UserRole + 1; constexpr int ObjValuesRole = Qt::UserRole + 2; QHash<int, QByteArray> MainListModel::roleNames() const { QHash<int, QByteArray> roles; roles[ObjNameRole] = "obj_name"; roles[ObjValuesRole] = "obj_values"; return roles; } QVariant MainListModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) { return QVariant(); } if (index.row() >= m_children.size()) { return QVariant(); } if (role == ObjNameRole) { return QString::fromStdString(m_children[index.row()]->getObj()->m_name); } if(role == ObjValuesRole) { return QVariant::fromValue(m_children[index.row()]); } return QVariant(); }
true
ec3f00468125dcc0639d20f4a9d776b58d346da2
C++
Arnaudlaurent/EXIIITIA-1
/CODE/LIB/ExtiaCounter/ExtiaCounter.h
UTF-8
1,070
2.65625
3
[]
no_license
#ifndef EXTIA_COUNTER_H_ #define EXTIA_COUNTER_H_ #include "Arduino.h" extern "C" void TIMER1_OVF_vect(void) __attribute__((signal)); #define MAX_COUNTER 3 // 65536 - 16000 => TIMER1 max value (16bits) - 16Mhz master clock, no prescaler #define TIMER_INITVAL 49536 class ExtiaCounter { public: ExtiaCounter(); bool setCounter(unsigned int counter, unsigned int duration, void (*callback)()); bool resetCounter(unsigned int counter); void startCounter(unsigned int counter); void pauseCounter(unsigned int counter); bool isRunning(unsigned int counter); unsigned long millis(); friend void ::TIMER1_OVF_vect(void); private: // millis() value static volatile unsigned long s_millis; // Counters current values static volatile int s_counterCurrentMillis[MAX_COUNTER]; // Period for callback execution static int s_counterDuration[MAX_COUNTER]; // Callback on counter tick static void (*s_counterCallback[MAX_COUNTER])(void); // Boolean used to pause execution static volatile bool s_counterState[MAX_COUNTER]; }; #endif // !EXTIA_COUNTER_H_
true
203212bf0df835bcbd1179f5226ba507642dbc9d
C++
moyang602/bit_mbzirc
/src/bit_task/src/map_address_manage.cpp
UTF-8
2,244
2.53125
3
[]
no_license
#include "ros/ros.h" #include "bit_task/FindMapAddress.h" #include "bit_task/isAddressExist.h" #include "bit_task/WriteAddress.h" // 获取指定地点位置 bool FindMapAddress(bit_task::FindMapAddress::Request &req, bit_task::FindMapAddress::Response &res) { std::string Name = req.AddressToFind; // To do 添加匹配找点的程序 res.AddressPose.header.frame_id = "map"; res.AddressPose.header.stamp = ros::Time().now(); res.AddressPose.pose.position.x = 2.0; res.AddressPose.pose.position.y = 0; res.AddressPose.pose.position.z = 0; res.AddressPose.pose.orientation.x = 0; res.AddressPose.pose.orientation.y = 0; res.AddressPose.pose.orientation.z = 0; res.AddressPose.pose.orientation.w = 1; res.radius = 1.0; ROS_INFO_STREAM("The pose of ["<<Name<<"] has been send back"); } // 指定地点位置是否存在 bool isAddressExist(bit_task::isAddressExist::Request &req, bit_task::isAddressExist::Response &res) { std::string Name = req.AddressToFind; // To do 判断是否存在程序 if (true) { res.flag = true; ROS_INFO_STREAM("The pose of ["<<Name<<"] exist"); } else { res.flag = false; ROS_INFO_STREAM("The pose of ["<<Name<<"] doesn't exist"); } } // 写入指定地点 bool WriteAddress(bit_task::WriteAddress::Request &req, bit_task::WriteAddress::Response &res) { std::string Name = req.AddressToFind; // To do 写入地点程序 if (true) { res.state = 0; ROS_INFO_STREAM("The pose of ["<<Name<<"] has been written"); } else { res.state = 1; ROS_INFO_STREAM("The pose of ["<<Name<<"] exist"); } } int main(int argc, char *argv[]) { ros::init(argc, argv, "address_manage_node"); ros::NodeHandle nh("~"); ros::ServiceServer service_find = nh.advertiseService("FindMapAddress",FindMapAddress); ros::ServiceServer service_is = nh.advertiseService("isAddressExist",isAddressExist); ros::ServiceServer service_write = nh.advertiseService("WriteAddress",WriteAddress); ROS_INFO_STREAM("Map address manage start work"); ros::spin(); return 0; }
true
9a34ad2c43c76e5dc3c8d3434b8bdf0e5205f820
C++
seongwon-kang/Elsword-Source-2014
/KncWX2Server/Common/ServerLogManager.cpp
UHC
3,537
2.59375
3
[ "MIT" ]
permissive
#include "ServerLogManager.h" ////////////////////////////////////////////////////////////////////////// const wchar_t* serverlog::GetLogLevelStr( serverlog::LOG_LEVEL eLogLevel ) { switch( eLogLevel ) { case serverlog::CLOG: return L"clog"; case serverlog::CLOG2: return L"clog2"; case serverlog::CWARN: return L"cwarn"; case serverlog::CERR: return L"cerr"; case serverlog::COUT: return L"cout"; case serverlog::COUT2: return L"cout2"; } return L"unknown"; } ////////////////////////////////////////////////////////////////////////// // log stream KLogStream::KLogStream() { } KLogStream::~KLogStream() { // log KLogInfoPtr spLogInfo = KLogInfoPtr( new KLogInfo( m_kLogInfo ) ); if( spLogInfo == NULL ) { START_LOG( cerr, L"log !" ) << END_LOG; return; } KServerLogManager::GetInstance().QueueingToLog( spLogInfo ); } void KLogStream::EndLog( const wchar_t* pStrFileName, int iStrLine ) { std::wstringstream wstrStream; wstrStream << L" " << L"(" << pStrFileName << L", " << iStrLine << L")" << std::endl; m_kLogInfo.m_vecContent.push_back( wstrStream.str() ); m_kLogInfo.m_iFileLine = iStrLine; } ////////////////////////////////////////////////////////////////////////// // server log manager KServerLogManager KServerLogManager::ms_selfInstance; ImplToStringW( KServerLogManager ) { return stm_; } KServerLogManager::KServerLogManager() : m_bIsShutDown( false ) { } KServerLogManager::~KServerLogManager() { } void KServerLogManager::QueueingToLog( const KLogInfoPtr& spLogInfo ) { KLocker lock( m_csLogDataQueue ); if( m_bIsShutDown ) return; m_LogDataQueue.push( spLogInfo ); } bool KServerLogManager::GetLogInfo( KLogInfoPtr& spLogInfo ) { KLocker lock( m_csLogDataQueue ); if( m_LogDataQueue.empty() ) return false; spLogInfo = m_LogDataQueue.front(); m_LogDataQueue.pop(); return true; } void KServerLogManager::Run() { START_LOG( cout, L"Server Log Manager Run()" ); DWORD ret; while( true ) { ret = ::WaitForSingleObject( m_hKillEvent, 1 ); // 0.05s if( ret == WAIT_OBJECT_0 ) break; if( ret == WAIT_TIMEOUT ) Loop(); else std::cout << "*** WaitForSingleObject() - return : "<< ret << std::endl; } } void KServerLogManager::Loop() { KLogInfoPtr spLogInfo; if( GetLogInfo( spLogInfo ) == false ) return; switch( spLogInfo->m_cLogLevel ) { case serverlog::CLOG: { for( u_int ui = 0; ui < spLogInfo->m_vecContent.size(); ++ui ) { dbg::clog << spLogInfo->m_vecContent[ui]; } } break; case serverlog::CLOG2: { for( u_int ui = 0; ui < spLogInfo->m_vecContent.size(); ++ui ) { dbg::clog2 << spLogInfo->m_vecContent[ui]; } } break; case serverlog::CWARN: { for( u_int ui = 0; ui < spLogInfo->m_vecContent.size(); ++ui ) { dbg::cwarn << spLogInfo->m_vecContent[ui]; } } break; case serverlog::CERR: { for( u_int ui = 0; ui < spLogInfo->m_vecContent.size(); ++ui ) { dbg::cerr << spLogInfo->m_vecContent[ui]; } } break; case serverlog::COUT: { for( u_int ui = 0; ui < spLogInfo->m_vecContent.size(); ++ui ) { dbg::cout << spLogInfo->m_vecContent[ui]; } } break; case serverlog::COUT2: { for( u_int ui = 0; ui < spLogInfo->m_vecContent.size(); ++ui ) { dbg::cout2 << spLogInfo->m_vecContent[ui]; } } break; } } void KServerLogManager::Shutdown() { KLocker lock( m_csLogDataQueue ); // m_bIsShutDown = true; // End(); }
true
e7e2630083288204cecb4badf597645c7261ddeb
C++
melody40/monorepo
/C++ codes/splitString/main.cpp
UTF-8
610
3.03125
3
[]
no_license
#include <iostream> #include <fstream> int main() { char s; std::ifstream inputfile("input.txt"); std::ofstream outputfile; outputfile.open("output.txt", std::ofstream::out); // size_t pos = 0; // std::string token; // while ((pos = s.find(delimiter)) != std::string::npos) { // token = s.substr(0, pos); // std::cout << token << std::endl; // s.erase(0, pos + delimiter.length()); // } // std::cout << s << std::endl; outputfile<< "HEllo"; while (inputfile>> s){ if (s>='A' && s<='Z') outputfile<< s; } return 0; }
true
8c0957eb53f3ce318c6bfcccb1b96a3481bcbefd
C++
sajeda123/Data-Structure
/Linked List/Delete_node.cpp
UTF-8
1,815
3.40625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; struct linked_list { int num; struct linked_list *next; }; typedef struct linked_list node; node *head=NULL,*last=NULL,*previous=NULL; void delete_node(int key) { int flag=0,p=0; node *my_node=head; while(my_node!=NULL) { p++; if(p==key) { if(previous==NULL) { head=my_node->next; } else { previous->next=my_node->next; } flag=1; free(my_node); break; } else{ previous=my_node; my_node=my_node->next; } } if(flag==0){ cout<<"Key not found"<<endl; } } /*void Add_in_first(int val) { node *temp_node=(node*)malloc(sizeof(node)); temp_node->num=val; temp_node->next=head; head=temp_node; } */ void Add_in_last(int val) { node *temp_node; temp_node=(node *)malloc(sizeof(node)); temp_node->num=val; temp_node->next=NULL; if(head==NULL) { head=temp_node; last=temp_node; } else { last->next=temp_node; last=temp_node; } } void print() { node *m_node; m_node=head; while(m_node!=NULL) { cout<<m_node->num<<" "; m_node=m_node->next; } } int main() { int val; while(1) { cin>>val; if(val==-1) { break; } else { //cout<<"all="<<val<<endl; //Add_in_first(val); Add_in_last(val); } } print(); int key; cin>>key; delete_node(key+1); print(); }
true
a8603d53bc10afc1e9039cb840cf1cfd67acf906
C++
KsGin/LeetCode
/LeetCode/ConstructTheRectangle.h
UTF-8
633
3.203125
3
[]
no_license
/* * File : ConstructTheRectangle * Author : KsGin * Date : 03/11/2017 */ #ifndef LEETCODE_CONSTRUCTTHERECTANGLE_H #define LEETCODE_CONSTRUCTTHERECTANGLE_H #include <vector> class Solution { public: std::vector<int> constructRectangle(int area) { int length = area , width = 1; for (int i = area / 2; i > 0 ; --i) { if(area % i == 0 && abs((area / i) - i) < length - width){ length = std::max(area / i , i); width = area / length; } } return std::vector<int> {length , width}; } }; #endif //LEETCODE_CONSTRUCTTHERECTANGLE_H
true
85c28d591b29e072ec4a2bc3d2c4e78f90700c54
C++
Makocb/Commivoyajer-problem-v2
/Matrix.cpp
UTF-8
2,784
3.15625
3
[]
no_license
#include "Matrix.h" #include <ctime> #include <iostream> #include "Globals.h" Matrix::Matrix():Matrix(Globals::defaultGenerationMin, Globals::defaultGenerationMax, Globals::defaultSize) { } Matrix::Matrix(int min, int max, int dim) { std::srand(time(NULL)); std::vector<int> matrixRow; for (int i = 0; i < dim; i++) { horzHeading.push_back(i); vertHeading.push_back(i); for (int j = 0; i < dim; i++) { matrixRow.push_back(rand() % (max - min + 1) + min); } matrix.push_back(matrixRow); matrixRow.clear(); } } int Matrix::minInRow(const int& rowNum) { try { if ((rowNum > matrix.size()) or (rowNum < 0)) { throw(100); } int min = -1; for (auto& number : matrix[rowNum]) { if (number < min) { min = number; } } return min; } catch(int errorCode) { catchBlock_(errorCode); } } int Matrix::minInCol(const int& colNum) { try { if ((colNum > matrix.size()) or (colNum < 0)) { throw(100); } int min = -1; for (int i = 0; i < matrix.size(); i++) { if (matrix[i][colNum] < min) { min = matrix[i][colNum]; } } return min; } catch (int errorCode) { catchBlock_(errorCode); } } void Matrix::rowReduction(const int& rowNum, const int& reductionNumber) { try { if ((rowNum > matrix.size()) or (rowNum < 0)) { throw(100); } for (auto& number : matrix[rowNum]) { number -= reductionNumber; } } catch (int errorCode) { catchBlock_(errorCode); } } void Matrix::colReduction(const int& colNum, const int& reductionNumber) { try { if ((colNum > matrix.size()) or (colNum < 0)) { throw(100); } for (int i = 0; i < matrix.size(); i++) { matrix[i][colNum] -= reductionNumber; } } catch (int errorCode) { catchBlock_(errorCode); } } void Matrix::globalRowReduction() { for (int i = 0; i < matrix.size(); i++) { this->rowReduction(i, this->minInRow(i)); } } void Matrix::globalColReduction() { for (int i = 0; i < matrix.size(); i++) { this->colReduction(i, this->minInCol(i)); } } void Matrix::deleteRow(const int& rowNum) { try { if ((rowNum > matrix.size()) or (rowNum < 0)) { throw(100); } matrix[rowNum].clear(); vertHeading.erase(vertHeading.begin() + rowNum); } catch (int errorCode) { catchBlock_(errorCode); } } void Matrix::deleteCol(const int& colNum) { try { if ((colNum > matrix.size()) or (colNum < 0)) { throw(100); } for (int i = 0; i < matrix.size(); i++) { matrix[i].erase(matrix[i].begin() + colNum); } horzHeading.erase(horzHeading.begin() + colNum); } catch (int errorCode) { catchBlock_(errorCode); } } void Matrix::catchBlock_(int& errorCode) { if (errorCode == 100) { std::cout << "index is out of matrix array range"; } exit(errorCode); }
true
2ac7f2736acaeca787fccdc208f0bcb56ebea05c
C++
dandycheung/dandy-twl
/TWL/include/util/pathutil.cpp
UTF-8
5,019
2.65625
3
[]
no_license
#include <windows.h> #include <shlwapi.h> #pragma comment(lib, "shlwapi.lib") #include "numutil.h" #define IsDigit(c) ((c) >= TEXT('0') && c <= TEXT('9')) // // Takes a location string ("shell32.dll,3") and parses // it into a file-component and an icon index. // Returns the icon index // int WINAPI PathParseIconLocation(IN OUT LPTSTR pszIconFile) { int iIndex = 0; if(pszIconFile) { LPTSTR pszComma, pszEnd; // look for the last comma in the string pszEnd = pszIconFile + lstrlen(pszIconFile); pszComma = StrRChr(pszIconFile, pszEnd, TEXT(',')); if(pszComma && *pszComma) { LPTSTR pszComma2 = pszComma + 1; BOOL fIsDigit = FALSE; // Sometimes we get something like: "C:\path, comma\path\file.ico" // where the ',' is in the path and does not indicates that an icon index follows while(*pszComma2) { if((TEXT(' ') == *pszComma2) || (TEXT('-') == *pszComma2)) ++pszComma2; else { if(IsDigit(*pszComma2)) fIsDigit = TRUE; break; } } if(fIsDigit) { *pszComma++ = 0; // terminate the icon file name. iIndex = (int)CIntergerParser::StringToLong(pszComma); } } PathUnquoteSpaces(pszIconFile); PathRemoveBlanks(pszIconFile); } return iIndex; } // // If a path is contained in quotes then remove them. // void WINAPI PathUnquoteSpaces(LPTSTR lpsz) { if(lpsz) { int cch = lstrlen(lpsz); // Are the first and last chars quotes? if(lpsz[0] == TEXT('"') && lpsz[cch-1] == TEXT('"')) { // Yep, remove them. lpsz[cch - 1] = TEXT('\0'); MoveMemory(lpsz, lpsz + 1, sizeof(TCHAR) * (cch - 1)); } } } // // Strips leading and trailing blanks from a string. // Alters the memory where the string sits. // // in: // lpszString string to strip // // out: // lpszString string sans leading/trailing blanks // // void WINAPI PathRemoveBlanks(LPTSTR lpszString) { if(lpszString) { LPTSTR lpszPosn = lpszString; /* strip leading blanks */ while(*lpszPosn == TEXT(' ')) lpszPosn++; if(lpszPosn != lpszString) lstrcpy(lpszString, lpszPosn); /* strip trailing blanks */ // Find the last non-space // Note that AnsiPrev is cheap is non-DBCS, but very expensive otherwise for(lpszPosn=lpszString; *lpszString; lpszString=CharNext(lpszString)) { if(*lpszString != TEXT(' ')) lpszPosn = lpszString; } // Note AnsiNext is a macro for non-DBCS, so it will not stop at NULL if(*lpszPosn) *CharNext(lpszPosn) = TEXT('\0'); } } #ifndef _INC_SHLWAPI //////////////////////////////////////////////////////////////////////////////// // for StrRChr() // // ChrCmp - Case sensitive character comparison for DBCS // Assumes w1, wMatch are characters to be compared // Return FALSE if they match, TRUE if no match // __inline BOOL ChrCmpA_inline(WORD w1, WORD wMatch) { // // Most of the time this won't match, so test it first for speed. // if(LOBYTE(w1) == LOBYTE(wMatch)) { if(IsDBCSLeadByte(LOBYTE(w1))) return w1 != wMatch; return FALSE; } return TRUE; } __inline BOOL ChrCmpW_inline(WCHAR w1, WCHAR wMatch) { return w1 != wMatch; } // // StrRChr - Find last occurrence of character in string // Assumes lpStart points to start of string // lpEnd points to end of string (NOT included in search) // wMatch is the character to match // returns ptr to the last occurrence of ch in str, NULL if not found. // #define READNATIVEWORD(x) (*(UNALIGNED WORD *)x) LPSTR StrRChrA(LPCSTR lpStart, LPCSTR lpEnd, WORD wMatch) { LPCSTR lpFound = NULL; ASSERT(lpStart); ASSERT(!lpEnd || lpEnd <= lpStart + lstrlenA(lpStart)); if(!lpEnd) lpEnd = lpStart + lstrlenA(lpStart); for( ; lpStart < lpEnd; lpStart = CharNextA(lpStart)) { // ChrCmp returns FALSE when characters match if(!ChrCmpA_inline(READNATIVEWORD(lpStart), wMatch)) lpFound = lpStart; } return (LPSTR)lpFound; } LPWSTR StrRChrW(LPCWSTR lpStart, LPCWSTR lpEnd, WCHAR wMatch) { LPCWSTR lpFound = NULL; if(!lpEnd) lpEnd = lpStart + lstrlenW(lpStart); for( ; lpStart < lpEnd; lpStart++) { if(!ChrCmpW_inline(*lpStart, wMatch)) lpFound = lpStart; } return (LPWSTR)lpFound; } #endif // !_INC_SHLWAPI
true
4d5427dba2c32e107ac097e225ec9cc8df23ce45
C++
melodeeli98/codeblox-capstone
/master-firmware/codeblox_driver.ino
UTF-8
4,647
2.640625
3
[]
no_license
#include "LowPower.h" #include "codeblox_driver.h" #include "side.h" #include <avr/io.h> void resetClock(); void initDriver(void (*newMessageCallback)(const Message&, enum Side_Name)){ // turn off reflective sensors asap DDRB |= 1 << PINB7; PORTB |= 1 << PINB7; resetClock(); //select external reference analogReference(EXTERNAL); Serial.begin(9600); delay(10); initSides(newMessageCallback); } void goToSleep(){ putSidesToSleep(); //Serial.println("sleeping"); LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF); //Serial.println("awake"); } void (*newSerialMessageCallback)(char *) = NULL; void registerSerialMessageCallback(void (*callback)(char *)){ newSerialMessageCallback = callback; } int readReflectiveSensor(int sensor){ switch (sensor) { case 0: return analogRead(A0); case 1: return analogRead(A1); case 2: return analogRead(A2); case 3: return analogRead(A3); case 4: return analogRead(A4); case 5: return analogRead(A5); default: return 0; } } static const unsigned long sensorLoadTime = 1000UL; static const int sensorThreshold = 250; static volatile byte * sensors = NULL; static volatile int * sensor0 = NULL; static volatile int * sensor1 = NULL; static volatile int * sensor2 = NULL; static volatile int * sensor3 = NULL; static volatile int * sensor4 = NULL; static volatile int * sensor5 = NULL; static volatile bool readSensors = false; static volatile bool readSensorsRaw = false; static volatile unsigned long readSensorsTime = 0; static volatile unsigned long readSensorsRawTime = 0; void updateDriver(){ updateSides(); if(readSensorsTime < timeMicros() && readSensors){ readSensors = false; byte value = 0; for (int sensor = 0; sensor < numReflectiveSensors; sensor++) { value |= (((byte)!(readReflectiveSensor(sensor) < sensorThreshold)) << sensor); } *sensors = value; if(!readSensorsRaw){ PORTB |= 1 << PINB7; } } if(readSensorsRawTime < timeMicros() && readSensorsRaw){ readSensorsRaw = false; *sensor0 = readReflectiveSensor(0); *sensor1 = readReflectiveSensor(1); *sensor2 = readReflectiveSensor(2); *sensor3 = readReflectiveSensor(3); *sensor4 = readReflectiveSensor(4); *sensor5 = readReflectiveSensor(5); if(!readSensors){ PORTB |= 1 << PINB7; } } //read incoming serial messages const unsigned int maxReceivedMessageSize = 20; static char receivedMessage[maxReceivedMessageSize] = ""; static unsigned int messagePos = 0; while (Serial.available() > 0 && newSerialMessageCallback != NULL){ // read the incoming byte: char incomingByte = (char)Serial.read(); if (incomingByte == '\n') { newSerialMessageCallback(receivedMessage); receivedMessage[0] = '\0'; messagePos = 0; } else { if(messagePos < maxReceivedMessageSize-1){ receivedMessage[messagePos] = incomingByte; receivedMessage[messagePos+1] = '\0'; messagePos++; } } } } void readReflectiveSensorsLater(byte *s){ sensors = s; readSensors = true; readSensorsTime = timeMicros() + sensorLoadTime; PORTB &= ~(1 << PINB7); } void readReflectiveSensorsRawLater(int *s0, int *s1, int *s2, int *s3, int *s4, int *s5){ sensor0 = s0; sensor1 = s1; sensor2 = s2; sensor3 = s3; sensor4 = s4; sensor5 = s5; readSensorsRaw = true; readSensorsRawTime = timeMicros() + sensorLoadTime; PORTB &= ~(1 << PINB7); } size_t serialLog(const __FlashStringHelper * s){ return Serial.println(s); } size_t serialLog(const String &s){ return Serial.println(s); } size_t serialLog(const char s[]){ return Serial.println(s); } size_t serialLog(char s){ return Serial.println(s); } size_t serialLog(byte s , int i){ return Serial.println(s, i); } size_t serialLog(int s, int i){ return Serial.println(s, i); } size_t serialLog(unsigned int s, int i){ return Serial.println(s, i); } size_t serialLog(long s, int i){ return Serial.println(s, i); } size_t serialLog(unsigned long s, int i){ return Serial.println(s, i); } size_t serialLog(double s, int i){ return Serial.println(s, i); } size_t serialLog(const Printable& s){ return Serial.println(s); } size_t serialLog(void){ return Serial.println(); } const unsigned long maxTime = ~0UL; volatile unsigned long startTime = 0UL; void resetClock(){ startTime = micros(); } unsigned long timeMicros(){ volatile unsigned long currTime = micros(); if (startTime > currTime) { //aka overflow return (maxTime - startTime) + 1UL + currTime; } return currTime - startTime; }
true
53dc95f64f4467aa2e912bfcc5834372845a2d88
C++
chen415296831/usejenkins
/main.cpp
UTF-8
372
2.546875
3
[]
no_license
/*********************************************** Filename: main.cpp Author: Description: Create Data: 2019-05-16 19:03:50 Modfiy History: 2019-05-16 19:03:50 ***********************************************/ #include <iostream> #include <string> using namespace std; int main() { string hello = "hello world"; cout << hello << endl; }
true
6ce82576b726c11fa7f33f35a33e715e6b77b7fb
C++
PeteyPii/Euler
/src/problems/Problem020.cpp
UTF-8
354
2.5625
3
[ "MIT" ]
permissive
#include "SourcePrefix.h" #include "BigInteger.h" #include "Common.h" int32 problem20(int32 n) { if (n == 0) { return 1; } if (n < 0) { throw string("We shouldn't take the factorial of a negative number"); } BigInteger x(1); for (int32 i = 1; i <= n; i++) { x *= i; } return x.sumOfDigits(); } #include "SourceSuffix.h"
true
ff57609878d698d0909d353692f8796fc7a40634
C++
NAThompson/paraview_mwes
/src/EulerSpiral.cxx
UTF-8
1,608
2.75
3
[]
no_license
#include <iostream> #include <string> #include <cmath> #include <vtkm/cont/DataSet.h> #include <vtkm/cont/DataSetFieldAdd.h> #include <vtkm/cont/DataSetBuilderExplicit.h> #include <vtkm/io/writer/VTKDataSetWriter.h> #include <boost/math/quadrature/tanh_sinh.hpp> #include <boost/math/constants/constants.hpp> void write_1d_unstructured(std::vector<std::array<double, 2>> const & spiral_data) { vtkm::cont::DataSetBuilderExplicitIterative dsb; std::vector<vtkm::Id> ids; for (size_t i = 0; i < spiral_data.size(); ++i) { auto point = spiral_data[i]; vtkm::Id pid = dsb.AddPoint({point[0], point[1], 0.0}); ids.push_back(pid); } dsb.AddCell(vtkm::CELL_SHAPE_POLY_LINE, ids); vtkm::cont::DataSet dataSet = dsb.Create(); vtkm::io::VTKDataSetWriter writer("euler_spiral.vtk"); writer.WriteDataSet(dataSet); } void build_euler_spiral(int samples, double t_max) { std::vector<std::array<double, 2>> spiral_data(samples); double dt = 2*t_max/samples; auto integrator = boost::math::quadrature::tanh_sinh<double>(); auto x_coord = [](double s) { return std::cos(s*s); }; auto y_coord = [](double s) { return std::sin(s*s); }; for (size_t i = 0; i < samples; ++i) { double t = -t_max + i*dt; double x = integrator.integrate(x_coord, 0.0, t); double y = integrator.integrate(y_coord, 0.0, t); spiral_data[i] = {x, y}; } write_1d_unstructured(spiral_data); } int main(int argc, char** argv) { int samples = 1024; double t_max = 9; build_euler_spiral(samples, t_max); }
true
0b5bb4db01b0e00bcb85f84dc959ecf5f8471c1b
C++
JustEndRay/Lab3.3E-OOP-
/Bus.h
UTF-8
611
2.953125
3
[]
no_license
#pragma once #include "Car.h" #include <string> #include <iostream> #include <sstream> class Bus :public Car { private: int Number_of_passenger_seats; public: Bus(); Bus(int); Bus(Bus&); void SetNumber_of_passenger_seats(int Power); int GetNumber_of_passenger_seats() const; void Re_assignment_Number_of_passenger_seats(); void Change_Number_of_passenger_seats(); friend ostream& operator << (ostream& out, const Bus& A); friend istream& operator >> (istream& in, Bus& A); operator string() const; Bus& operator ++ (); Bus& operator -- (); Bus operator ++ (int); Bus operator -- (int); };
true
a403e6f2bbe89c8b970d647033709ede28bf592f
C++
LeulShiferaw/resume
/IA/SA-odd/main.cpp
UTF-8
4,887
3.0625
3
[]
no_license
/* * ===================================================================================== * * Filename: main.cpp * * Description: Odd version of SA * * Version: 1.0 * Created: 26.12.2016 05:36:08 * Revision: none * Compiler: gcc * * Author: Leul Shiferaw (ls), l.shiferaw@jacobs-university.de * Organization: * * ===================================================================================== */ #include <stdio.h> //Add A, B and put it in C //But based on ax, ay... void add(int **A, int **B, int **C, const int &ax, const int &ay, const int &bx, const int &by, const int &cx, const int &cy, const int &s) { for(int i = 0; i<s; ++i) for(int j = 0; j<s; ++j) C[cx+i][cy+j] = A[ax+i][ay+i]+B[bx+i][by+j]; } //Subtract A, B and put it in C //But based on ax, ay... void subtr(int **A, int **B, int **C, const int &ax, const int &ay, const int &bx, const int &by, const int &cx, const int &cy, const int &s) { for(int i = 0; i<s; ++i) for(int j = 0; j<s; ++j) C[cx+i][cy+j] = A[ax+i][ay+i]-B[bx+i][by+j]; } //Using Strassen's Algo multiply A and B and put it in C //But multiply only the portion described by ax, ay... //s-size void multiply(int **A, int **B, int **C, const int &ax, const int &ay, const int &bx, const int &by, const int &cx, const int &cy, const int &s) { //Base Case if(s==1) { C[cx][cy] = A[ax][ay]*B[bx][by]; return; } const int n = (s+(s%2))/2; //Create Sum and Product Matrices int **S[10], **P[7]; for(int i = 0; i<10; ++i) { if(i<7) P[i] = new int*[n]; S[i] = new int*[n]; for(int j = 0; j<n; ++j) { S[i][j] = new int[n]; if(i<7) P[i][j] = new int[n]; } } //Define Location constants const int a11x = ax; const int a11y = ay; const int a12x = ax; const int a12y = ay+n; const int a21x = ax+n; const int a21y = ay; const int a22x = ax+n; const int a22y = ay+n; const int b11x = bx; const int b11y = by; const int b12x = bx; const int b12y = by+n; const int b21x = bx+n; const int b21y = by; const int b22x = bx+n; const int b22y = by+n; const int c11x = cx; const int c11y = cy; const int c12x = cx; const int c12y = cy+n; const int c21x = cx+n; const int c21y = cy; const int c22x = cx+n; const int c22y = cy+n; //Calc Sums subtr(B, B, S[0], b12x, b12y, b22x, b22y, 0, 0, n);//B12-B22 add(A, A, S[1], a11x, a11y, a12x, a12y, 0, 0, n);//A11+A12 add(A, A, S[2], a21x, a21y, a22x, a22y, 0, 0, n);//A21+A22 subtr(B, B, S[3], b21x, b21y, b11x, b11y, 0, 0, n);//B21-B11 add(A, A, S[4], a11x, a11y, a22x, a22y, 0, 0, n);//A11+A22 add(B, B, S[5], b11x, b11y, b22x, b22y, 0, 0, n);//B11+B22 subtr(A, A, S[6], a12x, a12y, a22x, a22y, 0, 0, n);//A12-A22 add(B, B, S[7], b21x, b21y, b22x, b22y, 0, 0, n);//B21+B22 subtr(A, A, S[8], a11x, a11y, a21x, a21y, 0, 0, n);//A11-A21 add(B, B, S[9], b11x, b11y, b12x, b12y, 0, 0, n);//B11+B12 //Calc Products multiply(A, S[0], P[0], a11x, a11y, 0, 0, 0, 0, n);//A11*S1 multiply(S[1], B, P[1], 0, 0, b22x, b22y, 0, 0, n);//S2*B22 multiply(S[2], B, P[2], 0, 0, b11x, b11y, 0, 0, n);//S3*B11 multiply(A, S[3], P[3], a22x, a22y, 0, 0, 0, 0, n);//A22*S4 multiply(S[4], S[5], P[4], 0, 0, 0, 0, 0, 0, n);//S5*S6 multiply(S[6], S[7], P[5], 0, 0, 0, 0, 0, 0, n);//S7*S8 multiply(S[8], S[9], P[6], 0, 0, 0, 0, 0, 0, n);//S9*S10 //Calc C //Use S as temp storage add(P[4], P[3], S[0], 0, 0, 0, 0, 0, 0, n); subtr(S[0], P[1], S[0], 0, 0, 0, 0, 0, 0, n); add(S[0], P[5], C, 0, 0, 0, 0, c11x, c11y, n);//C11 = P5+P4-P2+p6 add(P[0], P[1], C, 0, 0, 0, 0, c12x, c12y, n);//C12 = P1+P2 add(P[2], P[3], C, 0, 0, 0, 0, c21x, c21y, n);//C21 = P3+P4 add(P[4], P[0], S[0], 0, 0, 0, 0, 0, 0, n); subtr(S[0], P[2], S[0], 0, 0, 0, 0, 0, 0, n); subtr(S[0], P[6], C, 0, 0, 0, 0, c22x, c22y, n);//C22 = P5+P1-P3-P7 for(int i = 0; i<10; ++i) { for(int j = 0; j<n; ++j) { if(i<7) { delete[]P[i][j]; P[i][j] = NULL; } delete[]S[i][j]; S[i][j] = NULL; } } for(int i = 0; i<10; ++i) { if(i<7) { delete[]P[i]; P[i] = NULL; } delete[]S[i]; S[i] = NULL; } } void display(int **A, const int &n) { for(int i = 0; i<n; ++i) { for(int j = 0; j<n; ++j) printf("%d ", A[i][j]); printf("\n"); } } int main() { int n = 2; int **A, **B, **C; //Create 3 nxn matrices A = new int*[n]; B = new int*[n]; C = new int*[n]; for(int i = 0; i<n; ++i) { A[i] = new int[n]; B[i] = new int[n]; C[i] = new int[n]; } //Assign A and B A[0][0] = 1; A[0][1] = 2; A[1][0] = 3; A[1][1] = 4; B[0][0] = 5; B[0][1] = 6; B[1][0] = 7; B[1][1] = 8; //A*B = C multiply(A, B, C, 0, 0, 0, 0, 0, 0, n); printf("Result: \n"); display(C, n); //Free Data for(int i = 0; i<n; ++i) { delete[]A[i]; delete[]B[i]; delete[]C[i]; A[i] = B[i] = C[i] = NULL; } delete[]A; delete[]B; delete[]C; A = NULL; B = NULL; C = NULL; return 0; }
true
806d8ad9ac1cba1658020dcd12d31f67c948b310
C++
tjlaboss/OpenMOC
/src/Timer.h
UTF-8
2,210
2.703125
3
[ "MIT" ]
permissive
/** * @file Timer.h * @brief The Timer class. * @date January 2, 2012 * @author William Boyd, MIT, Course 22 (wboyd@mit.edu) */ #ifndef TIMER_H_ #define TIMER_H_ #ifdef __cplusplus #ifdef SWIG #include "Python.h" #endif #include "log.h" #include "constants.h" #include <time.h> #include <omp.h> #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <utility> #include <map> #include <vector> #include <string> #include <ios> #include <unistd.h> #endif #ifdef MPIx #include <mpi.h> #endif /** * @class Timer Timer.h "src/Timer.cpp" * @brief The Timer class is for timing and profiling regions of code. */ class Timer { private: /** A vector of floating point start times at each inclusive level * at which we are timing */ static std::vector<double> _start_times; /** The time elapsed (seconds) for the current split */ float _elapsed_time; /** Whether or not the Timer is running for the current split */ bool _running; /** A vector of the times and messages for each split */ static std::map<std::string, double> _timer_splits; /** * @brief Assignment operator for static referencing of the Timer. * @param & the Timer static class object * @return a pointer to the Timer static class object */ Timer &operator=(const Timer &) { return *this; } /** * @brief Timer constructor. * @param & The Timer static reference pointer. */ Timer(const Timer &) { } public: /** * @brief Constructor sets the current split elapsed time to zero. */ Timer() { _running = false; _elapsed_time = 0; } /** * @brief Destructor. */ virtual ~Timer() { } /** * @brief Returns a static instance of the Timer class. * @return a pointer to the static Timer class */ static Timer *Get() { static Timer instance; return &instance; } void startTimer(); void stopTimer(); void recordSplit(const char* msg); double getTime(); double getSplit(const char* msg); void printSplits(); void clearSplit(const char* msg); void clearSplits(); void processMemUsage(double& vm_usage, double& resident_set); #ifdef MPIx void reduceTimer(MPI_Comm comm); #endif }; #endif /* TIMER_H_ */
true
8eb8ad0d62ef6d26c1aa22f879ac2a2c72bee600
C++
Igronemyk/OI
/LuoGu/p3379-2.cpp
UTF-8
3,416
2.921875
3
[]
no_license
#include <cstdio> #include <algorithm> #include <cstring> #include <cmath> using namespace std; template<typename T> T read() { T result = 0;int f = 1;char c = getchar(); while(c > '9' || c < '0') {if(c == '-') f *= -1;c = getchar();} while(c <='9' && c >= '0') {result = result * 10 + c - '0';c = getchar();} return result * f; } struct Graph { struct Edge { int next,to; } *edges; int tot,*heads; Graph(int edgeSize,int nodeSize) { edges = new Edge[edgeSize]; tot = 0; heads = new int[nodeSize]; memset(heads,-1,sizeof(int) * nodeSize); } void addEdge(int u,int v) { edges[tot].to = v; edges[tot].next = heads[u]; heads[u] = tot++; } }; struct ST { int **values,*compareVal; ST(int *val,int length,int *compareVal) : compareVal(compareVal) { values = new int*[length]; int calLen = myLog2(length); for(int i = 0;i < length;i++) { values[i] = new int[calLen + 1]; values[i][0] = val[i]; } for(int j = 1;j <= calLen;j++) { for(int i = 0;i + (1 << j) - 1 < length;i++) { if(compareVal[values[i][j - 1]] <= compareVal[values[i + (1 << (j - 1))][j - 1]]) { values[i][j] = values[i][j - 1]; }else { values[i][j] = values[i + (1 << (j - 1))][j - 1]; } } } } int query(int left,int right) { if(left > right) return -1; int logVal = myLog2(right - left + 1); if(compareVal[values[left][logVal]] <= compareVal[values[right - (1 << logVal) + 1][logVal]]) { return values[left][logVal]; }else { return values[right - (1 << logVal) + 1][logVal]; } } int myLog2(int val) { return static_cast<int>(log(static_cast<double>(val)) / log(2.0)); } }; void getSeq(int now,int father,int nowDepth,int &nowInsertPos,int *values,int *depth,Graph &graph,int *firstPos) { values[nowInsertPos] = now; if(firstPos[now] == -1) { firstPos[now] = nowInsertPos; } depth[now] = nowDepth; nowInsertPos++; for(int i = graph.heads[now];i != -1;i = graph.edges[i].next) { Graph::Edge &tmpEdge = graph.edges[i]; if(tmpEdge.to == father) continue; getSeq(tmpEdge.to,now,nowDepth + 1,nowInsertPos,values,depth,graph,firstPos); values[nowInsertPos++] = now; } } int main() { int N = read<int>(),M = read<int>(),S = read<int>(); S--; Graph graph((N - 1) * 2,N); for(int i = 0;i < N - 1;i++) { int u = read<int>(),v = read<int>(); u--; v--; graph.addEdge(u,v); graph.addEdge(v,u); } int nowInsertPos = 0,*values = new int[2 * N - 1],*depth = new int[N],*firstPos = new int[N]; memset(depth,-1,sizeof(int) * N); memset(firstPos,-1,sizeof(int) * N); getSeq(S,-1,0,nowInsertPos,values,depth,graph,firstPos); ST table(values,2 * N - 1,depth); while(M--) { int u = read<int>(),v = read<int>(); u--; v--; int queryU = firstPos[u],queryV = firstPos[v]; if(queryU > queryV) swap(queryU,queryV); printf("%d\n",table.query(queryU,queryV) + 1); } return 0; }
true
695bf334b2666e772e69f7fcf78158c2865d0ce5
C++
AkiKuraTomoKu/SRC16_Real-Rover
/programms/check/NMEA/NMEA.ino
UTF-8
162
2.640625
3
[]
no_license
void setup(void){ Serial.begin(115200); Serial2.begin(9600); } void loop(void){ if(Serial2.available()){ Serial.print((char)Serial2.read()); } }
true
9887e7bb3bcdaf04e663ce0e464a9164d082b8f3
C++
abasak24/SAGA-Bench
/src/dynamic/types.h
UTF-8
3,060
2.96875
3
[ "BSD-2-Clause" ]
permissive
#ifndef TYPES_H_ #define TYPES_H_ #include <cstdint> #include <iostream> #include <limits> #include <map> #include <queue> #include <vector> /* Basic building blocks for node and its variations, typedefs. */ typedef int64_t NodeID; typedef int64_t Weight; typedef int PID; typedef std::map<NodeID, NodeID> MapTable; static const int32_t kRandSeed = 27491095; const float kDistInf = std::numeric_limits<float>::max()/2; const size_t kMaxBin = std::numeric_limits<size_t>::max()/2; class EdgeID: public std::pair<NodeID, NodeID> { public: EdgeID(): std::pair<NodeID, NodeID>(0, 0) {} EdgeID(NodeID a, NodeID b): std::pair<NodeID, NodeID>(a, b) {} inline int operator %(int mod) const { return this->first % mod; } }; class BaseNode { public: virtual NodeID getNodeID() const = 0; virtual Weight getWeight() const = 0; virtual void setInfo(NodeID n, Weight w) = 0; virtual void printNode() const = 0; }; class Node: public BaseNode { private: NodeID node; public: Node(): node(-1){} Node(NodeID n):node(n){} void setInfo(NodeID n, Weight w){ (void)w; node = n; } NodeID getNodeID() const {return node;} Weight getWeight() const {return -1;} void printNode() const{ std::cout << node << " "; } }; class NodeWeight: public BaseNode { NodeID node; Weight weight; public: NodeWeight():node(-1), weight(-1){} NodeWeight(NodeID n):node(n), weight(-1){} NodeWeight(NodeID n, Weight w): node(n), weight(w) {} void setInfo(NodeID n, Weight w){ node = n; weight = w; } Weight getWeight() const {return weight;} NodeID getNodeID() const {return node;} void printNode() const{ std::cout << "(" << node << "," << weight << ")" << " "; } bool operator< (const NodeWeight& rhs) const { return node == rhs.getNodeID() ? weight < rhs.getWeight() : node < rhs.getNodeID(); } bool operator== (const NodeWeight& rhs) const { return (node == rhs.getNodeID()) && (weight == rhs.getWeight()); } }; struct Edge { NodeID source; NodeID destination; Weight weight; int batch_id; bool sourceExists; bool destExists; Edge(NodeID s, NodeID d, Weight w, bool se, bool de): source(s), destination(d), weight(w), batch_id(-1), sourceExists(se), destExists(de) {} Edge(NodeID s, NodeID d, bool se, bool de): Edge(s, d, -1, se, de) {} Edge(NodeID s, NodeID d, Weight w): Edge(s, d, w, false, false) {} Edge(NodeID s, NodeID d): Edge(s, d, -1) {} Edge(){} Edge reverse() const { return Edge(destination, source, weight, destExists, sourceExists); } }; typedef std::vector<Edge> EdgeList; typedef std::queue<Edge> EdgeQueue; typedef std::queue<EdgeList> EdgeBatchQueue; std::ostream& operator<<(std::ostream &out, EdgeID const &id); std::ostream& operator<<(std::ostream &out, Node const &nd); std::ostream& operator<<(std::ostream &out, NodeWeight const &nw); #endif // TYPES_H_
true
8096218637f32f35e9d723d8766176b9bcc74e39
C++
KeyKy/issue
/caffe_thread_learn.hpp
UTF-8
1,092
2.8125
3
[]
no_license
#ifndef caffe_thread_learn_hpp #define caffe_thread_learn_hpp #include <stdio.h> #include <boost/thread.hpp> #include <boost/shared_ptr.hpp> namespace boost { class thread; } class InternalThread { public: InternalThread() : thread_() {} virtual ~InternalThread(); /** * Caffe's thread local state will be initialized using the current * thread values, e.g. device id, solver index etc. The random seed * is initialized using caffe_rng_rand. */ void StartInternalThread(); /** Will not return until the internal thread has exited. */ void StopInternalThread(); bool is_started() const; protected: /* Implement this method in your subclass with the code you want your thread to run. */ virtual void InternalThreadEntry() { std::cout << "parant" << std::endl; } virtual void fun() {} /* Should be tested when running loops to exit when requested. */ bool must_stop(); private: void entry(); boost::shared_ptr<boost::thread> thread_; }; #endif /* caffe_thread_learn_hpp */
true
c0b32d40141176476800cad5588f6347dfef3be4
C++
chromium/chromium
/base/containers/intrusive_heap.h
UTF-8
42,335
3.21875
3
[ "BSD-3-Clause" ]
permissive
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_CONTAINERS_INTRUSIVE_HEAP_H_ #define BASE_CONTAINERS_INTRUSIVE_HEAP_H_ // Implements a standard max-heap, but with arbitrary element removal. To // facilitate this, each element has associated with it a HeapHandle (an opaque // wrapper around the index at which the element is stored), which is maintained // by the heap as elements move within it. // // An IntrusiveHeap is implemented as a standard max-heap over a std::vector<T>, // like std::make_heap. Insertion, removal and updating are amortized O(lg size) // (occasional O(size) cost if a new vector allocation is required). Retrieving // an element by handle is O(1). Looking up the top element is O(1). Insertions, // removals and updates invalidate all iterators, but handles remain valid. // Similar to a std::set, all iterators are read-only so as to disallow changing // elements and violating the heap property. That being said, if the type you // are storing is able to have its sort key be changed externally you can // repair the heap by resorting the modified element via a call to "Update". // // Example usage: // // // Create a heap, wrapping integer elements with WithHeapHandle in order to // // endow them with heap handles. // IntrusiveHeap<WithHeapHandle<int>> heap; // // // WithHeapHandle<T> is for simple or opaque types. In cases where you // // control the type declaration you can also provide HeapHandle storage by // // deriving from InternalHeapHandleStorage. // class Foo : public InternalHeapHandleStorage { // public: // explicit Foo(int); // ... // }; // IntrusiveHeap<Foo> heap2; // // // Insert some elements. Like most containers, "insert" returns an iterator // // to the element in the container. // heap.insert(3); // heap.insert(1); // auto it = heap.insert(4); // // // By default this is a max heap, so the top element should be 4 at this // // point. // EXPECT_EQ(4, heap.top().value()); // // // Iterators are invalidated by further heap operations, but handles are // // not. Grab a handle to the current top element so we can track it across // // changes. // HeapHandle* handle = it->handle(); // // // Insert a new max element. 4 should no longer be the top. // heap.insert(5); // EXPECT_EQ(5, heap.top().value()); // // // We can lookup and erase element 4 by its handle, even though it has // // moved. Note that erasing the element invalidates the handle to it. // EXPECT_EQ(4, heap.at(*handle).value()); // heap.erase(*handle); // handle = nullptr; // // // Popping the current max (5), makes 3 the new max, as we already erased // // element 4. // heap.pop(); // EXPECT_EQ(3, heap.top().value()); // // Under the hood the HeapHandle is managed by an object implementing the // HeapHandleAccess interface, which is passed as a parameter to the // IntrusiveHeap template: // // // Gets the heap handle associated with the element. This should return the // // most recently set handle value, or HeapHandle::Invalid(). This is only // // called in DCHECK builds. // HeapHandle GetHeapHandle(const T*); // // // Changes the result of GetHeapHandle. GetHeapHandle() must return the // // most recent value provided to SetHeapHandle() or HeapHandle::Invalid(). // // In some implementations, where GetHeapHandle() can independently // // reproduce the correct value, it is possible that SetHeapHandle() does // // nothing. // void SetHeapHandle(T*, HeapHandle); // // // Clears the heap handle associated with the given element. After calling // // this GetHeapHandle() must return HeapHandle::Invalid(). // void ClearHeapHandle(T*); // // The default implementation of HeapHandleAccess assumes that your type // provides HeapHandle storage and will simply forward these calls to equivalent // member functions on the type T: // // void T::SetHeapHandle(HeapHandle) // void T::ClearHeapHandle() // HeapHandle T::GetHeapHandle() const // // The WithHeapHandle and InternalHeapHandleStorage classes in turn provide // implementations of that contract. // // In summary, to provide heap handle support for your type, you can do one of // the following (from most manual / least magical, to least manual / most // magical): // // 0. use a custom HeapHandleAccessor, and implement storage however you want; // 1. use the default HeapHandleAccessor, and manually provide storage on your // your element type and implement the IntrusiveHeap contract; // 2. use the default HeapHandleAccessor, and endow your type with handle // storage by deriving from a helper class (see InternalHeapHandleStorage); // or, // 3. use the default HeapHandleAccessor, and wrap your type in a container that // provides handle storage (see WithHeapHandle<T>). // // Approach 0 is suitable for custom types that already implement something akin // to heap handles, via back pointers or any other mechanism, but where the // storage is external to the objects in the heap. If you already have the // ability to determine where in a container an object lives despite it // being moved, then you don't need the overhead of storing an actual HeapHandle // whose value can be inferred. // // Approach 1 is is suitable in cases like the above, but where the data // allowing you to determine the index of an element in a container is stored // directly in the object itself. // // Approach 2 is suitable for types whose declarations you control, where you // are able to use inheritance. // // Finally, approach 3 is suitable when you are storing PODs, or a type whose // declaration you can not change. // // Most users should be using approach 2 or 3. #include <algorithm> #include <functional> #include <limits> #include <memory> #include <type_traits> #include <utility> #include <vector> #include "base/base_export.h" #include "base/check.h" #include "base/check_op.h" #include "base/memory/ptr_util.h" #include "base/ranges/algorithm.h" #include "third_party/abseil-cpp/absl/container/inlined_vector.h" namespace base { // Intended as a wrapper around an |index_| in the vector storage backing an // IntrusiveHeap. A HeapHandle is associated with each element in an // IntrusiveHeap, and is maintained by the heap as the object moves around // within it. It can be used to subsequently remove the element, or update it // in place. class BASE_EXPORT HeapHandle { public: enum : size_t { kInvalidIndex = std::numeric_limits<size_t>::max() }; constexpr HeapHandle() = default; constexpr HeapHandle(const HeapHandle& other) = default; HeapHandle(HeapHandle&& other) noexcept : index_(std::exchange(other.index_, kInvalidIndex)) {} ~HeapHandle() = default; HeapHandle& operator=(const HeapHandle& other) = default; HeapHandle& operator=(HeapHandle&& other) noexcept { index_ = std::exchange(other.index_, kInvalidIndex); return *this; } static HeapHandle Invalid(); // Resets this handle back to an invalid state. void reset() { index_ = kInvalidIndex; } // Accessors. size_t index() const { return index_; } bool IsValid() const { return index_ != kInvalidIndex; } // Comparison operators. friend bool operator==(const HeapHandle& lhs, const HeapHandle& rhs) { return lhs.index_ == rhs.index_; } friend bool operator!=(const HeapHandle& lhs, const HeapHandle& rhs) { return lhs.index_ != rhs.index_; } friend bool operator<(const HeapHandle& lhs, const HeapHandle& rhs) { return lhs.index_ < rhs.index_; } friend bool operator>(const HeapHandle& lhs, const HeapHandle& rhs) { return lhs.index_ > rhs.index_; } friend bool operator<=(const HeapHandle& lhs, const HeapHandle& rhs) { return lhs.index_ <= rhs.index_; } friend bool operator>=(const HeapHandle& lhs, const HeapHandle& rhs) { return lhs.index_ >= rhs.index_; } private: template <typename T, typename Compare, typename HeapHandleAccessor> friend class IntrusiveHeap; // Only IntrusiveHeaps can create valid HeapHandles. explicit HeapHandle(size_t index) : index_(index) {} size_t index_ = kInvalidIndex; }; // The default HeapHandleAccessor, which simply forwards calls to the underlying // type. template <typename T> struct DefaultHeapHandleAccessor { void SetHeapHandle(T* element, HeapHandle handle) const { element->SetHeapHandle(handle); } void ClearHeapHandle(T* element) const { element->ClearHeapHandle(); } HeapHandle GetHeapHandle(const T* element) const { return element->GetHeapHandle(); } }; // Intrusive heap class. This is something like a std::vector (insertion and // removal are similar, objects don't have a fixed address in memory) crossed // with a std::set (elements are considered immutable once they're in the // container). template <typename T, typename Compare = std::less<T>, typename HeapHandleAccessor = DefaultHeapHandleAccessor<T>> class IntrusiveHeap { private: using UnderlyingType = std::vector<T>; public: ////////////////////////////////////////////////////////////////////////////// // Types. using value_type = typename UnderlyingType::value_type; using size_type = typename UnderlyingType::size_type; using difference_type = typename UnderlyingType::difference_type; using value_compare = Compare; using heap_handle_accessor = HeapHandleAccessor; using reference = typename UnderlyingType::reference; using const_reference = typename UnderlyingType::const_reference; using pointer = typename UnderlyingType::pointer; using const_pointer = typename UnderlyingType::const_pointer; // Iterators are read-only. using iterator = typename UnderlyingType::const_iterator; using const_iterator = typename UnderlyingType::const_iterator; using reverse_iterator = typename UnderlyingType::const_reverse_iterator; using const_reverse_iterator = typename UnderlyingType::const_reverse_iterator; ////////////////////////////////////////////////////////////////////////////// // Lifetime. IntrusiveHeap() = default; IntrusiveHeap(const value_compare& comp, const heap_handle_accessor& access) : impl_(comp, access) {} template <class InputIterator> IntrusiveHeap(InputIterator first, InputIterator last, const value_compare& comp = value_compare(), const heap_handle_accessor& access = heap_handle_accessor()) : impl_(comp, access) { insert(first, last); } // Moves an intrusive heap. The outstanding handles remain valid and end up // pointing to the new heap. IntrusiveHeap(IntrusiveHeap&& other) = default; // Copy constructor for an intrusive heap. IntrusiveHeap(const IntrusiveHeap&); // Initializer list constructor. template <typename U> IntrusiveHeap(std::initializer_list<U> ilist, const value_compare& comp = value_compare(), const heap_handle_accessor& access = heap_handle_accessor()) : impl_(comp, access) { insert(std::begin(ilist), std::end(ilist)); } ~IntrusiveHeap(); ////////////////////////////////////////////////////////////////////////////// // Assignment. IntrusiveHeap& operator=(IntrusiveHeap&&) noexcept; IntrusiveHeap& operator=(const IntrusiveHeap&); IntrusiveHeap& operator=(std::initializer_list<value_type> ilist); ////////////////////////////////////////////////////////////////////////////// // Element access. // // These provide O(1) const access to the elements in the heap. If you wish to // modify an element in the heap you should first remove it from the heap, and // then reinsert it into the heap, or use the "Replace*" helper functions. In // the rare case where you directly modify an element in the heap you can // subsequently repair the heap with "Update". const_reference at(size_type pos) const { return impl_.heap_.at(pos); } const_reference at(HeapHandle pos) const { return impl_.heap_.at(pos.index()); } const_reference operator[](size_type pos) const { return impl_.heap_[pos]; } const_reference operator[](HeapHandle pos) const { return impl_.heap_[pos.index()]; } const_reference front() const { return impl_.heap_.front(); } const_reference back() const { return impl_.heap_.back(); } const_reference top() const { return impl_.heap_.front(); } // May or may not return a null pointer if size() is zero. const_pointer data() const { return impl_.heap_.data(); } ////////////////////////////////////////////////////////////////////////////// // Memory management. void reserve(size_type new_capacity) { impl_.heap_.reserve(new_capacity); } size_type capacity() const { return impl_.heap_.capacity(); } void shrink_to_fit() { impl_.heap_.shrink_to_fit(); } ////////////////////////////////////////////////////////////////////////////// // Size management. void clear(); size_type size() const { return impl_.heap_.size(); } size_type max_size() const { return impl_.heap_.max_size(); } bool empty() const { return impl_.heap_.empty(); } ////////////////////////////////////////////////////////////////////////////// // Iterators. // // Only constant iterators are allowed. const_iterator begin() const { return impl_.heap_.cbegin(); } const_iterator cbegin() const { return impl_.heap_.cbegin(); } const_iterator end() const { return impl_.heap_.cend(); } const_iterator cend() const { return impl_.heap_.cend(); } const_reverse_iterator rbegin() const { return impl_.heap_.crbegin(); } const_reverse_iterator crbegin() const { return impl_.heap_.crbegin(); } const_reverse_iterator rend() const { return impl_.heap_.crend(); } const_reverse_iterator crend() const { return impl_.heap_.crend(); } ////////////////////////////////////////////////////////////////////////////// // Insertion (these are std::multiset like, with no position hints). // // All insertion operations invalidate iterators, pointers and references. // Handles remain valid. Insertion of one element is amortized O(lg size) // (occasional O(size) cost if a new vector allocation is required). const_iterator insert(const value_type& value) { return InsertImpl(value); } const_iterator insert(value_type&& value) { return InsertImpl(std::move_if_noexcept(value)); } template <class InputIterator> void insert(InputIterator first, InputIterator last); template <typename... Args> const_iterator emplace(Args&&... args); ////////////////////////////////////////////////////////////////////////////// // Removing elements. // // Erasing invalidates all outstanding iterators, pointers and references. // Handles remain valid. Removing one element is amortized O(lg size) // (occasional O(size) cost if a new vector allocation is required). // // Note that it is safe for the element being removed to be in an invalid // state (modified such that it may currently violate the heap property) // when this called. // Takes the element from the heap at the given position, erasing that entry // from the heap. This can only be called if |value_type| is movable. value_type take(size_type pos); // Version of take that will accept iterators and handles. This can only be // called if |value_type| is movable. template <typename P> value_type take(P pos) { return take(ToIndex(pos)); } // Takes the top element from the heap. value_type take_top() { return take(0u); } // Erases the element at the given position |pos|. void erase(size_type pos); // Version of erase that will accept iterators and handles. template <typename P> void erase(P pos) { erase(ToIndex(pos)); } // Removes the element at the top of the heap (accessible via "top", or // "front" or "take"). void pop() { erase(0u); } // Erases every element that matches the predicate. This is done in-place for // maximum efficiency. Also, to avoid re-entrancy issues, elements are deleted // at the very end. // Note: This function is currently tuned for a use-case where there are // usually 8 or less elements removed at a time. Consider adding a template // parameter if a different tuning is needed. template <typename Functor> void EraseIf(Functor predicate) { // Stable partition ensures that if no elements are erased, the heap remains // intact. auto erase_start = std::stable_partition( impl_.heap_.begin(), impl_.heap_.end(), [&](const auto& element) { return !predicate(element); }); // Clear the heap handle of every element that will be erased. for (size_t i = static_cast<size_t>(erase_start - impl_.heap_.begin()); i < impl_.heap_.size(); ++i) { ClearHeapHandle(i); } // Deleting an element can potentially lead to reentrancy, we move all the // elements to be erased into a temporary container before deleting them. // This is to avoid changing the underlying container during the erase() // call. absl::InlinedVector<value_type, 8> elements_to_delete; std::move(erase_start, impl_.heap_.end(), std::back_inserter(elements_to_delete)); impl_.heap_.erase(erase_start, impl_.heap_.end()); // If no elements were removed, then the heap is still intact. if (elements_to_delete.empty()) { return; } // Repair the heap and ensure handles are pointing to the right index. ranges::make_heap(impl_.heap_, value_comp()); for (size_t i = 0; i < size(); ++i) SetHeapHandle(i); // Explicitly delete elements last. elements_to_delete.clear(); } ////////////////////////////////////////////////////////////////////////////// // Updating. // // Amortized cost of O(lg size). // Replaces the element corresponding to |handle| with a new |element|. const_iterator Replace(size_type pos, const T& element) { return ReplaceImpl(pos, element); } const_iterator Replace(size_type pos, T&& element) { return ReplaceImpl(pos, std::move_if_noexcept(element)); } // Versions of Replace that will accept handles and iterators. template <typename P> const_iterator Replace(P pos, const T& element) { return ReplaceImpl(ToIndex(pos), element); } template <typename P> const_iterator Replace(P pos, T&& element) { return ReplaceImpl(ToIndex(pos), std::move_if_noexcept(element)); } // Replaces the top element in the heap with the provided element. const_iterator ReplaceTop(const T& element) { return ReplaceTopImpl(element); } const_iterator ReplaceTop(T&& element) { return ReplaceTopImpl(std::move_if_noexcept(element)); } // Causes the object at the given location to be resorted into an appropriate // position in the heap. To be used if the object in the heap was externally // modified, and the heap needs to be repaired. This only works if a single // heap element has been modified, otherwise the behaviour is undefined. const_iterator Update(size_type pos); template <typename P> const_iterator Update(P pos) { return Update(ToIndex(pos)); } // Applies a modification function to the object at the given location, then // repairs the heap. To be used to modify an element in the heap in-place // while keeping the heap intact. template <typename P, typename UnaryOperation> const_iterator Modify(P pos, UnaryOperation unary_op) { size_type index = ToIndex(pos); unary_op(impl_.heap_.at(index)); return Update(index); } ////////////////////////////////////////////////////////////////////////////// // Access to helper functors. const value_compare& value_comp() const { return impl_.get_value_compare(); } const heap_handle_accessor& heap_handle_access() const { return impl_.get_heap_handle_access(); } ////////////////////////////////////////////////////////////////////////////// // General operations. void swap(IntrusiveHeap& other) noexcept; friend void swap(IntrusiveHeap& lhs, IntrusiveHeap& rhs) { lhs.swap(rhs); } // Comparison operators. These check for exact equality. Two heaps that are // semantically equivalent (contain the same elements, but in different // orders) won't compare as equal using these operators. friend bool operator==(const IntrusiveHeap& lhs, const IntrusiveHeap& rhs) { return lhs.impl_.heap_ == rhs.impl_.heap_; } friend bool operator!=(const IntrusiveHeap& lhs, const IntrusiveHeap& rhs) { return lhs.impl_.heap_ != rhs.impl_.heap_; } ////////////////////////////////////////////////////////////////////////////// // Utility functions. // Converts iterators and handles to indices. Helpers for templated versions // of insert/erase/Replace. size_type ToIndex(HeapHandle handle) { return handle.index(); } size_type ToIndex(const_iterator pos); size_type ToIndex(const_reverse_iterator pos); private: // Templated version of ToIndex that lets insert/erase/Replace work with all // integral types. template <typename I, typename = std::enable_if_t<std::is_integral<I>::value>> size_type ToIndex(I pos) { return static_cast<size_type>(pos); } // Returns the last valid index in |heap_|. size_type GetLastIndex() const { return impl_.heap_.size() - 1; } // Helper functions for setting heap handles. void SetHeapHandle(size_type i); void ClearHeapHandle(size_type i); HeapHandle GetHeapHandle(size_type i); // Helpers for doing comparisons between elements inside and outside of the // heap. bool Less(size_type i, size_type j); bool Less(const T& element, size_type i); bool Less(size_type i, const T& element); // The following function are all related to the basic heap algorithm // underpinning this data structure. They are templated so that they work with // both movable (U = T&&) and non-movable (U = const T&) types. // Primitive helpers for adding removing / elements to the heap. To minimize // moves, the heap is implemented by making a hole where an element used to // be (or where a new element will soon be), and moving the hole around, // before finally filling the hole or deleting the entry corresponding to the // hole. void MakeHole(size_type pos); template <typename U> void FillHole(size_type hole, U element); void MoveHole(size_type new_hole_pos, size_type old_hole_pos); // Moves a hold up the tree and fills it with the provided |element|. Returns // the final index of the element. template <typename U> size_type MoveHoleUpAndFill(size_type hole_pos, U element); // Moves a hole down the tree and fills it with the provided |element|. If // |kFillWithLeaf| is true it will deterministically move the hole all the // way down the tree, avoiding a second comparison per level, before // potentially moving it back up the tree. struct WithLeafElement { static constexpr bool kIsLeafElement = true; }; struct WithElement { static constexpr bool kIsLeafElement = false; }; template <typename FillElementType, typename U> size_type MoveHoleDownAndFill(size_type hole_pos, U element); // Implementation of Insert and Replace built on top of the MoveHole // primitives. template <typename U> const_iterator InsertImpl(U element); template <typename U> const_iterator ReplaceImpl(size_type pos, U element); template <typename U> const_iterator ReplaceTopImpl(U element); // To support comparators that may not be possible to default-construct, we // have to store an instance of value_compare. Using this to store all // internal state of IntrusiveHeap and using private inheritance to store // compare lets us take advantage of an empty base class optimization to avoid // extra space in the common case when Compare has no state. struct Impl : private value_compare, private heap_handle_accessor { Impl(const value_compare& value_comp, const heap_handle_accessor& heap_handle_access) : value_compare(value_comp), heap_handle_accessor(heap_handle_access) {} Impl() = default; Impl(Impl&&) = default; Impl(const Impl&) = default; Impl& operator=(Impl&& other) = default; Impl& operator=(const Impl& other) = default; const value_compare& get_value_compare() const { return *this; } value_compare& get_value_compare() { return *this; } const heap_handle_accessor& get_heap_handle_access() const { return *this; } heap_handle_accessor& get_heap_handle_access() { return *this; } // The items in the heap. UnderlyingType heap_; } impl_; }; // Helper class to endow an object with internal HeapHandle storage. By deriving // from this type you endow your class with self-owned storage for a HeapHandle. // This is a move-only type so that the handle follows the element across moves // and resizes of the underlying vector. class BASE_EXPORT InternalHeapHandleStorage { public: InternalHeapHandleStorage(); InternalHeapHandleStorage(const InternalHeapHandleStorage&) = delete; InternalHeapHandleStorage(InternalHeapHandleStorage&& other) noexcept; virtual ~InternalHeapHandleStorage(); InternalHeapHandleStorage& operator=(const InternalHeapHandleStorage&) = delete; InternalHeapHandleStorage& operator=( InternalHeapHandleStorage&& other) noexcept; // Allows external clients to get a pointer to the heap handle. This allows // them to remove the element from the heap regardless of its location. HeapHandle* handle() const { return handle_.get(); } // Implementation of IntrusiveHeap contract. Inlined to keep heap code as fast // as possible. void SetHeapHandle(HeapHandle handle) { DCHECK(handle.IsValid()); if (handle_) *handle_ = handle; } void ClearHeapHandle() { if (handle_) handle_->reset(); } HeapHandle GetHeapHandle() const { if (handle_) return *handle_; return HeapHandle::Invalid(); } // Utility functions. void swap(InternalHeapHandleStorage& other) noexcept; friend void swap(InternalHeapHandleStorage& lhs, InternalHeapHandleStorage& rhs) { lhs.swap(rhs); } private: std::unique_ptr<HeapHandle> handle_; }; // Spiritually akin to a std::pair<T, std::unique_ptr<HeapHandle>>. Can be used // to wrap arbitrary types and provide them with a HeapHandle, making them // appropriate for use in an IntrusiveHeap. This is a move-only type. template <typename T> class WithHeapHandle : public InternalHeapHandleStorage { public: WithHeapHandle() = default; // Allow implicit conversion of any type that T supports for ease of use with // InstrusiveHeap constructors/insert/emplace. template <typename U> WithHeapHandle(U value) : value_(std::move_if_noexcept(value)) {} WithHeapHandle(T&& value) noexcept : value_(std::move(value)) {} // Constructor that forwards all arguments along to |value_|. template <class... Args> explicit WithHeapHandle(Args&&... args); WithHeapHandle(const WithHeapHandle&) = delete; WithHeapHandle(WithHeapHandle&& other) noexcept = default; ~WithHeapHandle() override = default; WithHeapHandle& operator=(const WithHeapHandle&) = delete; WithHeapHandle& operator=(WithHeapHandle&& other) = default; T& value() { return value_; } const T& value() const { return value_; } // Utility functions. void swap(WithHeapHandle& other) noexcept; friend void swap(WithHeapHandle& lhs, WithHeapHandle& rhs) { lhs.swap(rhs); } // Comparison operators, for compatibility with ordered STL containers. friend bool operator==(const WithHeapHandle& lhs, const WithHeapHandle& rhs) { return lhs.value_ == rhs.value_; } friend bool operator!=(const WithHeapHandle& lhs, const WithHeapHandle& rhs) { return lhs.value_ != rhs.value_; } friend bool operator<=(const WithHeapHandle& lhs, const WithHeapHandle& rhs) { return lhs.value_ <= rhs.value_; } friend bool operator<(const WithHeapHandle& lhs, const WithHeapHandle& rhs) { return lhs.value_ < rhs.value_; } friend bool operator>=(const WithHeapHandle& lhs, const WithHeapHandle& rhs) { return lhs.value_ >= rhs.value_; } friend bool operator>(const WithHeapHandle& lhs, const WithHeapHandle& rhs) { return lhs.value_ > rhs.value_; } private: T value_; }; //////////////////////////////////////////////////////////////////////////////// // IMPLEMENTATION DETAILS namespace intrusive_heap { BASE_EXPORT inline size_t ParentIndex(size_t i) { DCHECK_NE(0u, i); return (i - 1) / 2; } BASE_EXPORT inline size_t LeftIndex(size_t i) { return 2 * i + 1; } template <typename HandleType> bool IsInvalid(const HandleType& handle) { return !handle || !handle->IsValid(); } BASE_EXPORT inline void CheckInvalidOrEqualTo(HeapHandle handle, size_t index) { if (handle.IsValid()) DCHECK_EQ(index, handle.index()); } } // namespace intrusive_heap //////////////////////////////////////////////////////////////////////////////// // IntrusiveHeap template <typename T, typename Compare, typename HeapHandleAccessor> IntrusiveHeap<T, Compare, HeapHandleAccessor>::IntrusiveHeap( const IntrusiveHeap& other) : impl_(other.impl_) { for (size_t i = 0; i < size(); ++i) { SetHeapHandle(i); } } template <typename T, typename Compare, typename HeapHandleAccessor> IntrusiveHeap<T, Compare, HeapHandleAccessor>::~IntrusiveHeap() { clear(); } template <typename T, typename Compare, typename HeapHandleAccessor> IntrusiveHeap<T, Compare, HeapHandleAccessor>& IntrusiveHeap<T, Compare, HeapHandleAccessor>::operator=( IntrusiveHeap&& other) noexcept { clear(); impl_ = std::move(other.impl_); return *this; } template <typename T, typename Compare, typename HeapHandleAccessor> IntrusiveHeap<T, Compare, HeapHandleAccessor>& IntrusiveHeap<T, Compare, HeapHandleAccessor>::operator=( const IntrusiveHeap& other) { clear(); impl_ = other.impl_; for (size_t i = 0; i < size(); ++i) { SetHeapHandle(i); } return *this; } template <typename T, typename Compare, typename HeapHandleAccessor> IntrusiveHeap<T, Compare, HeapHandleAccessor>& IntrusiveHeap<T, Compare, HeapHandleAccessor>::operator=( std::initializer_list<value_type> ilist) { clear(); insert(std::begin(ilist), std::end(ilist)); } template <typename T, typename Compare, typename HeapHandleAccessor> void IntrusiveHeap<T, Compare, HeapHandleAccessor>::clear() { // Make all of the handles invalid before cleaning up the heap. for (size_type i = 0; i < size(); ++i) { ClearHeapHandle(i); } // Clear the heap. impl_.heap_.clear(); } template <typename T, typename Compare, typename HeapHandleAccessor> template <class InputIterator> void IntrusiveHeap<T, Compare, HeapHandleAccessor>::insert(InputIterator first, InputIterator last) { for (auto it = first; it != last; ++it) { insert(value_type(*it)); } } template <typename T, typename Compare, typename HeapHandleAccessor> template <typename... Args> typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::const_iterator IntrusiveHeap<T, Compare, HeapHandleAccessor>::emplace(Args&&... args) { value_type value(std::forward<Args>(args)...); return InsertImpl(std::move_if_noexcept(value)); } template <typename T, typename Compare, typename HeapHandleAccessor> typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::value_type IntrusiveHeap<T, Compare, HeapHandleAccessor>::take(size_type pos) { // Make a hole by taking the element out of the heap. MakeHole(pos); value_type val = std::move(impl_.heap_[pos]); // If the element being taken is already the last element then the heap // doesn't need to be repaired. if (pos != GetLastIndex()) { MakeHole(GetLastIndex()); // Move the hole down the heap, filling it with the current leaf at the // very end of the heap. MoveHoleDownAndFill<WithLeafElement>( pos, std::move(impl_.heap_[GetLastIndex()])); } impl_.heap_.pop_back(); return val; } // This is effectively identical to "take", but it avoids an unnecessary move. template <typename T, typename Compare, typename HeapHandleAccessor> void IntrusiveHeap<T, Compare, HeapHandleAccessor>::erase(size_type pos) { DCHECK_LT(pos, size()); // Make a hole by taking the element out of the heap. MakeHole(pos); // If the element being erased is already the last element then the heap // doesn't need to be repaired. if (pos != GetLastIndex()) { MakeHole(GetLastIndex()); // Move the hole down the heap, filling it with the current leaf at the // very end of the heap. MoveHoleDownAndFill<WithLeafElement>( pos, std::move_if_noexcept(impl_.heap_[GetLastIndex()])); } impl_.heap_.pop_back(); } template <typename T, typename Compare, typename HeapHandleAccessor> typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::const_iterator IntrusiveHeap<T, Compare, HeapHandleAccessor>::Update(size_type pos) { DCHECK_LT(pos, size()); MakeHole(pos); // Determine if we're >= parent, in which case we may need to go up. bool child_greater_eq_parent = false; size_type i = 0; if (pos > 0) { i = intrusive_heap::ParentIndex(pos); child_greater_eq_parent = !Less(pos, i); } if (child_greater_eq_parent) { i = MoveHoleUpAndFill(pos, std::move_if_noexcept(impl_.heap_[pos])); } else { i = MoveHoleDownAndFill<WithElement>( pos, std::move_if_noexcept(impl_.heap_[pos])); } return cbegin() + i; } template <typename T, typename Compare, typename HeapHandleAccessor> void IntrusiveHeap<T, Compare, HeapHandleAccessor>::swap( IntrusiveHeap& other) noexcept { std::swap(impl_.get_value_compare(), other.impl_.get_value_compare()); std::swap(impl_.get_heap_handle_access(), other.impl_.get_heap_handle_access()); std::swap(impl_.heap_, other.impl_.heap_); } template <typename T, typename Compare, typename HeapHandleAccessor> typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::size_type IntrusiveHeap<T, Compare, HeapHandleAccessor>::ToIndex(const_iterator pos) { DCHECK(cbegin() <= pos); DCHECK(pos <= cend()); if (pos == cend()) return HeapHandle::kInvalidIndex; return pos - cbegin(); } template <typename T, typename Compare, typename HeapHandleAccessor> typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::size_type IntrusiveHeap<T, Compare, HeapHandleAccessor>::ToIndex( const_reverse_iterator pos) { DCHECK(crbegin() <= pos); DCHECK(pos <= crend()); if (pos == crend()) return HeapHandle::kInvalidIndex; return (pos.base() - cbegin()) - 1; } template <typename T, typename Compare, typename HeapHandleAccessor> void IntrusiveHeap<T, Compare, HeapHandleAccessor>::SetHeapHandle(size_type i) { impl_.get_heap_handle_access().SetHeapHandle(&impl_.heap_[i], HeapHandle(i)); intrusive_heap::CheckInvalidOrEqualTo(GetHeapHandle(i), i); } template <typename T, typename Compare, typename HeapHandleAccessor> void IntrusiveHeap<T, Compare, HeapHandleAccessor>::ClearHeapHandle( size_type i) { impl_.get_heap_handle_access().ClearHeapHandle(&impl_.heap_[i]); DCHECK(!GetHeapHandle(i).IsValid()); } template <typename T, typename Compare, typename HeapHandleAccessor> HeapHandle IntrusiveHeap<T, Compare, HeapHandleAccessor>::GetHeapHandle( size_type i) { return impl_.get_heap_handle_access().GetHeapHandle(&impl_.heap_[i]); } template <typename T, typename Compare, typename HeapHandleAccessor> bool IntrusiveHeap<T, Compare, HeapHandleAccessor>::Less(size_type i, size_type j) { DCHECK_LT(i, size()); DCHECK_LT(j, size()); return impl_.get_value_compare()(impl_.heap_[i], impl_.heap_[j]); } template <typename T, typename Compare, typename HeapHandleAccessor> bool IntrusiveHeap<T, Compare, HeapHandleAccessor>::Less(const T& element, size_type i) { DCHECK_LT(i, size()); return impl_.get_value_compare()(element, impl_.heap_[i]); } template <typename T, typename Compare, typename HeapHandleAccessor> bool IntrusiveHeap<T, Compare, HeapHandleAccessor>::Less(size_type i, const T& element) { DCHECK_LT(i, size()); return impl_.get_value_compare()(impl_.heap_[i], element); } template <typename T, typename Compare, typename HeapHandleAccessor> void IntrusiveHeap<T, Compare, HeapHandleAccessor>::MakeHole(size_type pos) { DCHECK_LT(pos, size()); ClearHeapHandle(pos); } template <typename T, typename Compare, typename HeapHandleAccessor> template <typename U> void IntrusiveHeap<T, Compare, HeapHandleAccessor>::FillHole(size_type hole_pos, U element) { // The hole that we're filling may not yet exist. This can occur when // inserting a new element into the heap. DCHECK_LE(hole_pos, size()); if (hole_pos == size()) { impl_.heap_.push_back(std::move_if_noexcept(element)); } else { impl_.heap_[hole_pos] = std::move_if_noexcept(element); } SetHeapHandle(hole_pos); } template <typename T, typename Compare, typename HeapHandleAccessor> void IntrusiveHeap<T, Compare, HeapHandleAccessor>::MoveHole( size_type new_hole_pos, size_type old_hole_pos) { // The old hole position may be one past the end. This occurs when a new // element is being added. DCHECK_NE(new_hole_pos, old_hole_pos); DCHECK_LT(new_hole_pos, size()); DCHECK_LE(old_hole_pos, size()); if (old_hole_pos == size()) { impl_.heap_.push_back(std::move_if_noexcept(impl_.heap_[new_hole_pos])); } else { impl_.heap_[old_hole_pos] = std::move_if_noexcept(impl_.heap_[new_hole_pos]); } SetHeapHandle(old_hole_pos); } template <typename T, typename Compare, typename HeapHandleAccessor> template <typename U> typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::size_type IntrusiveHeap<T, Compare, HeapHandleAccessor>::MoveHoleUpAndFill( size_type hole_pos, U element) { // Moving 1 spot beyond the end is fine. This happens when we insert a new // element. DCHECK_LE(hole_pos, size()); // Stop when the element is as far up as it can go. while (hole_pos != 0) { // If our parent is >= to us, we can stop. size_type parent = intrusive_heap::ParentIndex(hole_pos); if (!Less(parent, element)) break; MoveHole(parent, hole_pos); hole_pos = parent; } FillHole(hole_pos, std::move_if_noexcept(element)); return hole_pos; } template <typename T, typename Compare, typename HeapHandleAccessor> template <typename FillElementType, typename U> typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::size_type IntrusiveHeap<T, Compare, HeapHandleAccessor>::MoveHoleDownAndFill( size_type hole_pos, U element) { DCHECK_LT(hole_pos, size()); // If we're filling with a leaf, then that leaf element is about to be erased. // We pretend that the space doesn't exist in the heap. const size_type n = size() - (FillElementType::kIsLeafElement ? 1 : 0); DCHECK_LT(hole_pos, n); DCHECK(!GetHeapHandle(hole_pos).IsValid()); while (true) { // If this spot has no children, then we've gone down as far as we can go. size_type left = intrusive_heap::LeftIndex(hole_pos); if (left >= n) break; size_type right = left + 1; // Get the larger of the potentially two child nodes. size_type largest = left; if (right < n && Less(left, right)) largest = right; // If we're not deterministically moving the element all the way down to // become a leaf, then stop when it is >= the largest of the children. if (!FillElementType::kIsLeafElement && !Less(element, largest)) break; MoveHole(largest, hole_pos); hole_pos = largest; } if (FillElementType::kIsLeafElement) { // If we're filling with a leaf node we may need to bubble the leaf back up // the tree a bit to repair the heap. hole_pos = MoveHoleUpAndFill(hole_pos, std::move_if_noexcept(element)); } else { FillHole(hole_pos, std::move_if_noexcept(element)); } return hole_pos; } template <typename T, typename Compare, typename HeapHandleAccessor> template <typename U> typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::const_iterator IntrusiveHeap<T, Compare, HeapHandleAccessor>::InsertImpl(U element) { // MoveHoleUpAndFill can tolerate the initial hole being in a slot that // doesn't yet exist. It will be created by MoveHole by copy/move, thus // removing the need for a default constructor. size_type i = MoveHoleUpAndFill(size(), std::move_if_noexcept(element)); return cbegin() + static_cast<difference_type>(i); } template <typename T, typename Compare, typename HeapHandleAccessor> template <typename U> typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::const_iterator IntrusiveHeap<T, Compare, HeapHandleAccessor>::ReplaceImpl(size_type pos, U element) { // If we're greater than our parent we need to go up, otherwise we may need // to go down. MakeHole(pos); size_type i = 0; if (!Less(element, pos)) { i = MoveHoleUpAndFill(pos, std::move_if_noexcept(element)); } else { i = MoveHoleDownAndFill<WithElement>(pos, std::move_if_noexcept(element)); } return cbegin() + static_cast<difference_type>(i); } template <typename T, typename Compare, typename HeapHandleAccessor> template <typename U> typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::const_iterator IntrusiveHeap<T, Compare, HeapHandleAccessor>::ReplaceTopImpl(U element) { MakeHole(0u); size_type i = MoveHoleDownAndFill<WithElement>(0u, std::move_if_noexcept(element)); return cbegin() + static_cast<difference_type>(i); } //////////////////////////////////////////////////////////////////////////////// // WithHeapHandle template <typename T> template <class... Args> WithHeapHandle<T>::WithHeapHandle(Args&&... args) : value_(std::forward<Args>(args)...) {} template <typename T> void WithHeapHandle<T>::swap(WithHeapHandle& other) noexcept { InternalHeapHandleStorage::swap(other); std::swap(value_, other.value_); } } // namespace base #endif // BASE_CONTAINERS_INTRUSIVE_HEAP_H_
true
2f991e63de038b95e0f2c0d669d618ea337a068a
C++
sureshyhap/Schaums-Outlines-Programming-with-C-plus-plus
/Chapter 6/Problems/19/19.cpp
UTF-8
537
3.515625
4
[]
no_license
#include <iostream> void selection_sort(int a[], int size); int main(int argc, char* argv[]) { int a[] = {83, 823, 365, 8274, 05, 4, 84074, 679}; selection_sort(a, 8); for (int i = 0; i < 8; ++i) { std::cout << a[i] << " "; } return 0; } void selection_sort(int a[], int size) { for (int j = 0; j < size; ++j) { int i = 0, max = a[0], max_index = 0; for (; i < size - j; ++i) { if (a[i] > max) { max = a[i]; max_index = i; } } a[max_index] = a[--i]; a[i] = max; } }
true
46aef8eb43234b072fe99e931bda36274b8c99e0
C++
DrNefarious/kryptos
/dictionary_builder.cpp
UTF-8
325
2.875
3
[]
no_license
#include<iostream> #include<fstream> #include<string> using namespace std; int main(){ ifstream dictionary("words.txt"); ofstream output("words_4.txt"); string line; while(getline(dictionary,line)){ if(line.length() == 4){ output << line << endl; } } dictionary.close(); output.close(); return 0; }
true
bfd1a355bb4d8e847636f0b2d19e506f510f1193
C++
DGolgovsky/Courses
/CPP.OTUS/Design_Patterns/1.Creational_patterns/08.object_pool.cpp
UTF-8
1,375
3.5
4
[ "Unlicense" ]
permissive
// Объектный пул (Object pool) #include <exception> #include <iostream> #include <string> #include <vector> #include <array> class PgConnection {}; class PgConnectionPool { private: struct PgConnectionBlock { PgConnection* connection; bool busy; }; std::vector<PgConnectionBlock> m_pool; public: PgConnection* get() { for (size_t i = 0; i < m_pool.size(); ++i) { if (!m_pool[i].busy) { m_pool[i].busy = true; return m_pool[i].connection; } } auto block = PgConnectionBlock{new PgConnection, true}; m_pool.push_back(block); return block.connection; } void put(PgConnection* object) { for (size_t i = 0; i < m_pool.size(); ++i) { if (m_pool[i].connection == object) { m_pool[i].busy = false; break; } } } ~PgConnectionPool() { for (const auto &i : m_pool) { std::cout << i.connection << std::endl; delete i.connection; } } }; int main(int, char **) { PgConnectionPool pool; auto report_conn = pool.get(); pool.put(report_conn); auto admin_conn = pool.get(); auto user_conn = pool.get(); pool.put(user_conn); pool.put(admin_conn); return 0; }
true
9b5dc4b97d72847c49db0e77812e1f97c13a05f5
C++
AppliedAlpha/BOJ
/Submitted/2xxx/2745.cpp
UTF-8
406
2.578125
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int b, tmp, d = 1, sum = 0; string str; cin >> str >> b; for (int i=str.length()-1; i>=0; i--) { if (str[i] >= '0' && str[i] <= '9') tmp = str[i]-'0'; else tmp = str[i]-'A'+10; sum += tmp * d; d *= b; } cout << sum; }
true
67f4fe2d052f8ebced4288f4f635dae898fd90d1
C++
diegotf30/CS-Homeworks
/OOP/Robot/include/Camara.h
UTF-8
691
3.28125
3
[]
no_license
#ifndef CAMARA_H #define CAMARA_H #include <string> #include <iostream> #include <fstream> using namespace std; class Camara { public: ///Constructor Camara(string sQuality, string sType) { this->sQuality = sQuality; this->sType = sType; } ///Destructor virtual ~Camara() { } ///Getters string getCalidad() { return sQuality; } string getTipo() { return sType; } ///Methods friend ostream& operator << (ostream &out, const Camara &cCamara) { out << cCamara.sQuality << " " << cCamara.sType; return out; } protected: private: string sQuality; string sType; }; #endif // CAMARA_H
true
279df165e6b9d263210b42af81b39b570eac3585
C++
benitoab/2PA_TA_benitoab
/Antekeland/include/board.h
UTF-8
1,424
2.765625
3
[]
no_license
/** * @file main.cc * @brief Main file of the game. * @details This is the core file. It gathers all classes of the game to make it possible. * @author Javier Benito Abolafio <benitoab@esat-alumni.com> * @version alfa 1.0 * @date Ded-2020 * @copyright ESAT */ #ifndef __BOARD_H__ #define __BOARD_H__ 1 #include "tile.h" class Board{ public: //Constant of procedural generation static const unsigned char kBoardSize = 64; ///@var size of the procedural board const unsigned char kNState = 8; ///@var number of biomes of the board const float kCellconcentration = 0.55f; ///@var the conectration of all biomes //Methods /** *@brief init the layer 1 of the graphic board */ void initLayer1(); /** *@brief init the layer 2 of the graphic board */ void initLayer2(); /** *@brief udate the origin position of the map */ void update0Position(); /** *@brief reset the origin position of the map */ void reset0Position(); //void move0Position(SDL_Event* e); /** *@brief dra the map */ void drawMap(SDL_Renderer* renderer); //Atributes Tile map_[kBoardSize][kBoardSize]; ///@var arry of tiles of the map static int32_t x_origin_; ///@var pos x of the origin of the map static int32_t y_origin_; ///@var pos y of the origin of the map }; #endif // __BOARD_H__
true
f50076dca3d41d6f6b5d89d8132824641602a35b
C++
juliosueiras/Winter2015Class
/PROG20799/c_program/cint/cint-5.16.19-source/cint-5.16.19/reflex/inc/Reflex/Builder/DictSelection.h
UTF-8
9,793
2.796875
3
[ "MIT" ]
permissive
// @(#)root/reflex:$Name: $:$Id: DictSelection.h,v 1.6 2006/07/05 07:09:08 roiser Exp $ // Author: Stefan Roiser 2004 #ifndef ROOT_Reflex_DictSelection #define ROOT_Reflex_DictSelection #include "Reflex/Kernel.h" /** * @file DictSelection.h * @author scott snyder * @author Stefan Roiser (minor changes, mainly documentation) * @date Aug 2005 * @brief Definitions for selection classes to provide metadata * for SEAL dictionary generation. * * When generating dictionary information for a class, * one sometimes wants to specify additional information * beyond the class definition itself, for example, to specify * that certain members are to be treated as transient by the persistency * system. This can be done by associating a dictionary selection class * with the class for which dictionary information is being generated. * The contents of this selection class encode the additional information. * Below, we first discuss how to associate a selection class * with your class; then we list the current Set of information * which may appear inside the selection class. * * The simplest case is for the case of a non-template class @c C. * By default, the Name of the selection class is then * @c ROOT::Reflex::selection::C. If you have such a class, it will be found * automatically. If @c C is in a namespace, @c NS::C, then * the selection class should be in the same namespace: @c ROOT::Reflex::selection::NS::C. * Examples: * * @code * namespace N { * class C { ... }; * } * namespace ROOT { * namespace Reflex { * namespace selection { * namespace N { * class C { ... }; * } * } * } * } * @endcode * * If, however, we're dealing with a template class, @c C\<T>, then * things are trickier, since one needs to be sure that the * selection class gets properly instantiated. As before, the dictionary * generator will look for a class @c ROOT::Reflex::selection::C\<T> (with the same * template arguments as @c C). This will only succeed, however, * if the selection class has otherwise been used. Example: * * @code * * template <class T> * class C { ... }; * * namespace ROOT { * namespace Reflex { * namespace selection { * template <class T> * class C { ... }; * } * } * } * * struct foo { C<int> x; }; * * // Without this, the selection class won't be fully instantiated. * struct foo_selection { ROOT::Reflex::selection::C<int> x; } @endcode * * What one would really like is a way to ensure that the selection class * gets instantiated whenever the class its describing does. That does * not seem to be possible without modifying that class (at least not * without changes to gccxml). The following idiom seems to work: * * @code * * template <class T> class ROOT::Reflex::selection::C; // forward declaration * * template <class T> * class C * { * ... * typedef typename ROOT::Reflex::selection::C<T>::self DictSelection; * }; * * namespace ROOT { * namespace Reflex { * namespace selection { * template <class T> * class C * { * typedef DictSelection<C> self; * ... * }; * } * } * } * @endcode * * Note that if you instead use * * @code * * typedef ROOT::Reflex::selection::C<T> DictSelection; * @endcode * * then @c ROOT::Reflex::selection::C\<T> will not be fully instantiated. * * We turn now to declarations the may be present in the selection class. * Below, we'll call the class being described by the selection class @c C. * * @ROOT::Reflex::selection::AUTOSELECT * * This can be useful for automatically including classes which @c C depends upon. * * @code * template <class T> class ROOT::Reflex::selection::C; // forward declaration * * // class C<T> depends on std::vector<T>. * template <class T> * class C * { * public: * std::vector<T> fX; * typedef typename ROOT::Reflex::selection::C<T>::self DictSelection; * }; * * namespace ROOT { * namespace Reflex { * namespace selection { * template <class T> * class C * { * typedef DictSelection<C> self; * AUTOSELECT fX; * }; * } * } * } * * // The above declarations mark both C<T> and std::vector<T> * // as autoselect. This means that dictionary information for them * // will be emitted wherever it's needed --- no need to list them * // in selection.xml. * @endcode * * @ROOT::Reflex::selection::TRANSIENT * * This declaration marks the corresponding MemberAt in @c C with * the same Name as transient. This allows the transient flag * to be listed once in the class header, rather than having * to list it in selection.xml (in possibly many places if @c C * is a template class). Example: * * @code * * class C * { * public: * int fX; * int fY; // This shouldn't be saved. * }; * * namespace ROOT { * namespace Reflex { * namespace selection { * class C * { * TRANSIENT fY; // Don't save C::fY. * }; * } * } * } * @endcode * * @ROOT::Reflex::selection::TEMPLATE_DEFAULTS<T1, T2, ...> * * (The Name of the MemberAt used does not matter.) * Declares default template arguments for @c C. Up to 15 arguments * may be listed. If a given position cannot be defaulted, then * use @c ROOT::Reflex::selection::NODEFAULT. * * If this declaration has been made, then any defaulted template * arguments will be suppressed in the external representations * of the class Name (such as seen by the persistency service). * This can be used to add a new template argument to a class * without breaking backwards compatibility. * Example: * * @code * template <class T, class U> class ROOT::Reflex::selection::C; // forward declaration * * template <class T, class U=int> * class C * { * public: * ... * typedef typename ROOT::Reflex::selection::C<T>::self DictSelection; * }; * * namespace ROOT { * namespace Reflex { * namespace selection { * template <class T, class U> * class C * { * typedef DictSelection<C> self; * * TEMPLATE_DEFAULTS<NODEFAULT, int> dummy; * }; * } * } * } * // With the above, then C<T,int> will be represented externally * // as just `C<T>'. * @endcode */ namespace ROOT { namespace Reflex { namespace Selection { /* * @brief turn of autoselection of the class * * By default classes which appear in the Selection namespace will be selected * for dictionary generation. If a class has a member of type NO_SELF_AUTOSELECT * no dictionary information for this class will be generated. */ class RFLX_API NO_SELF_AUTOSELECT {}; /* * @brief Mark a MemberAt as being transient. * * This should be used in a selection class. This marks the corresponding * MemberAt as being transient. See the header comments for examples. */ class RFLX_API TRANSIENT {}; /* * @brief Mark the At of a (data)MemberAt as autoselected. * * This should be used in a selection class. The Name of the MemberAt shall be the same * as the MemberAt in the original class and will be automatically * selected to have dictionary information generated wherever it's * needed. See the header comments for examples. */ class RFLX_API AUTOSELECT{}; /* * @brief Placeholder for @c TEMPLATE_DEFAULTS. * * This is used in the @c TEMPLATE_DEFAULTS template argument list * for positions where template arguments cannot be defaulted. */ struct RFLX_API NODEFAULT {}; /* * @brief Declare template argument defaults. * * This should be used in a selection class. The template arguments * of this class give the template argument defaults for the class * being described. If the class is used with defaulted template * arguments, then these arguments will be omitted from external * representations. See the header comments for examples. */ template <class T1 = NODEFAULT, class T2 = NODEFAULT, class T3 = NODEFAULT, class T4 = NODEFAULT, class T5 = NODEFAULT, class T6 = NODEFAULT, class T7 = NODEFAULT, class T8 = NODEFAULT, class T9 = NODEFAULT, class T10 = NODEFAULT, class T11 = NODEFAULT, class T12 = NODEFAULT, class T13 = NODEFAULT, class T14 = NODEFAULT, class T15 = NODEFAULT> struct TEMPLATE_DEFAULTS { typedef NODEFAULT nodefault; typedef T1 t1; typedef T2 t2; typedef T3 t3; typedef T4 t4; typedef T5 t5; typedef T6 t6; typedef T7 t7; typedef T8 t8; typedef T9 t9; typedef T10 t10; typedef T11 t11; typedef T12 t12; typedef T13 t13; typedef T14 t14; typedef T15 t15; }; } // namespace Selection } // namespace Reflex } // namespace ROOT #endif // ROOT_Reflex_DictSelection
true
813c97dca1ba03c9fcc404c3451c8c4893e0da8e
C++
LuisAlbertoVasquezVargas/CP
/otherRepos/luis/HackerRank/ProjectEuler/euler065.cpp
UTF-8
1,085
2.703125
3
[]
no_license
import java.math.BigInteger; import java.util.Scanner; public class Main { public static BigInteger ONE = BigInteger.ONE; public static BigInteger ZERO = BigInteger.ZERO; public static BigInteger TWO = BigInteger.valueOf(2); public static int N = 30000; public static void main(String[] args) { Scanner cin = new Scanner( System.in ); int n = cin.nextInt(); BigInteger F[] = new BigInteger[ N + 5 ]; F[ 0 ] = ZERO; F[ 1 ] = ONE; for( int i = 0 ; i < n ; ++i ){ int cur = ( (i == 0) ? 2 : ( (i % 3 == 2) ? ( 2 * (i/3 + 1) ) : 1 ) ); //System.out.print(cur + " "); F[ i + 2 ] = (F[ i + 1 ].multiply( BigInteger.valueOf( cur ) )).add( F[ i ] ); //System.out.println( F[ i + 2 ] ); } String s = F[ n + 1 ].toString(); int ans = 0; for( int i = 0 ; i < s.length() ; ++i ){ char c = s.charAt( i ); ans += c - '0'; } System.out.println( ans ); } }
true
5897c074631fff4bd558b921709970f1ba56cd4e
C++
meatrick/cosc326
/etude03/etude03.cpp
UTF-8
6,048
3.375
3
[]
no_license
#include <iostream> #include <cstdlib> #include <string> #include <istream> #include <sstream> #include <cstring> #include <vector> #include <algorithm> // for reversing vectors #include <cmath> using namespace std; string increment_bitsting(string bitstring); struct Scenario { vector<int> numbers; int target_value; string order_mode; string output; // TODO: change to vector<char> Scenario() { // init } // method: given a scenario object and a solution in the form of a bitstring, create the output for the solution // if the solution is -1, do the "impossible" output // else ... void set_solution(vector<char> solution_operators) { if (solution_operators[0] == '0') { // impossible this->output = order_mode + " " + to_string(target_value) + " impossible"; return; } if (solution_operators[0] == '1') { // single operand, correct this->output = order_mode + " " + to_string(target_value) + " " + to_string(this->numbers[0]); return; } this->output = order_mode + " " + to_string(target_value) + " "; for (int i = 0; i < this->numbers.size(); i++) { if (i == this->numbers.size() - 1) { this->output += to_string(this->numbers[i]); } else { this->output += to_string(this->numbers[i]) + " "; char op = solution_operators[i]; this->output += op; this->output += ' '; } } } }; vector<char> DFS(vector<int> input_numbers, unsigned int level, int partial_sum, vector<char> operators, int target_value) { // trim if (partial_sum > target_value) { vector<char> empty_vec; empty_vec.clear(); return empty_vec; } // base case: if start_node is a leaf if (level == input_numbers.size() - 1) { if (partial_sum == target_value) { return operators; } } else { level++; vector<char> solution; vector<char> operators_left = operators, operators_right = operators; // left child int left_partial_sum = partial_sum + input_numbers[level]; operators_left.push_back('+'); solution = DFS(input_numbers, level, left_partial_sum, operators_left, target_value); if (!solution.empty()) { return solution; } // right child int right_partial_sum = partial_sum * input_numbers[level]; operators_right.push_back('*'); solution = DFS(input_numbers, level, right_partial_sum, operators_right, target_value); if (!solution.empty()) { return solution; } } // signal that the DFS did not find a valid solution here vector<char> empty_vec; empty_vec.clear(); return empty_vec; } vector<char> DFSN(vector<int> input_numbers, unsigned int level, pair<int, int> operands, vector<char> operators, int target_value) { // base case: if start_node is a leaf: only additions remain, sum it all up if (level == input_numbers.size() - 1) { int sum = operands.first + operands.second; if (sum == target_value) { return operators; } } else { // operations to prepare for the next level of the tree level++; vector<char> solution; vector<char> operators_left = operators, operators_right = operators; pair<int,int> operands_left = operands, operands_right = operands; operands_left = make_pair(operands_left.first + operands_left.second, input_numbers[level]); operators_left.push_back('+'); solution = DFSN(input_numbers, level, operands_left, operators_left, target_value); if (!solution.empty()) { return solution; } operands_right = make_pair(operands_right.first, operands_right.second * input_numbers[level]); operators_right.push_back('*'); solution = DFSN(input_numbers, level, operands_right, operators_right, target_value); if (!solution.empty()) { return solution; } } // signal that the DFS did not find a valid solution here vector<char> empty_vec; empty_vec.clear(); return empty_vec; } // find solution for type L vector<char> find_solution(vector<int> input_numbers, int target_value) { // special case: 1 input operand if (input_numbers.size() == 1) { vector<char> operators_solution; if (input_numbers[0] == target_value) { operators_solution.push_back('1'); } else { operators_solution.push_back('0'); } return operators_solution; } vector<char> operators; vector<char> operators_solution = DFS(input_numbers, 0, input_numbers[0], operators, target_value); // no solution if (operators_solution.empty()) { operators_solution.push_back('0'); } return operators_solution; } vector<char> find_solutionN(vector<int> input_numbers, int target_value) { // special case: 1 input operand if (input_numbers.size() == 1) { vector<char> operators_solution; if (input_numbers[0] == target_value) { operators_solution.push_back('1'); } else { operators_solution.push_back('0'); } return operators_solution; } vector<char> operators; pair<int, int> operands(0, input_numbers[0]); vector<char> operators_solution = DFSN(input_numbers, 0, operands, operators, target_value); if (operators_solution.empty()) { operators_solution.push_back('0'); } return operators_solution; } int main() { // parse input and create Scenarios string line; Scenario* s = NULL; int line_number = 0; stringstream ss; while (getline(cin, line)) { line_number++; ss.str(line); // input from first line if (line_number % 2 == 1) { s = new Scenario(); int number; while (ss >> number) { s->numbers.push_back(number); } } else { // input from second line int target_value; char order_mode; ss >> target_value; ss >> order_mode; s->target_value = target_value; s->order_mode = order_mode; vector<int> input_numbers = s->numbers; // all processing and output if (s->order_mode == "L") { vector<char> solution_operators = find_solution(input_numbers, s->target_value); s->set_solution(solution_operators); } else if (s->order_mode == "N") { vector<char> solution_operators = find_solutionN(input_numbers, s->target_value); s->set_solution(solution_operators); } cout << s->output << endl; } ss.clear(); } return 0; }
true
5272629dfb035d03209afacd79ac786c79b8ba33
C++
AbdullahJasim/SimpleGames
/GenericPlayer.h
UTF-8
391
2.765625
3
[]
no_license
#pragma once #ifndef GENERIC_PLAYER #define GENERIC_PLAYER #include "Hand.h" class GenericPlayer : public Hand { friend ostream& operator<<(ostream& os, const GenericPlayer& aGenericPlayer); public: GenericPlayer(const string& name = ""); virtual ~GenericPlayer(); virtual bool IsHitting() const = 0; bool IsBusted() const; void Bust() const; protected: string m_Name; }; #endif
true
a16e1cd78fc2a2b235def23143c6dcf6f8d8e02a
C++
kstenerud/patch-a-bobble
/src/Bitbuff.cpp
UTF-8
3,725
2.59375
3
[]
no_license
#include <windows.h> #include "bitbuff.h" int get_bit(char* data, long bit_offset) { return ((data[(int)(bit_offset - (bit_offset%8)) / 8] & (1 << (int)(7-(bit_offset%8)))) != 0); } void set_bit(char* data, long bit_offset, int value) { if(value) data[(int)(bit_offset - (bit_offset%8)) / 8] |= (char)((1 << (int)(7-(bit_offset%8))) & 0xff); else data[(int)(bit_offset - (bit_offset%8)) / 8] &= (char)((~(1 << (int)(7-(bit_offset%8)))) & 0xff); } BOOL bitcode_value(char* buff, long bit_offset, int val, int granularity) { int i; long offset = bit_offset; if(val < 0 || val >= (1 << granularity)) return FALSE; for(i=granularity-1;i>=0;i--) set_bit(buff, offset++, val & (1 << i)); return TRUE; } BOOL BitBuff::set_granularity(int gran) { if(gran < 1 || gran > 8) return FALSE; m_granularity = gran; return TRUE; } BOOL BitBuff::put(long bit_offset, int value, int granularity) { if(bit_offset < 0 || bit_offset >= (int)m_len*8) return FALSE; if(granularity == 0) granularity = m_granularity; if(granularity < 1 || granularity > 8) return FALSE; return bitcode_value(m_data, bit_offset, value, granularity); } int BitBuff::get(long bit_offset, int granularity) { long offset = bit_offset; int val = 0; if(bit_offset < 0 || bit_offset >= (int)m_len*8) return -1; if(granularity == 0) granularity = m_granularity; if(granularity < 1 || granularity > 8) return -1; switch(granularity) { case 8: val += (::get_bit(m_data, offset++) ? 0x80 : 0); case 7: val += (::get_bit(m_data, offset++) ? 0x40 : 0); case 6: val += (::get_bit(m_data, offset++) ? 0x20 : 0); case 5: val += (::get_bit(m_data, offset++) ? 0x10 : 0); case 4: val += (::get_bit(m_data, offset++) ? 0x08 : 0); case 3: val += (::get_bit(m_data, offset++) ? 0x04 : 0); case 2: val += (::get_bit(m_data, offset++) ? 0x02 : 0); default: val += (::get_bit(m_data, offset++) ? 0x01 : 0); } return val & 0xff; } BOOL BitBuff::load(char* filename) { HANDLE fd; DWORD len; if(filename != NULL) { if(m_filename != NULL) delete [] m_filename; m_filename = new char[strlen(filename)+1]; strcpy(m_filename, filename); if( (fd=CreateFile(m_filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE) { if( (m_len=GetFileSize(fd, NULL)) != 0xffffffff) { if(m_data != NULL) delete [] m_data; m_data = new char[m_len]; if(ReadFile(fd, m_data, m_len, &len, NULL)) { CloseHandle(fd); return TRUE; } delete [] m_data; m_data = NULL; } } delete [] m_filename; m_filename = NULL; } CloseHandle(fd); return FALSE; } BOOL BitBuff::save(char* filename) { HANDLE fd; DWORD len; if(filename != NULL) { if(m_filename != NULL) delete [] m_filename; m_filename = new char[strlen(filename)+1]; strcpy(m_filename, filename); } if(m_filename != NULL && m_data != NULL) { if( (fd=CreateFile(m_filename, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL)) != INVALID_HANDLE_VALUE) { if(WriteFile(fd, m_data, m_len, &len, NULL)) { CloseHandle(fd); return TRUE; } } } CloseHandle(fd); return FALSE; }
true
d74e3dc037f3a4bdf1c3927d6c4b608b80c108b2
C++
EBailey67/DiceParser
/src/diceparser.h
UTF-8
3,350
3.1875
3
[]
no_license
#pragma once #include <map> #include <regex> #include <string> #include <sstream> #include "conditional.h" #include "error.h" #include "expression.h" #include "operand.h" #include "token.h" #include "value.h" namespace DungeonZ { class DiceParser { public: /// Error code results and strings Error ErrorCode; std::stringstream Output; double FinalResult; std::map<Error, std::string> ErrorStrings = { { Error::None, "None" }, { Error::MultDivIncorrect, "'*' or '\\' is used incorrectly!" }, { Error::OperatorPairing, "Operators have been paired incorrectly!" }, { Error::NoRValue, "An operator has no rValue!" }, { Error::IncorrectVariable, "A variable is being used incorrectly!" }, { Error::InvalidCharacter, "Invalid Character!" }, { Error::MissingVariable, "The expression contains an invalid variable!" }, { Error::Nesting, "Nesting Error" }, { Error::Expression, "Invalid Expression" }, { Error::Operation, "Invalid Operation" }, { Error::Conditional, "Invalid Conditional" }, }; // Finds the next token in the input stream starting from index // Returns the token found or Token::None if nothing was found Token NextToken(std::string input, size_t index); // Produces a random number between 1..sides // sides : The highest number to produce from the die</param> // returns : 1..sides int RollDice(int sides); // Produces a random number between 0..sides-1 // <param name="sides">The number of faces on the dice</param> // <returns>0..sides-1</returns> int RollZeroDice(int sides); // Rolls a number of dice with the specified sides. // <param name="number">number of dice to roll</param> // <param name="sides">highest number to produce from a single die</param> Value RollMultipleDice(int count, int sides, bool zeroBased = false); // Rolls a Fudge die (-1, 0, 1) // <param name="number">Number of dice to roll</param> // <returns>The sum of the die rolls</returns> Value RollFudge(int count); // Parses dice algebraic notation // <param name="diceNotation">string with the notation</param> // <returns>null or sum value</returns> std::string Parse(std::string diceNotation); protected: // Solves the expressions list in the proper order of operations std::vector<Expression> SolvePriority(std::vector<Expression> expressions); // Solves all addition and subtraction statements // <param name="expressions"></param> // <returns></returns> std::vector<Expression> SolveAdd(std::vector<Expression> expressions); // Solves all multiplication and division statements // <param name="expressions"></param> std::vector<Expression> SolveMult(std::vector<Expression> expressions); // Solves Dice statements std::vector<Expression> SolveDice(std::vector<Expression> expressions); // Solves distributed multipliers (loops) std::vector<Expression> SolveDistributedMultiply(std::vector<Expression> expressions); // Solves conditionals std::vector<Expression> SolveConditional(std::vector<Expression> expressions); Value DoOperation(Expression leftExp, Expression rightExp, Operand operand, Conditional conditional); private: // Produce a random number where n is low <= n <= high int RandomRange(int low, int high); std::string GetConditionalFriendlyName(Conditional conditional); }; }
true
ca67b88fa09378e3a1f11f4c4581f58a88d7d3be
C++
sek3951/10-team
/common.h
UTF-8
1,601
2.65625
3
[]
no_license
#pragma once #include <iostream> #include<vector> #include<algorithm> using namespace std; //constant #define DINO_BOTTOM_Y 12 #define TREE_BOTTOM_Y 20 #define TREE_BOTTOM_X 45 #define Bird_BOTTOM_Y 10 #define BIRD_BOTTOM_X 45 #define GRAVITY 3 #define CROWD_TIME 10 #define LEADER_BOARD_MAX 5 //function void SetConsoleView(); void GoToXY(int x, int y); int GetKeyDown(); void DrawDino(int dino_y); void DrawTree(int tree_x); void DrawDinoCrowd(); void DrawGameOver(const int score); bool IsTreeCollision(const int tree_x, const int dino_y); void DrawBird(int bird_x); bool IsBirdCollision(const int bird_x, const int dino_y, const int is_crowd); bool IsCoinCollision(const int coin_x, const int dino_y); bool IsLifeCollision(const int life_x, const int dino_y); bool Cmp(int a, int b); //class class Status { private: bool is_jumping; bool is_bottom; int is_crowd; public: bool GetIsJumping() { return is_jumping; } bool GetIsBottom() { return is_bottom; } int GetIsCrowd() { return is_crowd; } void StatusInit(); void SetIsJumping(bool); void SetIsBottom(bool); void SetIsCrowd(int); }; class Where { private: int dino_y; int tree_x; int bird_x; public: int GetDinoY() { return dino_y; } int GetTreeX() { return tree_x; } int GetBirdX() { return bird_x; } void WhereInit(); void SetDinoY(int); void SetTreeX(int); void SetBirdX(int); void DinoYPlus(int); void DinoYMinus(int); void BirdXMinus(int); void TreeXMinus(int); }; class LeaderBoard { private: vector<int>leader_board; public: void LeaderBoardPush(int); void ShowLeaderBoard(); void LeaderBoardSort(); };
true
a02380304404dfc5ba56370e0d0a89624db4e7be
C++
Hank-learner/Data-Structures-with-Algorithms
/samples/forestBT.cpp
UTF-8
2,187
3.71875
4
[]
no_license
#include <iostream> #include <sstream> using namespace std; #define basespace 10 struct Node { char key; int is_rchild; struct Node *left, *right; }; struct Node* newnode(char key) { struct Node* temp = new Node; temp->key = key; temp->left = NULL; temp->right = NULL; return temp; } void create(Node** parent, int child) { char key; Node* curr; cin >> key; if (key == '/') { return; } if (*parent != NULL) { curr = newnode(key); if (child == 0) { curr->right = *parent; (*(*parent)).left = curr; } else { if ((*(*parent)).right != NULL) { curr->right = (*(*parent)).right; } (*(*parent)).right = curr; (*(*parent)).is_rchild = 1; } } else { curr = newnode(key); *parent = curr; } cout << "child of " << curr->key << ": "; create(&curr, 0); cout << "sibling of " << curr->key << ": "; create(&curr, 1); } void printtree(Node* root, int space) { if (root == NULL) return; space += basespace; printtree(root->right, space); cout << endl; for (int i = basespace; i < space; i++) cout << " "; cout << root->key; printtree(root->left, space); } void inorder(Node* root) { if (root == NULL) return; inorder(root->left); cout << root->key << " "; inorder(root->right); } void preorder(struct Node* root) { Node* curr = root; while (curr != NULL) { printf("%c ", curr->key); if (curr->left != NULL) { curr = curr->left; } else if (curr->is_rchild == 1) { curr = curr->right; } else { while (curr->right != NULL && curr->is_rchild == 0) curr = curr->right; if (curr->right == NULL) { break; } else { curr = curr->right; } } } } int main() { struct Node* root = NULL; create(&root, 0); //inorder(root); cout << "The preorder of the binary tree : "; preorder(root); cout << endl; return 0; }
true
0a26636fa1cb433a52263b399a0823f374406a83
C++
donovan680/Paint-for-kids
/Actions/AddTriAction.cpp
UTF-8
2,492
2.625
3
[]
no_license
#include "AddTriAction.h" #include "..\Figures\CTriangle.h" #include "..\ApplicationManager.h" #include "..\GUI\input.h" #include "..\GUI\Output.h" AddTriAction::AddTriAction(ApplicationManager * pApp):Action(pApp) {} void AddTriAction::ReadActionParameters() { //Get a Pointer to the Input / Output Interfaces Output* pOut = pManager->GetOutput(); Input* pIn = pManager->GetInput(); pOut->PrintMessage("New Triangle: Click at first corner"); if(pManager->getSound()) PlaySound(TEXT("Sounds\\Triangle.wav"),NULL,SND_FILENAME); //Read 1st corner and store in point P1 pIn->GetPointClicked(P1.x, P1.y); if (P1.y < UI.ToolBarHeight+5 || P1.y > UI.height - UI.StatusBarHeight) { do { pOut->PrintMessage("You can not draw here please click on another point"); pIn->GetPointClicked(P1.x, P1.y); if (P1.y > UI.ToolBarHeight+5 && P1.y < UI.height - UI.StatusBarHeight) break; } while (1); } pOut->PrintMessage("New triangle: Click at second corner"); //Read 2nd corner and store in point P2 pIn->GetPointClicked(P2.x, P2.y); if (P2.y < UI.ToolBarHeight+5 || P2.y > UI.height - UI.StatusBarHeight) { do { pOut->PrintMessage("You can not draw here please click on another point"); pIn->GetPointClicked(P2.x, P2.y); if (P2.y > UI.ToolBarHeight+5 && P2.y < UI.height - UI.StatusBarHeight) break; } while (1); } pOut->PrintMessage("New triangle: Click at third corner"); //Read 3nd corner and store in point P3 pIn->GetPointClicked(P3.x, P3.y); if (P3.y < UI.ToolBarHeight+5 || P3.y > UI.height - UI.StatusBarHeight) { do { pOut->PrintMessage("You can not draw here please click on another point"); pIn->GetPointClicked(P3.x, P3.y); if (P3.y > UI.ToolBarHeight+5 && P3.y < UI.height - UI.StatusBarHeight) break; } while (1); } TriGfxInfo.isFilled =pManager->isFilled(); //default is not filled //get drawing, filling colors and pen width from the interface TriGfxInfo.DrawClr = pManager->GetColor2(); TriGfxInfo.FillClr = pManager->GetColor(); pOut->ClearStatusBar(); } //Execute the action void AddTriAction::Execute() { //This action needs to read some parameters first ReadActionParameters(); //Create a triangle with the parameters read from the user CTriangle *R=new CTriangle(P1, P2, P3, TriGfxInfo); //Add the triangle to the list of figures pManager->AddFigure(R); }
true
6db5837fdb74231d68b72a9344ac8dfa8559d06e
C++
kyshel/lab
/cpp/sword_03.cpp
UTF-8
587
3.609375
4
[]
no_license
#include <iostream> using namespace std; bool Find(int* matrix, int rows, int cols, int number){ bool found = false; if (matrix != NULL && rows > 0 && cols > 0){ int row = 0; int col = cols - 1; while(row < rows && col >= 0){ if(matrix[row * cols + col] == number){ found = true; break; }else if(matrix[row * cols + col] > number){ --col; }else{ ++row; } } } return found; } int main(){ int rows=2; int cols=2; int ma[4]={1,2,3,4}; int number = 4; cout << Find(ma,rows,cols,number) << endl; return 0; }
true
e84b74ada555ddeebc8d06bf24f8f79974b9b92e
C++
masoudjalalir/Snake_Game
/SNAKE.cpp
UTF-8
9,557
2.734375
3
[]
no_license
using namespace std; #include <conio.h> #include <stdio.h> #include <time.h> #include <iostream> #include <windows.h> //#define MAX 50 int InitialLength =15,q,e; char Screen[25][80]; // What to show on the screen char bait; bool akbar=true; bool masoudd=false; int Direction[25][80]; // Movement direction of each part of the snake body (1 -> Right, 2 -> Up, 3 -> Left, 4 -> Down, 0 -> No part of the snake) int BreakPoint[25][80]; // Changing direction of each part of the snake body due to pressing arror keys. Numbering is the sam as above. int head_col, head_row, endd = 1, bait_col, bait_row; // Cooredinates of the snake head. // Gets a 25*80 character matrix and shows simlutaneously ob the screen. void raandom() { while (akbar) { bait_col = rand() % 80; bait_row = rand() % 25; if (Screen[bait_row][bait_col]==' ') { Screen[bait_row][bait_col] = '$'; return; } } } void WriteScreenData(char Buffer[25][80]) { HANDLE hNewScreenBuffer; SMALL_RECT screenRect; CHAR_INFO chiBuffer[25 * 80]; COORD coordBufSize, coordBufCoord; for (int i = 0; i < 25; i++) { for (int j = 0; j < 80; j++) { chiBuffer[i * 80 + j].Char.AsciiChar = chiBuffer[i * 80 + j].Char.UnicodeChar = Buffer[i][j]; chiBuffer[i * 80 + j].Attributes = 7; } } hNewScreenBuffer = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CONSOLE_TEXTMODE_BUFFER, NULL); SetConsoleActiveScreenBuffer(hNewScreenBuffer); screenRect.Top = 0; screenRect.Left = 0; screenRect.Bottom = 24; screenRect.Right = 79; coordBufSize.Y = 25; coordBufSize.X = 80; coordBufCoord.X = 0; coordBufCoord.Y = 0; WriteConsoleOutput(hNewScreenBuffer, chiBuffer, coordBufSize, coordBufCoord, &screenRect); } void DrawSnake() { system("cls"); WriteScreenData(Screen); } void Start() { for (int i = 0; i < 25; i++) { for (int j = 0; j < 80; j++) { Screen[i][j] = ' '; Direction[i][j] = BreakPoint[i][j] = 0; } } //DrawSnake(); srand(time(NULL)); } void Get() { if (_kbhit()) { char ch = _getch(); if (ch == 27) exit(0); if (ch == -32) { ch = _getch(); if (ch == 77 && endd != 3) { endd = 1; BreakPoint[head_row][head_col] = 1; // Go right when arrived at this coordination } else if (ch == 72 && endd != 4) { endd = 2; BreakPoint[head_row][head_col] = 2; // Go up when arrived at this coordination } else if (ch == 75 && endd != 1) { endd = 3; BreakPoint[head_row][head_col] = 3; // Go left when arrived at this coordination } else if (ch == 80 && endd != 2) { endd = 4; BreakPoint[head_row][head_col] = 4; // Go down when arrived at this coordination } } } } void masoud() { for (int x = 0; x <25; x++) { for (int y = 0; y < 80; y++) { if (Screen[x][y] == '+') { if (Direction[x][y] == 1) { //going right if (y>0) { Screen[x][y] = '*'; Screen[x][y - 1] = '+'; Direction[x][y] = 1; Direction[x][y-1]=1; InitialLength++; cout << "\a"; raandom(); } else { Screen[x][y] = '*'; Screen[x][79] = '+'; Direction[x][y] = 1; InitialLength++; cout << "\a"; Direction[x][79] = 1; raandom(); } return; } else if (Direction[x][y] == 2) {//going up if (x<24) { Screen[x][y] = '*'; Screen[x + 1][y] = '+'; Direction[x][y] = 2; InitialLength++; cout << "\a"; Direction[x+1][y] = 2; raandom(); } else { Screen[x][y] = '*'; Screen[0][y] = '+'; Direction[x][y] = 2; Direction[0][y] = 2; InitialLength++; cout << "\a"; raandom(); } return; } else if (Direction[x][y] == 3) {//going left if (y<79) { Screen[x][y] = '*'; Screen[x][y + 1] = '+'; Direction[x][y] = 3; cout << "\a"; InitialLength++; Direction[x][y+1] = 3; raandom(); } else { Screen[x][y] = '*'; Screen[x][0] = '+'; Direction[x][y] = 3; cout << "\a"; InitialLength++; Direction[x][0] = 3; raandom(); } return; } else if (Direction[x][y] == 4) {//going down if (x>0) { Screen[x][y] = '*'; Screen[x - 1][y] = '+'; Direction[x][y] = 4; Direction[x-1][y] = 4; cout << "\a"; InitialLength++; raandom(); return; } else { Screen[x][y] = '*'; Direction[x][y] = 4; Screen[24][y] = '+'; Direction[24][y] = 4; cout << "\a"; InitialLength++; raandom(); return; } } } } } } void FirstStep() { head_col = rand() % 80; if (head_col< InitialLength - 1) { head_col = InitialLength - 1; } head_row = rand() % 25; Screen[head_row][head_col] = '&'; Direction[head_row][head_col] = 1; bait_col = rand() % 80; bait_row = rand() % 25; //between + , & for (int i = 1; i < InitialLength - 1; i++) { Screen[head_row][head_col - i] = '*'; Direction[head_row][head_col - i] = 1;//first Direction//set for all charactors//right } Screen[bait_row][bait_col] = '$'; Screen[head_row][head_col - InitialLength + 1] = '+'; Direction[head_row][head_col - InitialLength + 1] = 1; DrawSnake(); //_getch(); } void Newlocation() { Get(); char NewScreen[25][80]; int NewDirection[25][80]; for (int i = 0; i < 25; i++) { for (int j = 0; j < 80; j++) { NewScreen[i][j] = ' '; NewDirection[i][j] = 0; } } ///////////////////////////////////////////////////////////////////////// //chech all parts of snake for (int i = 0; i < 25; i++) { for (int j = 0; j < 80; j++) { if (Screen[head_row][head_col]=='*') { masoudd = true; return; } if (Screen[i][j] != ' ') { if ( BreakPoint[i][j] != 0 ) { Direction[i][j] = BreakPoint[i][j]; } if (Screen[i][j] == '+') { BreakPoint[i][j] = 0; } switch (Direction[i][j]) { //Direction and Screen are our variables; case 1://go right//one charactar { if (j<79) { if (Screen[bait_row][bait_col] == Screen[head_row][head_col] && Direction[head_row][head_col]==1) { Screen[bait_row][bait_col] = ' '; Direction[bait_row][bait_col] = 0; Screen[bait_row][bait_col] = '&'; Direction[bait_row][bait_col] = 1; masoud(); return; } NewScreen[i][j + 1] = Screen[i][j]; NewDirection[i][j + 1] = 1; if (Screen[i][j] == '&') { head_col = j + 1; head_row = i; } } else { NewScreen[i][0] = Screen[i][j]; NewDirection[i][0] = 1; if (Screen[i][j] == '&') { head_col = 0; head_row = i; } } }break; case 2://going up { if (i>0) { if (Screen[bait_row][bait_col] == Screen[head_row][head_col] && Direction[head_row][head_col] == 2) { Screen[bait_row][bait_col] = ' '; Direction[bait_row][bait_col] = 0; Screen[bait_row][bait_col] = '&'; Direction[bait_row][bait_col] = 2; masoud(); return; } NewScreen[i - 1][j] = Screen[i][j]; NewDirection[i - 1][j] = 2; if (Screen[i][j] == '&'){ head_row = i - 1; head_col = j; } } else { NewScreen[24][j] = Screen[i][j]; NewDirection[24][j] = 2; if (Screen[i][j] == '&'){ head_row = 24; } } } break; case 3://going left { if (j>0) { if (Screen[bait_row][bait_col] == Screen[head_row][head_col] && Direction[head_row][head_col] == 3) { Screen[bait_row][bait_col] = ' '; Direction[bait_row][bait_col] = 0; Screen[bait_row][bait_col] = '&'; Direction[bait_row][bait_col] = 3; masoud(); return; } NewScreen[i][j - 1] = Screen[i][j]; NewDirection[i][j - 1] = 3; if (Screen[i][j] == '&') { head_col = j - 1; } } else { NewScreen[i][79] = Screen[i][j]; NewDirection[i][79] = 3; if (Screen[i][j] == '&'){ head_col = 79; } } } break; case 4: { if (i<24) { if (Screen[bait_row][bait_col] == Screen[head_row][head_col] && Direction[head_row][head_col] == 4) { Screen[bait_row][bait_col] = ' '; Direction[bait_row][bait_col] = 0; Screen[bait_row][bait_col] = '&'; Direction[bait_row][bait_col] = 4; masoud(); return; } NewScreen[i + 1][j] = Screen[i][j]; NewDirection[i + 1][j] = 4; if (Screen[i][j] == '&'){ head_row = i + 1; } } else { NewScreen[0][j] = Screen[i][j]; NewDirection[0][j] = 4; if (Screen[i][j] == '&'){ head_row = 0; } } } break; } } } } for (int i = 0; i <25; i++) { for (int j = 0; j < 80; j++) { Screen[i][j] = NewScreen[i][j]; Direction[i][j] = NewDirection[i][j]; } } Screen[bait_row][bait_col] = '$'; } void main(void) { Start(); FirstStep(); while (1) { Sleep(100); Newlocation(); DrawSnake(); if (masoudd==true) { system("cls"); break; } } cout<<"you lose :("<<"\n"; cout << "YOUR SCORE :=>" << (InitialLength - 15); _getch(); }
true
25dc6b40e10aa2791e0ab3351182f6e55a4c9618
C++
orcchg/StudyProjects
/ORDINARY_PROGS/PEREBOR/number_of_splitts/main.cpp
UTF-8
630
3.078125
3
[]
no_license
#include <conio.h> #include <stdio.h> typedef long ULONG; ULONG Pk_split(ULONG,ULONG); int main() { int N; ULONG P; printf("Number of splitts; Enter N: "); scanf("%d",&N); printf("\n"); ULONG* ArrP = new ULONG[N]; P = Pk_split(N,N); printf("P = %ld\n\n",P); for(int y = 0; y < N; y++) { ArrP[y] = Pk_split(y+1,y+1); printf("%d: %ld\n",y+1,ArrP[y]); } delete [] ArrP; _getch(); } ULONG Pk_split(ULONG n, ULONG k) { ULONG p = 0; if(k == 1) return 1; if(n < 0) return 0; if(n == 0) return 1; { p = Pk_split(n - k,k) + Pk_split(n,k - 1); } return p; }
true
beb36fd68b8eefccf5374c0ef8d0df3c9b0a4dbb
C++
hvanhorik-GDP/Master
/Projects/GDP2019_Test/GLFW_Callbacks.cpp
UTF-8
5,668
2.5625
3
[]
no_license
#include "GLFW_Callbacks.h" #include "gl/GLCommon.h" #include <glm/glm.hpp> #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include "../Common/globalStuff.h" // for find object #include "../Common/pFindObjectByFriendlyName.h" #include <stdio.h> // for fprintf() static bool isShiftKeyDownByAlone(int mods); static bool isCtrlKeyDownByAlone(int mods); void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { const float cameraSPEED = 2.0f; if (!isShiftKeyDownByAlone(mods) && !isCtrlKeyDownByAlone(mods)) { // Move the camera (A & D for left and right, along the x axis) if (key == GLFW_KEY_A) { old_cameraEye.x -= cameraSPEED; // Move the camera -0.01f units } if (key == GLFW_KEY_D) { old_cameraEye.x += cameraSPEED; // Move the camera +0.01f units } // Move the camera (Q & E for up and down, along the y axis) if (key == GLFW_KEY_Q) { old_cameraEye.y -= cameraSPEED; // Move the camera -0.01f units } if (key == GLFW_KEY_E) { old_cameraEye.y += cameraSPEED; // Move the camera +0.01f units } // Move the camera (W & S for towards and away, along the z axis) if (key == GLFW_KEY_W) { old_cameraEye.z -= cameraSPEED; // Move the camera -0.01f units } if (key == GLFW_KEY_S) { old_cameraEye.z += cameraSPEED; // Move the camera +0.01f units } if (key == GLFW_KEY_B) { // Shoot a bullet from the pirate ship // Find the pirate ship... // returns NULL (0) if we didn't find it. cObject_Model* pShip = pFindObjectByFriendlyName("PirateShip"); // Maybe check to see if it returned something... // Find the sphere#2 cObject_Model* pBall = pFindObjectByFriendlyName("Sphere#2"); // Set the location velocity for sphere#2 pBall->positionXYZ = pShip->positionXYZ; pBall->inverseMass = 1.0f; // So it's updated // 20.0 units "to the right" // 30.0 units "up" pBall->velocity = glm::vec3(15.0f, 20.0f, 0.0f); pBall->acceleration = glm::vec3(0.0f, 0.0f, 0.0f); pBall->diffuseColour = glm::vec4(1.0f, 0.0f, 0.0f, 0.0f); }//if ( key == GLFW_KEY_B ) } if (isShiftKeyDownByAlone(mods)) { // move the light if (key == GLFW_KEY_A) { sexyLightPosition.x -= cameraSPEED; // Move the camera -0.01f units } if (key == GLFW_KEY_D) { sexyLightPosition.x += cameraSPEED; // Move the camera +0.01f units } // Move the camera (Q & E for up and down, along the y axis) if (key == GLFW_KEY_Q) { sexyLightPosition.y -= cameraSPEED; // Move the camera -0.01f units } if (key == GLFW_KEY_E) { sexyLightPosition.y += cameraSPEED; // Move the camera +0.01f units } // Move the camera (W & S for towards and away, along the z axis) if (key == GLFW_KEY_W) { sexyLightPosition.z -= cameraSPEED; // Move the camera -0.01f units } if (key == GLFW_KEY_S) { sexyLightPosition.z += cameraSPEED; // Move the camera +0.01f units } if (key == GLFW_KEY_1) { sexyLightConstAtten *= 0.99f; // 99% of what it was } if (key == GLFW_KEY_2) { sexyLightConstAtten *= 1.01f; // 1% more of what it was } if (key == GLFW_KEY_3) { sexyLightLinearAtten *= 0.99f; // 99% of what it was } if (key == GLFW_KEY_4) { sexyLightLinearAtten *= 1.01f; // 1% more of what it was } if (key == GLFW_KEY_5) { sexyLightQuadraticAtten *= 0.99f; // 99% of what it was } if (key == GLFW_KEY_6) { sexyLightQuadraticAtten *= 1.01f; // 1% more of what it was } if (key == GLFW_KEY_V) { sexyLightSpotInnerAngle -= 0.1f; } if (key == GLFW_KEY_B) { sexyLightSpotInnerAngle += 0.1f; } if (key == GLFW_KEY_N) { sexyLightSpotOuterAngle -= 0.1f; } if (key == GLFW_KEY_M) { sexyLightSpotOuterAngle += 0.1f; } if (key == GLFW_KEY_9) { bLightDebugSheresOn = false; } if (key == GLFW_KEY_0) { bLightDebugSheresOn = true; } }//if (isShiftKeyDownByAlone(mods)) // Moving the pirate ship in a certain direction if (isCtrlKeyDownByAlone(mods)) { const float SHIP_SPEED_CHANGE = 0.01f; const float SHIP_ANGLE_CHANGE = 0.01f; cObject_Model* pShip = pFindObjectByFriendlyName("PirateShip"); // Turn the ship around //if (key == GLFW_KEY_A) //{ // Left // pShip->HACK_AngleAroundYAxis -= SHIP_ANGLE_CHANGE; // pShip->rotationXYZ.y = pShip->HACK_AngleAroundYAxis; //} //if (key == GLFW_KEY_D) //{ // Right // pShip->HACK_AngleAroundYAxis += SHIP_ANGLE_CHANGE; // pShip->rotationXYZ.y = pShip->HACK_AngleAroundYAxis; //} //if (key == GLFW_KEY_W) //{ // Faster // pShip->HACK_speed += SHIP_SPEED_CHANGE; //} //if (key == GLFW_KEY_S) //{ // Slower // pShip->HACK_speed -= SHIP_SPEED_CHANGE; //} } if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GLFW_TRUE); } bool isShiftKeyDownByAlone(int mods) { if (mods == GLFW_MOD_SHIFT) { // Shift key is down all by itself return true; } //// Ignore other keys and see if the shift key is down //if ((mods & GLFW_MOD_SHIFT) == GLFW_MOD_SHIFT) //{ //} return false; } bool isCtrlKeyDownByAlone(int mods) { if (mods == GLFW_MOD_CONTROL) { return true; } return false; } void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) { // Move the sphere to where the camera is and shoot the ball from there... cObject_Model* pTheBall = pFindObjectByFriendlyName("Sphere#1"); // What's the velocity // Target - eye = direction glm::vec3 direction = glm::normalize(old_cameraTarget - old_cameraEye); float speed = 5.0f; pTheBall->velocity = direction * speed; pTheBall->positionXYZ = old_cameraEye; return; }
true
8c15ebb41c1dd0a7753bedadbb88d4c86b305520
C++
ailuoxz/BadPrincess-Game
/Src/BaseSubsystems/Math.h
ISO-8859-1
5,688
3.0625
3
[]
no_license
/** @file Math.h Este fichero contiene la definicin de ciertos tipos de datos utilizados por la aplicacin y relacionados con la base matemtica; en particular, define distintos tipos de matriz, vector, etc. <p> En la prctica, los tipos son simplemente tipos sinnimos a los de Ogre, para evitar prdidas de tiempo en conversiones superfluas entre la aplicacin y Ogre (s habr que hacerlas entre la aplicacin y el motor de fsica, por ejemplo). <p> Se ofrecen tambin una serie de funciones auxiliares. @author David Llans @date Julio, 2010 */ #ifndef __BaseSubsystems_Math_H #define __BaseSubsystems_Math_H // Includes de Ogre donde se definen los tipos #include "../OGRE/OgreVector2.h" #include <../OGRE/OgreVector3.h> #include <../OGRE/OgreVector4.h> #include <../OGRE/OgreQuaternion.h> #include <../OGRE/OgreMatrix3.h> #include <../OGRE/OgreMatrix4.h> #include <../OGRE/OgreRay.h> /** Definicion de matriz de 4x4. La definicin del tipo de datos es la misma que la utilizada por el motor grfico, por lo tanto es dependiente del motor usado. */ typedef Ogre::Matrix4 Matrix4; /** Definicin de matriz de 3x3 de rotacin. La definicin del tipo de datos es la misma que la utilizada por el motor grfico, por lo tanto es dependiente del motor usado. */ typedef Ogre::Matrix3 Matrix3; /** Vector (o punto) 2d utilizado. La definicin del tipo de datos es la misma que la utilizada por el motor grfico, por lo tanto es dependiente del motor usado. */ typedef Ogre::Vector2 Vector2; /** Vector (o punto) 3d utilizado. La definicin del tipo de datos es la misma que la utilizada por el motor grfico, por lo tanto es dependiente del motor usado. */ typedef Ogre::Vector3 Vector3; /** Vector (o punto) 4d utilizado. La definicin del tipo de datos es la misma que la utilizada por el motor grfico, por lo tanto es dependiente del motor usado. */ typedef Ogre::Vector4 Vector4; /** Quaternion, usado para clculos de rotaciones tridimensionales. La definicin del tipo de datos es la misma que la utilizada por el motor grfico, por lo tanto es dependiente del motor usado. */ typedef Ogre::Quaternion Quaternion; /** Rayo. La definicin del tipo de datos es la misma que la utilizada por el motor grfico, por lo tanto es dependiente del motor usado. */ typedef Ogre::Ray Ray; /** Rayo. La definicin del tipo de datos es la misma que la utilizada por el motor grfico, por lo tanto es dependiente del motor usado. */ typedef Ogre::Radian Radian; /** Namespace en el que ofrecemos alguna definicin de constante matamtica y mtodos para convertir grados en radianes, etc. */ namespace Math { /** Definicin de la constante PI. */ static const float PI = float( 4.0 * atan( 1.0 ) ); /** Constante para pasar de grados a radianes. */ static const float _deg2Rad = PI / 180.0f; /** Constante para pasar de radianes a grados. */ static const float _rad2Deg = 180.0f / PI; /** Transforma grados en radianes. @param degree ngulo en grados. @return ngulo en radianes. */ static float fromDegreesToRadians(float degrees) {return degrees*_deg2Rad;} /** Transforma radianes en grados. @param radian ngulo en radianes. @return ngulo en grados. */ static float fromRadiansToDegrees(float radians) {return radians*_rad2Deg;} /** Crea un vector unitario de direccin a partir de un angulo de orientacin en radianes. @param orientation Orientacin en radianes. @return Vector unitario en el plano XZ. */ static Vector3 getDirection(float orientation) { return Vector3(-sin(orientation), 0, -cos(orientation)); } // getDirection /** Aplica un viraje a una matriz de transformacin. @param turn Giro en radianes que se quiere aplicar. @param transform Matriz de transformacin a modificar. */ static void yaw(float turn, Matrix4& transform) { Matrix3 rotation; transform.extract3x3Matrix(rotation); Ogre::Radian yaw, pitch, roll; rotation.ToEulerAnglesYXZ(yaw, pitch, roll); Ogre::Radian newYaw = yaw + Ogre::Radian(turn); rotation.FromEulerAnglesYXZ(newYaw, pitch, roll); transform = rotation; } // yaw /** Extrae el estado del viraje de una matriz de transformacin. @param transform Matriz de transformacin. @return Viraje de la entidad. */ static float getYaw(const Matrix4& transform) { Matrix3 rotation; transform.extract3x3Matrix(rotation); Ogre::Radian yaw, pitch, roll; rotation.ToEulerAnglesYXZ(yaw, pitch, roll); return yaw.valueRadians(); } // getYaw /** Establece un viraje a una matriz de transformacin. @param turn Giro en radianes que se quiere etablecer. @param transform Matriz de transformacin a modificar. */ static void setYaw(float turn, Matrix4& transform) { // Reiniciamos la matriz de rotacin transform = Matrix3::IDENTITY; // Sobre esta rotamos. Math::yaw(turn,transform); } // setYaw /** Crea un vector unitario de direccin en el plano XZ a partir de una matriz de transformacin. @param transform Matriz de transformacin. @return Vector unitario en el plano XZ. */ static Vector3 getDirection(const Matrix4& transform) { return getDirection(getYaw(transform)); } // getDirection /** Crea un vector unitario de direccin en el plano XZ que corresponde al vector pasado por parmetro y girado 90 grados en el eje de la Y. @param direction Vector director @return Vector normal al vector director. */ static Vector3 getPerpendicular (const Vector3& direction) { Ogre::Quaternion q; q.FromAngleAxis(Ogre::Degree(90),Vector3::UNIT_Y); return q * direction.normalisedCopy(); } } // namespace Math #endif // __BaseSubsystems_Math_H
true
ca60fb7ae22ebd9922948e3e776b097748b9e776
C++
dabare/arduino
/robotSensor/robotSensor.ino
UTF-8
2,069
2.65625
3
[]
no_license
//----------------------Motors----------------- #define MLF 9 #define MLB 10 #define MRF 5 #define MRB 6 //----------------------Sensors----------------- #define SJL 11 #define SJR 2 #define SPR 3 #define SPL 4 #define SJF 12 #define SJY 13 #define maxMotor 255 #define blackPath 1 void setup() { pinMode(8, INPUT); pinMode(2, OUTPUT); pinMode(3, OUTPUT); pinMode(4, OUTPUT); pinMode(11, OUTPUT); pinMode(12, OUTPUT); pinMode(13, OUTPUT); digitalWrite(2, HIGH); digitalWrite(3, HIGH); digitalWrite(4, HIGH); digitalWrite(11, HIGH); digitalWrite(12, HIGH); digitalWrite(13, HIGH); Serial.begin(9600); } void loop() { followLine(); } void followLine() { if (readPin(SJF) && !readPin(SJL) && readPin(SJR)) { while (readPin(SJF)) { rightMotorForward(); leftMotorBackward(); } stopLeftMotor(); stopRightMotor(); } else if (readPin(SJF) && readPin(SJL) && !readPin(SJR)) { while (readPin(SJF)) { leftMotorForward(); rightMotorBackward(); } stopLeftMotor(); stopRightMotor(); } else if (readPin(SPL) && !readPin(SPR)) { stopRightMotor(); leftMotorForward(); } else if (readPin(SPR) && !readPin(SPL)) { stopLeftMotor(); rightMotorForward(); } else if (!readPin(SPR) && !readPin(SPL)) { leftMotorForward(); rightMotorForward(); } else { stopRightMotor(); stopLeftMotor(); } } void leftMotorForward() { analogWrite(MLF, maxMotor); analogWrite(MLB, 0); } void rightMotorForward() { analogWrite(MRF, maxMotor); analogWrite(MRB, 0); } void leftMotorBackward() { analogWrite(MLF, 0); analogWrite(MLB, maxMotor); } void rightMotorBackward() { analogWrite(MRF, 0); analogWrite(MRB, maxMotor); } void stopRightMotor() { analogWrite(MRF, 0); analogWrite(MRB, 0); } void stopLeftMotor() { analogWrite(MLF, 0); analogWrite(MLB, 0); } bool readPin(int pin) { bool stat = false; digitalWrite(pin, LOW); delayMicroseconds(200); stat = digitalRead(8); digitalWrite(pin, HIGH); return blackPath - stat; }
true
c859641293deefddfabf6b80d545eff516df0314
C++
ArpitSingla/Competitve-Programming-CP
/Codeforces Contest/Round #644 (Div. 3)/Similar Pairs.cpp
UTF-8
1,084
2.578125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define int long long int int32_t main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin) ; freopen("output.txt", "w", stdout) ; #endif ios_base::sync_with_stdio(false); cin.tie(NULL) ; cout.tie(NULL) ; int t ; cin >> t ; while( t-- ) { int n; cin>>n; int *arr=new int[n]; for(int i=0;i<n;i++){ cin>>arr[i]; } int even=0,odd=0; int flag=0; for(int i=0;i<n;i++){ if(arr[i]&1){ odd++; } else{ even++; } } if((odd%2==0) && (even%2==0)){ cout<<"YES"<<endl; } else{ sort(arr,arr+n); for(int i=0;i<n;i++){ if(arr[i+1]-arr[i]==1){ flag=1; break; } } if(flag){ cout<<"YES"<<endl; } else{ cout<<"NO"<<endl; } } } return 0 ; }
true
9b5c0b6e5f3bcef1274de396654f4e638c1d861e
C++
aliasvishnu/leetcode
/Solutions/621*-TaskScheduler.cpp
UTF-8
1,557
3.40625
3
[]
no_license
// Time - O(n) // Space - O(k) /* First we store all the counts in a heap (name of the process doesn't matter). For n+1 steps, we pick the most occuring process and subtact 1 from it and put it in an array. Then we add the new values to the heap. We do this until there are more than or equal to n processes in teh heap. Otherwise, we just have (n+1)*count to add to the answer; */ #include <priority_queue> class Solution { public: priority_queue<int> q; unordered_map<char, int> mp; int leastInterval(vector<char>& tasks, int n) { int time = 0; int len = tasks.size(); for(int i = 0; i < len; i++){ if(mp.find(tasks[i]) == mp.end()) mp[tasks[i]] = 0; mp[tasks[i]] += 1; } unordered_map<char, int> ::iterator it; for(it = mp.begin(); it != mp.end(); it++){ q.push(it->second); } while(q.size() > n){ vector<int> temp; for(int j = 0; j < (n+1); j++){ temp.push_back(q.top()-1); time += 1; q.pop(); } for(int j = 0; j < (n+1); j++){ if(temp[j] > 0) q.push(temp[j]); } } int count = 0; if(!q.empty() && q.top() != 0) { int val = q.top(); q.pop(); while(!q.empty() && q.top() == val){ count += 1; q.pop(); } time +=(1+n)*val + count-n; } return time; } };
true
5d8602a63f7cf0a8c983b6b6432e55cde150fb15
C++
Christopher-Yan/Luogu
/lg 2663.cpp
UTF-8
432
2.578125
3
[]
no_license
#include <iostream> #include <cstdio> using namespace std; int n, m, sum; int c[30]; int dp[10010]; int main() { cin >> n; m = n / 2; for (int i = 1; i <= n; ++i) { cin >> c[i]; sum += c[i]; } sum /= 2; for (int i = 1; i <= n; ++i) { for (int j = m; j >= c[i]; --j) { cout << c[i] <<endl; if (dp[j] + c[i] <= sum) dp[j] = max(dp[j], dp[j - 1] + c[i]); } } cout << dp[m]; return 0; }
true
79344e8a459ab21de9b410a5a31308ebd22160ed
C++
OrangeBaoWang/AutoTuneTMP
/paper/fmm_m2m_interactions/kernels/struct_of_array_data.hpp
UTF-8
6,941
2.890625
3
[ "BSD-3-Clause" ]
permissive
#pragma once // #include "interaction_constants.hpp" namespace octotiger { namespace fmm { // component type has to be indexable, and has to have a size() operator template <typename AoS_type, typename component_type, size_t num_components, size_t entries, size_t padding> class struct_of_array_data { private: // data in SoA form static constexpr size_t padded_entries_per_component = entries + padding; component_type *const data; public: template <size_t component_access> inline component_type *pointer(const size_t flat_index) const { constexpr size_t component_array_offset = component_access * padded_entries_per_component; // should result in single move instruction, indirect addressing: reg + reg // + constant return data + flat_index + component_array_offset; } // careful, this returns a copy! template <size_t component_access> inline m2m_vector value(const size_t flat_index) const { return m2m_vector(this->pointer<component_access>(flat_index), Vc::flags::element_aligned); } // template <size_t component_access> // inline component_type& reference(const size_t flat_index) const { // return *this->pointer<component_access>(flat_index); // } struct_of_array_data(const std::vector<AoS_type> &org) : data( new component_type[num_components * padded_entries_per_component]) { for (size_t component = 0; component < num_components; component++) { for (size_t entry = 0; entry < org.size(); entry++) { data[component * padded_entries_per_component + entry] = org[entry][component]; } } } struct_of_array_data(const size_t entries_per_component) : data( new component_type[num_components * padded_entries_per_component]) { } ~struct_of_array_data() { if (data) { delete[] data; } } struct_of_array_data(const struct_of_array_data &other) = delete; struct_of_array_data(const struct_of_array_data &&other) = delete; struct_of_array_data &operator=(const struct_of_array_data &other) = delete; // write back into non-SoA style array void to_non_SoA(std::vector<AoS_type> &org) { // constexpr size_t padded_entries_per_component = entries + padding; for (size_t component = 0; component < num_components; component++) { for (size_t entry = 0; entry < org.size(); entry++) { org[entry][component] = data[component * padded_entries_per_component + entry]; } } } }; // template <typename AoS_type, typename component_type, size_t num_components> // class struct_of_array_data; // template <typename AoS_type, typename component_type, size_t num_components> // class struct_of_array_iterator; // template <typename AoS_type, typename component_type, size_t num_components> // class struct_of_array_view // { // protected: // struct_of_array_data<AoS_type, component_type, num_components>& data; // size_t flat_index; // public: // struct_of_array_view<AoS_type, component_type, num_components>( // struct_of_array_data<AoS_type, component_type, num_components>& data, // size_t // flat_index) // : data(data) // , flat_index(flat_index) {} // inline m2m_vector component(size_t component_index) const { // return m2m_vector(this->component_pointer(component_index), // Vc::flags::element_aligned); // } // // returning pointer so that Vc can convert into simdarray // // (notice: a reference would be silently broadcasted) // inline component_type* component_pointer(size_t component_index) const { // return data.access(component_index, flat_index); // } // }; // // component type has to be indexable, and has to have a size() operator // template <typename AoS_type, typename component_type, size_t num_components> // class struct_of_array_data // { // private: // // data in SoA form // std::vector<component_type> data; // const size_t padded_entries_per_component; // friend class struct_of_array_iterator<AoS_type, component_type, // num_components>; // public: // struct_of_array_data(const std::vector<AoS_type>& org) // : padded_entries_per_component(org.size() + SOA_PADDING) { // data = std::vector<component_type>(num_components * (org.size() + // SOA_PADDING)); // for (size_t component = 0; component < num_components; component++) { // for (size_t entry = 0; entry < org.size(); entry++) { // data[component * padded_entries_per_component + entry] = // org[entry][component]; // } // } // } // struct_of_array_data(const size_t entries_per_component) // : padded_entries_per_component(entries_per_component + SOA_PADDING) { // data = std::vector<component_type>(num_components * // padded_entries_per_component); // } // inline component_type* access(const size_t component_index, const size_t // flat_entry_index) { // return data.data() + // (component_index * padded_entries_per_component + // flat_entry_index); // } // struct_of_array_view<AoS_type, component_type, num_components> // get_view(size_t // flat_index) { // return struct_of_array_view<AoS_type, component_type, // num_components>( // *this, flat_index); // } // // write back into non-SoA style array // void to_non_SoA(std::vector<AoS_type>& org) { // for (size_t component = 0; component < num_components; component++) { // for (size_t entry = 0; entry < org.size(); entry++) { // org[entry][component] = data[component * // padded_entries_per_component + // entry]; // } // } // } // }; // template <typename AoS_type, typename component_type, size_t num_components> // class struct_of_array_iterator // { // private: // component_type* current; // size_t component_offset; // public: // struct_of_array_iterator( // struct_of_array_data<AoS_type, component_type, num_components>& data, // size_t flat_index) { // current = data.data.data() + flat_index; // component_offset = data.padded_entries_per_component; // } // inline component_type* pointer() { // return current; // } // // int is dummy parameter // inline void operator++(int) { // current += component_offset; // } // inline void increment(size_t num) { // current += component_offset * num; // } // inline void decrement(size_t num) { // current -= component_offset * num; // } // inline m2m_vector value() { // return m2m_vector(this->pointer(), Vc::flags::element_aligned); // } // }; } // namespace fmm } // namespace octotiger
true
b4470c5ec51efe5550cde7ff6e91541b2db773ea
C++
Nonaminggumerah/MAGANG_IRIS-repo
/Penugasan_3.cpp
UTF-8
790
3.40625
3
[]
no_license
#include <iostream> #include <cstring> using namespace std; class Animal { protected: int umur;char nama[10]; public: void set_data (int a, char b[10]) { umur = a; strcpy(b,nama); } }; class Zebra:public Animal {public: void message_zebra() {cout<< "Zebra namanya "<<nama<<" berumur "<< umur << "tahun. Zebra suka minum kopi. \n";} }; class Lumbalumba: public Animal {public: void message_lumbalumba() {cout<< "Lumba-lumba namanya "<< nama << " berumur "<< umur << "tahun. Lumba-lumba suka makan cokelat.\n";} }; int main () { Zebra zeb; Lumbalumba lumba; char n1[10]="Pi'i'"; char n2[10]="Yoyon"; zeb.set_data (20,n1); lumba.set_data (12,n2); zeb.message_zebra() ; lumba.message_lumbalumba() ; return 0; }
true
b309bedb3bc251c52dd1154c2e5a725a8a33a7af
C++
makese/PAT-Basic
/1012.cpp
UTF-8
1,017
2.78125
3
[]
no_license
#include <iostream> using namespace std; int main(){ int in[1000]; int n = 0; int a[5] = {0}; bool has[5] = {false}; bool a2 = false; int a4 = 0; cin >> n; for(int i = 0; i < n; i ++) { cin >> in[i]; } for(int i = 0; i < n; i ++){ switch(in[i] % 5){ case 0: if(in[i] % 2 == 0) { a[0] += in[i]; has[0] = true; } break; case 1: if(!a2){ a[1] += in[i]; a2 = true; has[1] = true; } else { a[1] -= in[i]; a2 = false; } break; case 2: a[2] ++; has[2] = true; break; case 3: has[3] = true; a[3] += in[i]; a4 ++; break; case 4: has[4] = true; if(a[4] < in[i]){ a[4] = in[i]; } break; } } for(int i = 0; i < 4; i ++){ if(has[i] == true){ if(i == 3){ float temp = a[i] / (float)a4; printf("%.1f ",temp); } else { printf("%d ",a[i]); } } else { printf("%c ",'N'); } } if(has[4] == true){ printf("%d",a[4]); } else { printf("%c",'N'); } }
true
45b75eb23427c76e7d273c9dc9c3827c5cb1f521
C++
yuta6686/DX_016
/DX21_Sample16/score.cpp
SHIFT_JIS
3,687
3.015625
3
[]
no_license
//============================================================================= // // XRA [score.cpp] // Author : // //============================================================================= #include "score.h" #include "texture.h" #include "sprite.h" //***************************************************************************** // }N` //***************************************************************************** #define TEXTURE_WIDTH (16) // LTCY #define TEXTURE_HEIGHT (32) // #define TEXTURE_MAX (1) // eNX`̐ //***************************************************************************** // vg^Cv錾 //***************************************************************************** //***************************************************************************** // O[oϐ //***************************************************************************** static bool g_Use; // true:gĂ false:gp static float g_w, g_h; // ƍ static D3DXVECTOR3 g_Pos; // |S̍W static int g_TexNo; // eNX`ԍ static int g_Score; // XRA //============================================================================= // //============================================================================= HRESULT InitScore(void) { //eNX` g_TexNo = LoadTexture("data/TEXTURE/number.png"); // g_Use = true; g_w = TEXTURE_WIDTH; g_h = TEXTURE_HEIGHT; g_Pos = D3DXVECTOR3(500.0f, 20.0f, 0.0f); g_Score = 0; // XRȀ return S_OK; } //============================================================================= // I //============================================================================= void UninitScore(void) { } //============================================================================= // XV //============================================================================= void UpdateScore(void) { } //============================================================================= // `揈 //============================================================================= void DrawScore(void) { //LtOONȂ`悷 if (g_Use) { // eNX`ݒ GetDeviceContext()->PSSetShaderResources(0, 1, GetTexture(g_TexNo)); // int number = g_Score; for (int i = 0; i < SCORE_DIGIT; i++) { // \錅̐ float x = (float)(number % 10); // XRÄʒueNX`[W𔽉f float px = g_Pos.x - g_w * i; // vC[̕\ʒuX float py = g_Pos.y; // vC[̕\ʒuY float pw = g_w; // vC[̕\ float ph = g_h; // vC[̕\ float tw = 1.0f / 10; // eNX`̕ float th = 1.0f / 1; // eNX`̍ float tx = x * tw; // eNX`̍XW float ty = 0.0f; // eNX`̍YW // P̃|S̒_ƃeNX`Wݒ DrawSprite(g_TexNo, px, py, pw, ph, tx, ty, tw, th); // ̌ number /= 10; } } } //============================================================================= // XRAZ // :add :lj_B}CiX”\ //============================================================================= void AddScore(int add) { g_Score += add; if (g_Score > SCORE_MAX) { g_Score = SCORE_MAX; } }
true
2b2a24944177a2b76b5bf46eff421d1d25cc5490
C++
planaria/kumori
/include/kumori/socket_streambuf.hpp
UTF-8
2,113
2.828125
3
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
#pragma once #include "socket.hpp" namespace kumori { class socket_streambuf : public std::streambuf , boost::noncopyable { public: socket_streambuf( socket& socket, const boost::posix_time::time_duration& timeout, char* input_buffer, std::size_t input_buffer_size, char* output_buffer, std::size_t output_buffer_size) : socket_(socket) , timeout_(timeout) , input_buffer_size_(input_buffer_size) { char* input_buffer_end = input_buffer + input_buffer_size; setg(input_buffer, input_buffer_end, input_buffer_end); char* output_buffer_end = output_buffer + output_buffer_size - 1; setp(output_buffer, output_buffer_end); } socket_streambuf( socket& socket, const boost::posix_time::time_duration& timeout, std::vector<char>& input_buffer, std::vector<char>& output_buffer) : socket_streambuf(socket, timeout, input_buffer.data(), input_buffer.size(), output_buffer.data(), output_buffer.size()) { } virtual int_type underflow() override { if (gptr() == egptr()) { std::size_t n = socket_.read_some(eback(), input_buffer_size_, timeout_); if (n == 0) return traits_type::eof(); setg(eback(), eback(), eback() + n); } return traits_type::to_int_type(*gptr()); } virtual int_type overflow(int_type char_int = traits_type::eof()) override { std::size_t size = pptr() - pbase(); std::size_t offset = 0; if (!traits_type::eq_int_type(char_int, traits_type::eof())) { *pptr() = traits_type::to_char_type(char_int); ++size; } while (offset != size) { char* buffer = pbase() + offset; std::size_t buffer_size = size - offset; std::size_t length = socket_.write_some(buffer, buffer_size, timeout_); offset += length; } setp(pbase(), epptr()); return traits_type::not_eof(char_int); } virtual int sync() override { bool error = traits_type::eq_int_type(overflow(), traits_type::eof()); return error ? -1 : 0; } private: socket& socket_; boost::posix_time::time_duration timeout_; std::size_t input_buffer_size_; }; }
true
42d1b26d30f03ec492d0719a8c5539672c157d70
C++
Stephanomejia17/CCOMP-2-2
/13_Punteros/ejemplo3.cpp
UTF-8
273
3.125
3
[]
no_license
#include <iostream> using namespace std; int main(){ int arr[] = {10,2,4,6,7,9,7}; int tam = sizeof(arr) / sizeof(arr[0]); int *ptr = arr; //es quievalente a poner => int *ptr = &arr[0] while(tam--){ cout << *ptr++ << " "; } cout << endl; }
true
160595ad325379d48058a8365b1b8ced764b810d
C++
sharvi1203/DSA
/Graph/Detect cycle in an undirected graph.cpp
UTF-8
611
3.109375
3
[]
no_license
bool isCyclicUtil(vector<int> g[], int V,int sv,int parent,vector<bool>& visited){ visited[sv]=true; for(auto i=g[sv].begin();i<g[sv].end();i++){ if(!visited[*i]){ if(isCyclicUtil(g,V,*i,sv,visited)){ return true; } }else if(*i!=parent){ return true; } } return false; } bool isCyclic(vector<int> g[], int V) { vector<bool> visited(V,false); for(int i=0;i<V;i++){ if(!visited[i]){ if(isCyclicUtil(g,V,i,-1,visited)){ return true; } } } return false; }
true
b4d80f814cfdc7957f2314fbaea9973028149a0d
C++
wilfried-oss/graph
/graph/Graph.cpp
UTF-8
11,837
3.3125
3
[]
no_license
#include "Graph.h" using namespace std; Graph::Graph(bool type):nodes(),edges(),oriented(type){} void Graph::addNode(string node) { if(nodes.find(node)==nodes.end()) nodes.insert(node); } void Graph::removeNode(string node) { for(const auto &n:nodes) removeEdge(n,node); edges.erase(edges.find(node)); nodes.erase(node); } void Graph::addNode() { vector<string>defNodes; defNodes.push_back("S0"); defNodes.push_back("S1"); defNodes.push_back("S2"); static int i(0); addNode(defNodes[i++]); } void Graph::addEdge(string node1,string node2,int c) { addNode(node1);addNode(node2); edges[node1].push_back(Neighbor(node2,c)); if(!oriented) edges[node2].push_back(Neighbor(node1,c)); } void Graph::removeEdge(string node1,string node2) { vector<Neighbor>&neighbors=edges[node1]; vector<Neighbor>::iterator it=neighbors.begin(); while(it!=neighbors.end()) { if(it->name==node2) { neighbors.erase(it); break; } it++; } if(!oriented) { vector<Neighbor>&neighbors=edges[node2]; it=neighbors.begin(); while(it!=neighbors.end()) { if(it->name==node1) { neighbors.erase(it); break; } it++; } } } void Graph::displayNodes() { for(const auto &n:nodes) cout<<n<<"\t"; cout<<endl; } void Graph::displayMatrix() { int len((int)nodes.size()),i(0),j(0); // Number of nodes vector<int>line(len,0); vector<vector<int> >matrice(len,line); // Null Len order Matrix map<int,string>indexToName; for(const auto &n:nodes) indexToName[i++]=n; // Construction of the matrix for(i=0;i<len;i++) { for(j=0;j<len;j++) matrice[i][j]=getWeight(indexToName[i],indexToName[j]); } // For displaying the matrix cout<<endl<<endl<<"\t\t"; for(const auto &n:indexToName) cout<<n.second<<"\t"; cout<<endl<<endl<<endl; i=0; for(const auto &l:matrice) { cout<<"\t"<<indexToName[i++]<<"\t"; for(const auto &cel:l) cout<<cel<<"\t"; cout<<endl<<endl<<endl; } } bool Graph::fpath(string node1,string node2) { if(nodes.find(node1)==nodes.end()|| nodes.find(node1)==nodes.end()) { NOTFOUND() return false; } vector<string> path=bfs(node1); return find(path.begin(),path.end(),node2)!=path.end(); } void Graph::existPath(string node1,string node2) { bool path=fpath(node1,node2); if(path) cout<<"\nYes there is a path between "<<node1<<" and "<<node2<<endl; else cout<<"\nThere is no path between "<<node1<<" and "<<node2<<endl; } void Graph::order() { if(nodes.size()) cout<<"The order of the graph is "<<nodes.size()<<endl; else cout<<"There is no node on the graph"<<endl; } void Graph::displayDegree(string node) { if(nodes.find(node)==nodes.end()) { NOTFOUND() return; } if (!oriented) cout<<"Deg("<<node<<")="<<edges[node].size()<<endl; else { cout<<"Deg+("<<node<<")="<<nextTo(node).size()<<endl; cout<<"Deg-("<<node<<")="<<previousTo(node).size()<<endl; cout<<"Deg("<<node<<")="<<nextTo(node).size()+previousTo(node).size()<<endl; } } int Graph::degree(string node) { if(nodes.find(node)==nodes.end()) return -1; if(!oriented) return edges[node].size(); return edges[node].size()+previousTo(node).size(); } void Graph::displayNextTo(string node) { if(nodes.find(node)==nodes.end()) { NOTFOUND( ) return; } vector<string> nex=nextTo(node); if(nex.size()==0) cout<<"The node "<<node<<" has no successor."<<endl; else { cout<<"The successor of "<<node<<" : "; for(const auto &n:nex) cout<<n<<"\t"; cout<<endl; } } vector<string> Graph::nextTo(string node) { vector<string> successor; if(nodes.find(node)==nodes.end()) return successor; vector<Neighbor> neighbor=edges[node]; for(const auto &n:neighbor) successor.push_back(n.name); return successor; } vector<string> Graph::previousTo(string node) { if(!oriented) return nextTo(node); vector<string> prev; for(const auto &n:nodes) { vector<string> nex=nextTo(n); if(find(nex.begin(),nex.end(),node)!=nex.end()) prev.push_back(n); } return prev; } void Graph::displayPreviousTo(string node) { if(nodes.find(node)==nodes.end()) { NOTFOUND( ) return; } vector<string> prev=previousTo(node); if(prev.size()==0) cout<<"The node "<<node<<" has no previous."<<endl; else { cout<<"The previous of "<<node<<" : "; for(const auto &p:prev) cout<<p<<"\t"; cout<<endl; } } int Graph::getWeight(string node1,string node2) { vector<Neighbor> neighbors=edges[node1]; for(const auto &neighbor:neighbors) { if(neighbor.name==node2) return neighbor.cost; } return 0; } string Graph::miniDistance(map<string,int> &tab) { map<string,int>::iterator it1=tab.begin(); map<string,int>::iterator it2=tab.begin(); while(it1!=tab.end()) { if((it1->second)<(it2->second)) it2=it1; it1++; } return it2->first; } void Graph::dijkstra(string source) { if(nodes.find(source)==nodes.end()) { NOTFOUND() return; } map<string,int>dist1,dist2; set<string> aTraiter(nodes),traiter; for(const auto &n:nodes) dist1[n]=INFINI; dist1[source]=0; while(!aTraiter.empty()) { string x=miniDistance(dist1); traiter.insert(x); aTraiter.erase(find(aTraiter.begin(),aTraiter.end(),x)); for(const auto &y:nextTo(x)) { if(traiter.find(y)==traiter.end()) { int val(dist1[x]+getWeight(x,y)); if(dist1[y]>val) dist1[y]=val; } } dist2[x]=dist1[x]; dist1.erase(dist1.find(x)); } for(const auto &n:dist2) { cout<<source<<"---->"<<n.first; if(n.second<0||n.second==INFINI) cout<<" : INFINI"<<endl; else cout<<" : "<<n.second<<endl; cout<<endl; } } int Graph::Eulerian() { int odd(0); if(oriented) { for(const auto &n:nodes) if(inDegree(n)==outDegree(n)) odd++; } else { for(const auto &n:nodes) // count odd nodes if(degree(n)>0 && degree(n)%2) odd++; } return odd; } void Graph::isEulerian() { int rep=(connected())?Eulerian():3; if(rep==0) cout<<"The graph is Eulerian \n"<<endl; else if(rep==2) cout<<"The graph is Semi Eulerian \n"<<endl; else cout<<"The graph is not Eulerian \n"<<endl; } void Graph::isHamiltonian() { } bool Graph::nIsHamiltonian() { if(nodes.size()<3 && connected()) { cout<<"The graph is Hamiltonian "<<endl; return true; } else if(nodes.size()<3 && !connected()) { cout<<"The graph is not Hamiltonian "<<endl; return false; } return false; } bool Graph::oIsHamiltonian() { bool ok(true); for(const auto &n:nodes) { if(degree(n)<=1) { cout<<"The graph is not Hamiltonian "<<endl; return false; } } return ok; } bool Graph::connected() { int zero(0); // zero-node degree for(const auto &n:nodes) if(!degree(n)) zero++; return (int)connectedComponents().size()== zero+1; } void Graph::isConnected() { if(connected()) cout<<"\nThe graph is connected"<<endl; else cout<<"\nThe graph is not connected"<<endl; } int Graph::outDegree(string node) { if(edges.find(node)!=edges.end()) return edges[node].size(); return 0; } int Graph::inDegree(string node) { if(edges.find(node)!=edges.end()) return previousTo(node).size(); return 0; } vector<string>Graph::bfs(string node) { queue<string>file; map<string,bool>colored; vector<string> path; for(const auto &n:nodes) colored[n]=false; colored[node]=true; file.push(node); while(!file.empty()) { string nex=file.front(); file.pop(); path=nextTo(nex); for(const auto &n:path) { if(!colored[n]) { colored[n]=true; file.push(n); } } } path.clear(); for(const auto &n:colored) if(n.second) // All nodes reachable from node path.push_back(n.first); return path; } void Graph::displayBfs(string node) { if(nodes.find(node)==nodes.end()) { NOTFOUND() return; } vector<string>path=bfs(node); for(const auto &n:path) cout<<n<<"\t"; } /*********** Connected components ********* */ void Graph::dfs(string source,map<string,bool>&colored,vector<string>&compo) { colored[source]=true; compo.push_back(source); vector<string> nex=nextTo(source); vector<string>::iterator i; for(i=nex.begin();i!=nex.end();i++) if(!colored[*i]) dfs(*i,colored,compo); } Graph Graph::getTranspose() { Graph gr(oriented); for(const auto &n:nodes) { vector<string> prev=previousTo(n); for(const auto &pr:prev) gr.addEdge(n,pr,getWeight(pr,n)); } return gr; } void Graph::fillOrder(string node,map<string,bool>&colored,stack<string>&file) { vector<string> neighors=nextTo(node); colored[node]=true; for(const auto &n:neighors) if(!colored[n]) fillOrder(n,colored,file); file.push(node); } map<int,vector<string>>Graph::connectedComponents() { stack<string> file; map<string,bool> colored; for(const auto &n:nodes) colored[n]=false; for(const auto &n:nodes) if(!colored[n]) fillOrder(n,colored,file); Graph gr=getTranspose(); for(const auto &n:nodes) colored[n]=false; int j(1); map<int,vector<string>> components; while(!file.empty()) { string node=file.top(); file.pop(); if(!colored[node]) { vector<string> cp; gr.dfs(node,colored,cp); components[j++]=cp; } } return components; } void Graph::displayComponents() { map<int,vector<string>>components=connectedComponents(); int len=(int) components.size(); if(len==1) cout<<"The only connected component of the graph is: "; else cout<<"The connected components of the graph:\n"<<endl; for(const auto &n:components) { if (len>1) cout<<"Component "<<n.first; cout<<":\t{ "; for(const auto &k:n.second) cout<<k<<" "; cout<<"}"<<endl; } }
true
03ab6f35b8cf499a685a479d52cba01e46124f4f
C++
Divyalok123/LeetCode_Practice
/Practice/PartitionArrayintoDisjointIntervals.cpp
UTF-8
830
3.328125
3
[]
no_license
/* https://leetcode.com/problems/partition-array-into-disjoint-intervals/ */ #include <iostream> #include <algorithm> #include <vector> using namespace std; class Solution { public: int partitionDisjoint(vector<int>& A) { if(A.size() == 2) return 1; int n = A.size(); vector<int> one(n), two(n); int left_max = INT_MIN; for(int i = 0; i < A.size(); i++) { left_max = max(left_max, A[i]); one[i] = left_max; } int right_min = INT_MAX; for(int i = A.size()-1; i >= 0; i--) { right_min = min(A[i], right_min); two[i] = right_min; } int i = 0; while(i < A.size()-1 && one[i] > two[i+1]) i++; return i+1; } };
true
90b4b519177f5e6ceb809205bfba5e23964afc57
C++
benitoab/2PA_TA_benitoab
/Antekeland/src/main.cc
UTF-8
371
2.5625
3
[]
no_license
/** * @file main.cc * @brief Main file of the game. * @details This is the core file. It gathers all classes of the game to make it possible. * @author Ricardo Beltrán Muriel <beltranmu@esat-alumni.com> * @version alfa 1.0 * @date Ded-2020 * @copyright ESAT */ #include"game.h" int main(int argc, char* argv[]){ Game g; /** <Represents the game> */ g.mainGame(); return 0; }
true
4b32ec2952e5d73e02af404a1906e7c1fcf0ded2
C++
angello10/TIL
/BAEKJOON/1920.cpp
UTF-8
398
2.71875
3
[]
no_license
#include <cstdio> #include <algorithm> using namespace std; int main() { int N; scanf("%d", &N); int arr[N]; for (int i = 0;i < N;i++) { scanf("%d", &arr[i]); } sort(arr, arr + N); int M; scanf("%d", &M); for (int i = 0;i < M;i++) { int x; scanf("%d", &x); printf("%d\n", binary_search(arr, arr + N, x)); } return 0; }
true
77693a392a7627c25401b6dc08d93537486ca072
C++
nvurdien/Game-Master
/121-p6-Vurdien-Navie/Nim.h
UTF-8
1,089
2.984375
3
[]
no_license
//Nim Game header: contains all the methods used in the Nim Class. //Navie Vurdien //email: nvurdien@hotmail.com #include <vector> #ifndef NIM_H //if not defined in cpp, else ignore till matching #endif #define NIM_H //define it for cpp class Nim { //globals used in Nim game int g_arraysize;//the array size int g_playrow;//the players row input int g_playpin;//the players pin input std::vector<int> a_game;//the game array public: void setup(); //generates number of rows & pins void prompt(); //response prompt void hello();//gives the prompt (what the game looks like so far) void listen();//gets the how many pins from a row that the user wants to take void change_pins();//changes the number of pins after the player's turn bool is_empty();//checks if the vector is empty void comp_change_pins();//changes the number of pins after the computer's turn void respond();//changes the number of pins in rows void cleanup();//cleans up function bool endchk();//checks if game is done void conversation();//plays the code }; #endif //NIM.H //avoid redef errors
true
97dc4d7acda830b3be17004217514f74a0e31d1b
C++
HeiwaRyuu/Calculadoras
/Multiplicador de Matrizes/Multiplicador de Matrizesz.cpp
UTF-8
2,155
2.734375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <conio.h> double a11,a12,a13,a21,a22,a23,a31,a32,a33,b11,b12,b13,b21,b22,b23,b31,b32,b33,c11,c12,c13,c21,c22,c23,c31,c32,c33,cont; int main(){ do{ system("cls"); printf("\nEntre os valores dos coeficientes da matriz A na ordem a11,a12,a13...:\n"); printf("\nEntre com o valor de a11:\n"); scanf("%lf", &a11); printf("\nEntre com o valor de a12:\n"); scanf("%lf", &a12); printf("\nEntre com o valor de a13:\n"); scanf("%lf", &a13); printf("\nEntre com o valor de a21:\n"); scanf("%lf", &a21); printf("\nEntre com o valor de a22:\n"); scanf("%lf", &a22); printf("\nEntre com o valor de a23:\n"); scanf("%lf", &a23); printf("\nEntre com o valor de a31:\n"); scanf("%lf", &a31); printf("\nEntre com o valor de a32:\n"); scanf("%lf", &a32); printf("\nEntre com o valor de a33:\n"); scanf("%lf", &a33); printf("\nEntre os valores dos coeficientes da matriz B na ordem b11,b12,b13...:\n"); printf("\nEntre com o valor de b11:\n"); scanf("%lf", &b11); printf("\nEntre com o valor de b12:\n"); scanf("%lf", &b12); printf("\nEntre com o valor de b13:\n"); scanf("%lf", &b13); printf("\nEntre com o valor de b21:\n"); scanf("%lf", &b21); printf("\nEntre com o valor de b22:\n"); scanf("%lf", &b22); printf("\nEntre com o valor de b23:\n"); scanf("%lf", &b23); printf("\nEntre com o valor de b31:\n"); scanf("%lf", &b31); printf("\nEntre com o valor de b32:\n"); scanf("%lf", &b32); printf("\nEntre com o valor de b33:\n"); scanf("%lf", &b33); c11=(a11*b11+a12*b21+a13*b31); c12=(a11*b12+a12*b22+a13*b32); c13=(a11*b13+a12*b23+a13*b33); c21=(a21*b11+a22*b21+a23*b31); c22=(a21*b12+a22*b22+a23*b32); c23=(a21*b13+a22*b23+a23*b33); c31=(a31*b11+a32*b21+a33*b31); c32=(a31*b12+a32*b22+a33*b32); c33=(a31*b13+a32*b23+a33*b33); printf("\nA matriz C resultado sera = \n|%lf %lf %lf|\n|%lf %lf %lf|\n|%lf %lf %lf|\n",c11,c12,c13,c21,c22,c23,c31,c32,c33); printf("\nSe deseja reutilizar o programa entre 1, caso deseje sair entre 2.\n"); scanf("%lf",&cont); }while(cont==1); printf("\nVoce saiu do programa entre qualquer tecla para prosseguir.\n"); getch(); return 0; }
true
10d6bf5e7a2f08eafc1d793b722322754b7333a3
C++
Sunghwan-Cho-Digipen/cs280_COB_LAB
/Lab6/Game/ClashOfBlocks.cpp
UTF-8
2,638
2.921875
3
[]
no_license
/*-------------------------------------------------------------- Copyright (C) 2020 DigiPen Institute of Technology. Reproduction or disclosure of this file or its contents without the prior written consent of DigiPen Institute of Technology is prohibited. File Name: ClashOfBlocks.cpp Purpose: Source file for ClashOfBlocks Project: CS280 Lab 6 - Clash Of Blocks Author: Sunghwan Cho Creation date: 04/21/2021 -----------------------------------------------------------------*/ #include "ClashOfBlocks.h" #include "Cell.h" #include "Image_Anims.h" bool ClashOfBlocks::Visit() { if (toVisit.empty() == false) { const int TO_VISIT_SIZE = static_cast<int>(toVisit.size()); for (int i = 0; i < TO_VISIT_SIZE; ++i) { const Vector2DInt CURRENT_POSITION = toVisit.front().cellPos; const int CURRENT_STEP = toVisit.front().step; const Images IMAGE_OF_PLAYER = toVisit.front().imageToUse; toVisit.pop_front(); Cell* cell = board->GetCell(CURRENT_POSITION); if (CURRENT_STEP != 0 && cell->GetImage() != Images::None) { continue; } cell->SetToImage(IMAGE_OF_PLAYER); const ToVisit UPWARD{ CURRENT_POSITION + Vector2DInt{ 0,1 },CURRENT_STEP + 1 ,IMAGE_OF_PLAYER }; const ToVisit RIGHTWARD{ CURRENT_POSITION + Vector2DInt{ 1,0 },CURRENT_STEP + 1 ,IMAGE_OF_PLAYER }; const ToVisit DOWNWARD{ CURRENT_POSITION + Vector2DInt{ 0,-1 },CURRENT_STEP + 1 ,IMAGE_OF_PLAYER }; const ToVisit LEFTWARD{ CURRENT_POSITION + Vector2DInt{ -1,0 },CURRENT_STEP + 1 ,IMAGE_OF_PLAYER }; if (TryToAdd(UPWARD) == true) { toVisit.emplace_back(UPWARD); } if (TryToAdd(RIGHTWARD) == true) { toVisit.emplace_back(RIGHTWARD); } if (TryToAdd(DOWNWARD) == true) { toVisit.emplace_back(DOWNWARD); } if (TryToAdd(LEFTWARD) == true) { toVisit.emplace_back(LEFTWARD); } } return false; } return true; } void ClashOfBlocks::PlayerSelected(Vector2DInt cellLocation) { toVisit.clear(); Cell* currentCell = board->GetCell(cellLocation); currentCell->SetToImage(Images::RedX); toVisit.emplace_back(ToVisit{ cellLocation ,0,Images::Red }); for (const Vector2DInt& AI_POSITION : board->GetAIStartSpots()) { const Images IMAGE_OF_AI = static_cast<Images>(static_cast<int>(board->GetCell(AI_POSITION)->GetImage()) - 1); // from the assignment explanation toVisit.emplace_back(ToVisit{ AI_POSITION ,0,IMAGE_OF_AI }); } } bool ClashOfBlocks::TryToAdd(ToVisit tryToAdd) { Cell* cell = board->GetCell(tryToAdd.cellPos); if (cell == nullptr) { return false; } if (cell->GetImage() != Images::None) { return false; } return true; }
true
6335e213b63d7dbb7cf895ac4d28ddfbb72225d1
C++
nabil-k/Mondlitch
/Enemy.h
UTF-8
5,931
3.078125
3
[]
no_license
#pragma once #include <math.h> #include <vector> #include <SFML/Graphics.hpp> #include "TextureManager.h" #include "Platform.h" class Enemy { int width, height; float pos_x, pos_y; float vel_x, vel_y; bool top_collision, bottom_collision, left_collision, right_collision; float gravity = 32; bool fall = true; TextureManager* textureManager; sf::Sprite sprite; // for animations sf::Clock animateTime; float maxKeyframeTime; float timeSinceLastKeyframe; float walkFrame; public: int getWidth(), getHeight(); float getX(), getY(); float getVelocityX(); bool canMoveLeft, canMoveRight; void moveLeft(); void moveRight(); sf::Sprite getSprite(); void changeSpriteTexture(); void update(std::vector<Platform> levelPlatforms); Enemy(float x, float y, TextureManager* textureManager) { pos_x = x; pos_y = y; width = 15; height = 20; vel_x = 0; vel_y = 0; maxKeyframeTime = 0.5; canMoveLeft = false; canMoveRight = true; this->textureManager = textureManager; sprite.setTexture(textureManager->getEnemyTexture(0)); sprite.setOrigin({ 0, 0 }); sprite.setPosition(sf::Vector2f(pos_x, pos_y)); } }; int Enemy::getWidth() { return width; } int Enemy::getHeight() { return height; } float Enemy::getX() { return pos_x; } float Enemy::getY() { return pos_y; } float Enemy::getVelocityX() { return vel_x; } void Enemy::moveLeft() { if (vel_x > -1) { vel_x += -gravity * 0.001802f; } pos_x += vel_x; } void Enemy::moveRight() { if (vel_x < 1) { vel_x += gravity * 0.001802f; } pos_x += vel_x; } void Enemy::changeSpriteTexture() { timeSinceLastKeyframe = animateTime.getElapsedTime().asSeconds(); // Flips sprite based on if they're moving left/right if (vel_x > 0) { sprite.setOrigin({ 0, 0 }); sprite.setScale({ 1, 1 }); } else if (vel_x < 0) { sprite.setOrigin({ sprite.getLocalBounds().width, 0 }); sprite.setScale({ -1, 1 }); } // When enemy is on the ground if (vel_y == 0) { if (vel_x == 0) { sprite.setTexture(textureManager->getEnemyTexture(0)); } else if (vel_x > 0 || vel_x < 0) { if (timeSinceLastKeyframe > (maxKeyframeTime - (std::abs(vel_x) * .3))) { ++walkFrame; if (walkFrame > 3) { walkFrame = 1; } sprite.setTexture(textureManager->getEnemyTexture(walkFrame)); animateTime.restart(); } } } } void Enemy::update(std::vector<Platform> levelPlatforms) { // Controls how player falls if (fall) { if (vel_y < 10) { vel_y += gravity * 0.001802f * 2; } pos_y += vel_y; sprite.move(0.f, vel_y); } if (canMoveLeft) { moveLeft(); } if (canMoveRight) { moveRight(); } // Player's hitbox float leftX = pos_x; float rightX = (pos_x + width); float topY = pos_y; float bottomY = pos_y + height; // Tracks if player can move in a certain direction bool playerTouchedBottom = false; float adjustment; // Player Collision Detection bool leftXCollission, rightXCollision, topYCollision, bottomYCollision; for (auto &platform : levelPlatforms) { if (platform.isCollidable()) { leftXCollission = (leftX > platform.getX()) && (leftX < (platform.getX() + platform.getWidth())); rightXCollision = (rightX > platform.getX()) && (rightX < (platform.getX() + platform.getWidth())); topYCollision = (topY > platform.getY()) && (topY < (platform.getY() + platform.getHeight())); bottomYCollision = (bottomY > platform.getY() && (bottomY < platform.getY() + platform.getHeight())); // Checks bottom collisions if (vel_y > 0) { float leftXCollission_bottom = (leftX + 1 > platform.getX()) && (leftX + 1 < (platform.getX() + platform.getWidth())); float rightXCollision_bottom = (rightX - 1 > platform.getX()) && (rightX - 1 < (platform.getX() + platform.getWidth())); if (bottomYCollision && (rightXCollision_bottom || leftXCollission_bottom)) { float adjustment = platform.getY() - height; playerTouchedBottom = true; pos_y = adjustment; bottomY = pos_y + height; vel_y = 0; sprite.setPosition(pos_x, adjustment); } } // Checks top collisions if (vel_y < 0) { float leftXCollission_bottom = (leftX + 1 > platform.getX()) && (leftX + 1 < (platform.getX() + platform.getWidth())); float rightXCollision_bottom = (rightX - 1 > platform.getX()) && (rightX - 1 < (platform.getX() + platform.getWidth())); if (topYCollision && (rightXCollision_bottom || leftXCollission_bottom)) { float adjustment = platform.getY() + platform.getHeight(); pos_y = adjustment; topY = pos_y; vel_y = 0; sprite.setPosition(pos_x, adjustment); } } // Checks left collisions if (vel_x < 0) { if (leftXCollission) { bool checkTopYPlatInBetween = platform.getY() > topY && platform.getY() + 1 < bottomY; bool checkBottomYPlatInBetween = platform.getY() + platform.getHeight() > topY && platform.getY() + platform.getHeight() < bottomY; if (checkTopYPlatInBetween || checkBottomYPlatInBetween) { pos_x = platform.getX() + platform.getWidth(); leftX = pos_x; sprite.setPosition(pos_x, pos_y); vel_x = 0; canMoveLeft = false; canMoveRight = true; } } } // Checks right collisions if (vel_x > 0) { if (rightXCollision) { bool checkTopYPlatInBetween = platform.getY() > topY && platform.getY() + 1 < bottomY; bool checkBottomYPlatInBetween = platform.getY() + platform.getHeight() > topY && platform.getY() + platform.getHeight() < bottomY; if (checkTopYPlatInBetween || checkBottomYPlatInBetween) { pos_x = platform.getX() - width; rightX = (pos_x + width); sprite.setPosition(pos_x, pos_y); vel_x = 0; canMoveLeft = true; canMoveRight = false; } } } if (!playerTouchedBottom) { fall = true; } } changeSpriteTexture(); } } sf::Sprite Enemy::getSprite(){ return sprite; }
true
b9d2327c03c128b20fb4871d2752c7d29c5da471
C++
dangerous66/C-
/fraction/fraction.h
UTF-8
905
3.296875
3
[]
no_license
#pragma once int min(int a,int b) { if (a < b) { return a; } else { return b; } } int max(int a, int b) { if (a > b) { return a; } else { return b; } } class Fraction { private: int m_numerator; int m_denominator; int common_denomintor(Fraction b) { for (int i = max(m_denominator,b.m_denominator); i <= m_denominator * b.m_denominator; i++) { if (i%m_denominator == 0 && i%b.m_denominator == 0) { return i; } } } int gcd() { for (int i = min(m_denominator,m_numerator); i >=1; i--) { if (m_denominator%i == 0 && m_numerator%i == 0) { return i; } } } Fraction common_sum(Fraction b) { return Fraction(m_numerator+b.m_numerator,b.m_denominator); } public: Fraction(); Fraction(int numerator,int denominator); Fraction operator+(Fraction b); void show(); };
true
df15c7bbf3b1936715d79f897484167610295934
C++
lava/lexy
/include/lexy/dsl/recover.hpp
UTF-8
6,064
2.5625
3
[ "BSL-1.0" ]
permissive
// Copyright (C) 2020-2021 Jonathan Müller <jonathanmueller.dev@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #ifndef LEXY_DSL_RECOVER_HPP_INCLUDED #define LEXY_DSL_RECOVER_HPP_INCLUDED #include <lexy/dsl/alternative.hpp> #include <lexy/dsl/base.hpp> #include <lexy/dsl/choice.hpp> #include <lexy/dsl/eof.hpp> #include <lexy/engine/find.hpp> namespace lexyd { template <typename Token, typename Limit> struct _find : rule_base { template <typename NextParser> struct parser { template <typename Context, typename Reader, typename... Args> LEXY_DSL_FUNC bool parse(Context& context, Reader& reader, Args&&... args) { using engine = lexy::engine_find_before<typename Token::token_engine, typename Limit::token_engine>; if (engine::match(reader) != typename engine::error_code()) return false; return NextParser::parse(context, reader, LEXY_FWD(args)...); } }; //=== dsl ===// /// Fail error recovery if limiting token is found first. template <typename... Tokens> LEXY_CONSTEVAL auto limit(Tokens... tokens) const { static_assert(sizeof...(Tokens) > 0); static_assert((lexy::is_token<Tokens> && ...)); auto l = (Limit{} / ... / tokens); return _find<Token, decltype(l)>{}; } LEXY_CONSTEVAL auto get_limit() const { return Limit{}; } }; template <typename Token> struct _find<Token, void> : rule_base { template <typename NextParser> struct parser { template <typename Context, typename Reader, typename... Args> LEXY_DSL_FUNC bool parse(Context& context, Reader& reader, Args&&... args) { using engine = lexy::engine_find<typename Token::token_engine>; if (engine::match(reader) != typename engine::error_code()) return false; return NextParser::parse(context, reader, LEXY_FWD(args)...); } }; //=== dsl ===// /// Fail error recovery if limiting token is found first. template <typename... Tokens> LEXY_CONSTEVAL auto limit(Tokens... tokens) const { static_assert(sizeof...(Tokens) > 0); static_assert((lexy::is_token<Tokens> && ...)); auto l = (tokens / ...); return _find<Token, decltype(l)>{}; } LEXY_CONSTEVAL auto get_limit() const { return eof; } }; /// Recovers once it finds one of the given tokens (without consuming them). template <typename... Tokens> LEXY_CONSTEVAL auto find(Tokens... tokens) { static_assert(sizeof...(Tokens) > 0); static_assert((lexy::is_token<Tokens> && ...)); auto needle = (tokens / ...); return _find<decltype(needle), void>{}; } } // namespace lexyd namespace lexyd { template <typename Limit, typename... R> struct _reco : rule_base { template <typename NextParser> struct parser { template <typename Context, typename Reader, typename... Args> LEXY_DSL_FUNC bool parse(Context& context, Reader& reader, Args&&... args) { while (true) { // Try to match the recovery rules. using recovery = lexy::rule_parser<_chc<R...>, NextParser>; auto result = recovery::try_parse(context, reader, LEXY_FWD(args)...); if (result != lexy::rule_try_parse_result::backtracked) // We've succesfully recovered; return the recovered result. return static_cast<bool>(result); // Cancel recovery when we've reached the limit. if (lexy::engine_peek<typename Limit::token_engine>(reader)) return false; // Consume one character and try again. reader.bump(); } return false; // unreachable } }; //=== dsl ===// /// Fail error recovery if Token is found before any of R. template <typename... Tokens> LEXY_CONSTEVAL auto limit(Tokens... tokens) const { static_assert(sizeof...(Tokens) > 0); static_assert((lexy::is_token<Tokens> && ...)); auto l = (Limit{} / ... / tokens); return _reco<decltype(l), R...>{}; } LEXY_CONSTEVAL auto get_limit() const { return Limit{}; } }; /// Discards input until one of the branches matches to recover from an error. template <typename... Branches> LEXY_CONSTEVAL auto recover(Branches...) { static_assert(sizeof...(Branches) > 0); static_assert((lexy::is_branch<Branches> && ...)); return _reco<lexyd::_eof, Branches...>{}; } } // namespace lexyd namespace lexyd { template <typename Rule, typename Recover> struct _tryr : rule_base { template <typename NextParser> struct parser { template <typename Context, typename Reader, typename... Args> LEXY_DSL_FUNC bool parse(Context& context, Reader& reader, Args&&... args) { if (lexy::rule_parser<Rule, NextParser>::parse(context, reader, LEXY_FWD(args)...)) // The rule was parsed succesfully, we're done here. return true; else { if constexpr (std::is_void_v<Recover>) return NextParser::parse(context, reader, LEXY_FWD(args)...); else return lexy::rule_parser<Recover, NextParser>::parse(context, reader, LEXY_FWD(args)...); } } }; }; /// Pares Rule, if that fails, continues immediately. template <typename Rule> LEXY_CONSTEVAL auto try_(Rule) { return _tryr<Rule, void>{}; } /// Parses Rule, if that fails, parses recovery rule. template <typename Rule, typename Recover> LEXY_CONSTEVAL auto try_(Rule, Recover) { return _tryr<Rule, Recover>{}; } } // namespace lexyd #endif // LEXY_DSL_RECOVER_HPP_INCLUDED
true
6aa5bb33aeb6d15dc451f43de3ca6342eea990a4
C++
TommyPlayer-c/Cplusplus_SimpleSTL
/test_vector.cpp
UTF-8
418
2.71875
3
[]
no_license
#include <iostream> #include "./list.h" #include "./vector.h" #include "./memory.h" using namespace std; using namespace SimpleSTL; int main() { vector<int> v(2, 9); cout << v[0] << " " << v[1] << " " << v[2] << endl; cout << v.size() << endl; cout << v.capacity() << endl; v.push_back(1034); cout << v.back() << endl; cout << v.size() << endl; cout << v.capacity() << endl; }
true
fa4387095e6c8890a111bd0f0c5613e11183da13
C++
sophiepeneva/Expressions
/Sum.cpp
UTF-8
595
3.515625
4
[]
no_license
# Expressions #include "Sum.h" Sum::Sum(Expression* firstExp, Expression* secondExp) { firstExpression = firstExp; secondExpression = secondExp; } Sum& Sum::operator=(const Sum& s) { if(this!=&s) { Destroy(); CopyFrom(s); } return *this; } void Sum::CopyFrom(const Sum& s) { firstExpression = s.firstExpression; secondExpression = s.secondExpression; } void Sum::print() const { std::cout << "("; firstExpression->print(); std::cout << " + "; secondExpression->print(); std::cout << ")"; } void Sum::Destroy() { delete[] firstExpression; delete[] secondExpression; }
true
43fde34c70cda85cb03c447c70bc3cc693f7f538
C++
godilopa/AI
/Project1/practicas steering/src/Path.cpp
ISO-8859-10
2,618
3.03125
3
[]
no_license
#include <stdafx.h> #include "../include/Path.h" #include <moaicore/MOAIEntity2D.h> Path::Path(){ } Path::~Path(){ } void Path::DrawPath() { USVec2D pointA = mPoints[0]; for (int i = 1; i < mPoints.size(); i++) { USVec2D pointB = mPoints[i]; MOAIGfxDevice& gfxDevice = MOAIGfxDevice::Get(); gfxDevice.SetPenColor(1.0f, 0.0f, 1.0f, 0.5f); MOAIDraw::DrawLine(pointA.mX, pointA.mY, pointB.mX, pointB.mY); pointA = pointB; } } /*Calculo la distancia al punto mas cercano de cada segmento devolviendo el mas cercano entre todos los segmentos */ USVec2D Path::GetNearestPathPosition(USVec2D position) { USVec2D pointA = mPoints[0]; float minorDistance = 10000000; float distance; USVec2D nearestPoint; for (int i = 1; i < mPoints.size(); i++) { USVec2D pointB = mPoints[i]; float k = ((position.mX - pointA.mX)*(pointB.mX - pointA.mX) + (position.mY - pointA.mY)*(pointB.mY - pointA.mY)) / ((pointB.mX - pointA.mX)*(pointB.mX - pointA.mX) + (pointB.mY - pointA.mY) *(pointB.mY - pointA.mY)); //Point is in Segment if (k < 1 && k > 0) { USVec2D v = pointA + (pointB - pointA) * k; distance = (v - position).LengthSquared(); if (distance < minorDistance) { minorDistance = distance; nearestPoint = v; activeSegment = i; } } else if (k >= 1) { //point is B USVec2D v = pointB - position; distance = v.LengthSquared(); if (distance < minorDistance) { minorDistance = distance; nearestPoint = pointB; activeSegment = i; } } else { //point is A USVec2D v = pointA - position; distance = v.LengthSquared(); if (distance < minorDistance) { minorDistance = distance; nearestPoint = pointA; activeSegment = i; } } pointA = pointB; } return nearestPoint; } USVec2D Path::GetNextPathPosition(USVec2D position, float progress){ USVec2D pointA = mPoints[activeSegment - 1]; USVec2D pointB = mPoints[activeSegment]; USVec2D dir = (pointB - pointA).NormSafe() * progress; float lengthToB = (pointB - position).Length(); //Si el tamao a avanzar es mayor de o que queda hasta B pasamos la siguiente segmento if (progress > lengthToB) { //Si estamos en el ultimo segmento no sumamos mas llegamos al ultimo punto if (activeSegment == mPoints.size() - 1) { return pointB; } else { float distanceOverlap = progress - lengthToB; //Cogemos el siguiente segmento y le sumamos lo que nos pasamos pointA = mPoints[activeSegment]; pointB = mPoints[activeSegment + 1]; dir = (pointB - pointA).NormSafe() * distanceOverlap; return pointA + dir; } } else { return position + dir; } }
true
16efaaf0ef8a3878c63500d77906961a00f2ff74
C++
KernelPanic-OpenSource/Win2K3_NT_drivers
/wdm/audio/filters/kmixer/rfcvec.inl
UTF-8
4,104
2.625
3
[]
no_license
/*++ Copyright (c) 1998-2000 Microsoft Corporation. All Rights Reserved. Module Name: rfcrcvec.inl Abstract: This includes the inline functions for the real float circular vector Author: Jay Stokes (jstokes) 22-Apr-1998 --*/ #if !defined(RFCVEC_INLINE) #define RFCVEC_INLINE #pragma once // --------------------------------------------------------------------------- // Make sure inlines are out-of-line in debug version #if !DBG #define INLINE __forceinline #else // DBG #define INLINE #endif // DBG // --------------------------------------------------------------------------- // Real FLOAT circular vector // "Regular" constructor INLINE NTSTATUS RfcVecCreate ( IN PRFCVEC* Vec, IN UINT Size, IN BOOL Initialize, IN FLOAT InitValue ) { NTSTATUS Status = STATUS_SUCCESS; ASSERT(Size > 0); *Vec = ExAllocatePoolWithTag( PagedPool, Size*sizeof(FLOAT), 'XIMK'); if (*Vec) { RfcVecFullInit(*Vec, Size, InitValue); } else { Status = STATUS_INSUFFICIENT_RESOURCES; } return(Status); } // Destructor INLINE VOID RfcVecDestroy ( PRFCVEC Vec ) { if (Vec) { if(Vec->Start) { ExFreePool(Vec->Start); } Vec->Start = NULL; ExFreePool(Vec); } } // Get buffer size INLINE UINT RfcVecGetSize ( PRFCVEC Vec ) { return (UINT)((Vec->End - Vec->Start) + 1); } // Read item LIFO, advance buffer pointer, wrap around if necessary INLINE FLOAT RfcVecLIFORead ( PRFCVEC Vec ) { return RfcVecPreviousRead(Vec); } // Read item FIFO, advance buffer pointer, wrap around if necessary INLINE FLOAT RfcVecFIFORead ( PRFCVEC Vec ) { return RfcVecReadNext(Vec); } // Write item, advance buffer pointer, wrap around if necessary INLINE VOID RfcVecWrite ( PRFCVEC Vec, FLOAT Value ) { RfcVecWriteNext(Vec, Value); } // Read item from current buffer position (decremented before item was read) INLINE FLOAT RfcVecPreviousRead ( PRFCVEC Vec ) { // CHECK_POINTER(Vec->Index); RfcVecLIFONext(Vec); return *Vec->Index; } // Read item from current buffer position (decremented before item was read) INLINE FLOAT RfcVecReadNext ( PRFCVEC Vec ) { FLOAT Value; ASSERT(Vec->Index); Value = *(Vec->Index); RfcVecFIFONext(Vec); return Value; } // Write item to current buffer position (incremented after item is written) INLINE VOID RfcVecWriteNext ( PRFCVEC Vec, FLOAT Value ) { ASSERT(Vec->Index); *Vec->Index = Value; RfcVecSkipForward(Vec); } // Increments current buffer position by one, wraps around if necessary INLINE VOID RfcVecFIFONext ( PRFCVEC Vec ) { // Wrap around if necessary if (++Vec->Index > Vec->End) Vec->Index = Vec->Start; } // Skip forward one element INLINE VOID RfcVecSkipForward ( PRFCVEC Vec ) { RfcVecFIFONext(Vec); } // Decrements current buffer position by one, wraps around if necessary INLINE VOID RfcVecLIFONext ( PRFCVEC Vec ) { // Wrap around if necessary if (--Vec->Index < Vec->Start) Vec->Index = Vec->End; } // Skip back one element INLINE VOID RfcVecSkipBack ( PRFCVEC Vec ) { RfcVecLIFONext(Vec); } // Get current index INLINE UINT RfcVecGetIndex ( PRFCVEC Vec ) { return (UINT)(Vec->Index - Vec->Start); } // Set current index INLINE VOID RfcVecSetIndex ( PRFCVEC Vec, UINT Index ) { ASSERT(Index < RfcVecGetSize(Vec)); Vec->Index = Vec->Start + Index; } // Set end pointer INLINE VOID RfcVecSetEndPointer ( PRFCVEC Vec, UINT Size ) { Vec->End = Vec->Start + Size - 1; } // Fill with contents from other buffer, // updating indices but not touching lengths (LIFO) INLINE VOID RfcVecLIFOFill ( PRFCVEC Vec, PRFCVEC rhs ) { // RfcVecWriteLoop(Vec, rhs, RfcVecLIFORead); } // Fill with contents from other buffer, // updating indices but not touching lengths (FIFO) INLINE VOID RfcVecFIFOFill ( PRFCVEC Vec, PRFCVEC rhs ) { // RfcVecWriteLoop(Vec, rhs, RfcVecFIFORead); } #endif // End of RFCVEC.INL
true
97941297647742243ee422777ce18ad4635c4474
C++
yue-w/HelloWorld
/UnitTest/TestDataParse.cpp
UTF-8
3,362
2.796875
3
[]
no_license
#include <gtest\gtest.h> #include "../Core/DataParser.h" #include "../Core/DataWrapper.h" #include "../Core/OptimizationData.h" #include "../Core/CommonFunc.h" namespace Core { TEST(Test_DataParser, TestGrad) { //Prepare data wrapper. DataWrapper data; data.Add("varName1", "x1"); data.Add("lowBnd1", "0"); data.Add("upBnd1", "1"); data.Add("initVal1", "0.5"); data.Add("grad1", "2*x1+1.11"); data.Add("varName2", "x2"); data.Add("lowBnd2", "0"); data.Add("upBnd2", "1"); data.Add("initVal2", "0.5"); data.Add("grad2", "2*x2+2.12"); //Parse. DataParser parser(&data); parser.Parse(); auto optData = parser.GetParsedData(); ASSERT_EQ(2, optData.VarCount()); auto varData = optData.GetVarData(2); ASSERT_EQ("2*x2+2.12", varData.Grad()); } TEST(Test_DataParser, ComputeVarCountCorrectly) { //Prepare data wrapper. DataWrapper data; data.Add("varName1", "x1"); data.Add("varName2", "x2"); data.Add("varName3", "x3"); //Parse. DataParser parser(&data); parser.Parse(); auto optData = parser.GetParsedData(); auto varData = optData.GetVarData(3); ASSERT_EQ("x3", varData.VarName()); ASSERT_EQ(3, optData.VarCount()); } TEST(Test_DataParser, ParseLowerBoundAndUpperBound) { //Prepare data wrapper. DataWrapper data; data.Add("varName1", "x1"); data.Add("lowBnd1", "0"); data.Add("upBnd1", "1"); data.Add("initVal1", "0.5"); data.Add("varName2", "x2"); //Parse. DataParser parser(&data); parser.Parse(); auto optData = parser.GetParsedData(); ASSERT_EQ(2, optData.VarCount()); auto varData = optData.GetVarData(1); ASSERT_EQ("x1", varData.VarName()); ASSERT_EQ(0, varData.Lb()); ASSERT_EQ(1, varData.Ub()); ASSERT_EQ(0.5, varData.InitVal()); } TEST(Test_DataParser, SomeValuesAreOptional) { //Prepare data wrapper with no upper bound and lower bound. DataWrapper data; data.Add("varName1", "x1"); data.Add("initVal1", "0.5"); //Parse. DataParser parser(&data); parser.Parse(); auto optData = parser.GetParsedData(); ASSERT_EQ(1, optData.VarCount()); auto varData = optData.GetVarData(1); ASSERT_EQ("x1", varData.VarName()); ASSERT_EQ(0.5, varData.InitVal()); ASSERT_EQ(DEFAULT_DOUBLE, varData.Lb());//lower bound is a default double. ASSERT_EQ(DEFAULT_DOUBLE, varData.Ub()); } TEST(Test_DataParser, VarCountIsDeterminedByVarName) { //Prepare data wrapper. DataWrapper data; data.Add("varName1", "x1"); data.Add("initVal1", "0.5"); //Add another var without a Var name. data.Add("lowBnd2", "0"); data.Add("upBnd2", "1"); data.Add("initVal2", "0.5"); //Parse. DataParser parser(&data); parser.Parse(); auto optData = parser.GetParsedData(); //Then there is only one var. ASSERT_EQ(1, optData.VarCount()); } TEST(Test_DataParser, ParseObjFunc) { //Prepare data wrapper. DataWrapper data; data.Add("objFunc", "x1*x1"); //Parse. DataParser parser(&data); parser.Parse(); auto optData = parser.GetParsedData(); ASSERT_EQ("x1*x1", optData.GetObjFunc()); } TEST(Test_DataParser, ObjFuncIsDefaultValueIfThereIsNoFuncInDataWrapper) { //Prepare data wrapper. DataWrapper data; data.Add("varName", "x1"); //Parse. DataParser parser(&data); parser.Parse(); auto optData = parser.GetParsedData(); ASSERT_EQ(DEFAULT_STRING, optData.GetObjFunc()); } }
true
cc52b6b2f2084186126619f6eb5dc002a625efd9
C++
ChiaYi-LIN/Computer-Programming
/PSA13/PSA13_b04704016/b04704016_p1.cpp
UTF-8
1,827
3.46875
3
[]
no_license
#include <iostream> #include <string> using namespace std; class Point{ public: Point(int a=0, int b=0){x=a; y=b;} int x, y; }; class Figure{ public: Figure(){ next = 0; } virtual float area(){ return 0; } void link(Figure *pFigure){ next = pFigure; } Figure *getLink(){ return next; } protected: Figure *next; }; class LineSegment : public Point, public Figure{ public: LineSegment(int x1=0, int y1=0, int x2=0, int y2=0) : Figure(){ //set point p1.x=x1; p1.y=y1; p2.x=x2; p2.y=y2; } float area(){return 0;} protected: Point p1, p2; }; class Rectangle : public Point, public Figure{ public: Rectangle(int x1=0, int y1=0, int x2=0, int y2=0): Figure(){ //set point topLeft.x=x1; topLeft.y=y1; bottomRight.x=x2; bottomRight.y=y2; } float area(){ return (bottomRight.x-topLeft.x)*(bottomRight.y-topLeft.y); } protected: Point topLeft, bottomRight; }; class Ellipse : public Point, public Figure{ public: Ellipse(int x1=0, int y1=0, int x2=0, int y2=0):PI(3.14159), Figure(){ //set point center.x=x1; center.y=y1; axis.x=x2; axis.y=y2; } float area(){ return PI*(axis.x-center.x)*(axis.y-center.y); } protected: Point center, axis; const float PI; }; int main()//don't modify main() { int i=0; string nameFigure[3]={"Line", "Rectangle", "Ellipse"}; LineSegment line(1,1, 10, 10); Rectangle rect(10, 10, 90, 50); Ellipse ellipse(30, 30, 40, 40); Figure *pBase; rect.link( &ellipse ); line.link( &rect ); pBase = &line; while( pBase ) { cout <<nameFigure[i]<< " area = " << pBase->area() << endl; pBase = pBase->getLink(); i++; } }
true
060a643d3f5bdc2cf4b72282b04c152dc571d4b5
C++
Masahiro-Obuchi/Atcoder
/ABC/ABC149/ABC149C.cpp
UTF-8
1,055
3.296875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; bool is_prime(const unsigned n) { switch (n) { case 0: // fall-through case 1: return false; case 2: // fall-through case 3: return true; } // n > 3 が保証された if (n % 2 == 0) return false; if (n % 3 == 0) return false; // 2と3の倍数でないので6の倍数ではないことが保証された if (n % 6 != 1 && n % 6 != 5) return false; // 6の倍数前後の数(素数かもしれない数)であることが保証された // 6の倍数前後の数を使って試し割りをする for (unsigned i = 5; i * i <= n; i += 6) { if (n % i == 0) return false; // 6n-1 if (n % (i + 2) == 0) return false; // 6n+1 } return true; } int main() { long long int X; cin >> X; long long int ans = 0; bool ok = false; while (!ok) { if (is_prime(X)) { ans = X; ok = true; break; } else X++; } cout << ans << endl; }
true
5e8ecbe1181a0b83488a72d516971878d438f316
C++
astateful/dyplat
/lib/bson/src/JSON.cpp
UTF-8
10,405
2.84375
3
[ "BSD-3-Clause" ]
permissive
#include "astateful/bson/JSON.hpp" #include "astateful/bson/Element/String.hpp" #include "astateful/bson/Element/Int.hpp" #include "astateful/bson/Element/Null.hpp" #include "astateful/bson/Element/Bool.hpp" #include "astateful/bson/Element/Double.hpp" #include "astateful/bson/Serialize.hpp" #include <locale> #include <algorithm> #include <cassert> #include <iostream> namespace astateful { namespace bson { namespace json { namespace { enum class state_e { UNKNOWN, KEY, SPLIT, VAL_UNKNOWN, VAL_STRING, VAL_ARRAY, VAL_OBJECT }; bool is_integer( const std::string& input ) { if ( input.empty() ) return false; const auto& first = input[0]; if ( ( !isdigit( first ) ) && ( first != '-') && ( first != '+' ) ) return false; char * test_conv; strtol( input.c_str(), &test_conv, 10 ); return ( *test_conv == 0 ); } bool is_double( const std::string& input ) { char* test_conv = 0; strtod( input.c_str(), &test_conv ); if ( *test_conv != '\0' || test_conv == input.c_str() ) return false; return true; } void store_value( bool is_array, Serialize& serialize, int& array_key, std::string& key, std::string& value, state_e& state ) { if ( is_integer( value ) ) { if (is_array) { serialize.append( ElementInt( std::to_string( array_key ), value ) ); value = ""; ++array_key; state = state_e::VAL_UNKNOWN; } else { serialize.append( ElementInt( key, value ) ); value = ""; key = ""; state = state_e::UNKNOWN; } } else if ( is_double( value ) ) { if (is_array) { serialize.append( ElementDouble( std::to_string( array_key ), value ) ); value = ""; ++array_key; state = state_e::VAL_UNKNOWN; } else { serialize.append( ElementDouble( key, value ) ); value = ""; key = ""; state = state_e::UNKNOWN; } } else if ( value == "null" ) { if (is_array) { serialize.append( ElementNull( std::to_string( array_key ) ) ); value = ""; ++array_key; state = state_e::VAL_UNKNOWN; } else { serialize.append( ElementNull( key ) ); value = ""; key = ""; state = state_e::UNKNOWN; } } else if ( value == "true" || value == "false" ) { bool bool_value = ( value == "true" ) ? true : false; if (is_array) { serialize.append( ElementBool( std::to_string( array_key ), bool_value ) ); value = ""; ++array_key; state = state_e::VAL_UNKNOWN; } else { serialize.append( ElementBool( key , bool_value ) ); value = ""; key = ""; state = state_e::UNKNOWN; } } } Serialize parse( const std::string& input, error_e& error, state_e start_state, bool is_array ) { Serialize serialize; std::string value; std::string key; auto state = start_state; int array_key = 0; int depth = 0; for ( const auto& i : input ) { switch ( i ) { case '{': switch ( state ) { case state_e::UNKNOWN: break; case state_e::KEY: key += i; break; case state_e::SPLIT: break; case state_e::VAL_UNKNOWN: state = state_e::VAL_OBJECT; ++depth; value += i; break; case state_e::VAL_STRING: break; case state_e::VAL_ARRAY: value += i; break; case state_e::VAL_OBJECT: ++depth; value += i; break; } break; case '}': switch ( state ) { case state_e::UNKNOWN: break; case state_e::KEY: key += i; break; case state_e::SPLIT: break; case state_e::VAL_UNKNOWN: break; case state_e::VAL_STRING: break; case state_e::VAL_ARRAY: value += i; break; case state_e::VAL_OBJECT: --depth; value += i; if ( depth == 0 ) { auto reduced = value.substr( 1, value.size() - 2 ); auto sub = parse( reduced, error, state_e::UNKNOWN, false ); auto t_key = ( is_array ) ? std::to_string( array_key ) : key; if (!serialize.append( t_key, sub, error ) ) return {}; value = ""; if ( is_array ) { array_key++; state = state_e::VAL_UNKNOWN; } else { key = ""; state = state_e::UNKNOWN; } } break; } break; case '[': switch ( state ) { case state_e::UNKNOWN: break; case state_e::KEY: break; case state_e::SPLIT: break; case state_e::VAL_UNKNOWN: state = state_e::VAL_ARRAY; ++depth; value += i; break; case state_e::VAL_STRING: break; case state_e::VAL_ARRAY: ++depth; value += i; break; case state_e::VAL_OBJECT: value += i; break; } break; case ']': switch ( state ) { case state_e::UNKNOWN: break; case state_e::KEY: break; case state_e::SPLIT: break; case state_e::VAL_UNKNOWN: break; case state_e::VAL_STRING: break; case state_e::VAL_ARRAY: --depth; value += i; if ( depth == 0 ) { auto reduced = value.substr( 1, value.size() - 2 ); auto sub = parse( reduced, error, state_e::VAL_UNKNOWN, true ); auto t_key = ( is_array ) ? std::to_string( array_key ) : key; if ( !serialize.appendArray( t_key, sub, error ) ) return {}; value = ""; if ( is_array ) { ++array_key; state = state_e::VAL_UNKNOWN; } else { key = ""; state = state_e::UNKNOWN; } } break; case state_e::VAL_OBJECT: value += i; break; } break; case '\"': switch ( state ) { case state_e::UNKNOWN: state = state_e::KEY; break; case state_e::KEY: state = state_e::SPLIT; break; case state_e::SPLIT: break; case state_e::VAL_UNKNOWN: state = state_e::VAL_STRING; break; case state_e::VAL_STRING: if ( value.size() > 0 ) { if ( value[value.size() - 1] == '\\' ) { value += i; } else { if ( is_array ) { serialize.append( ElementString( std::to_string( array_key ), value ) ); ++array_key; value = ""; state = state_e::VAL_UNKNOWN; } else { serialize.append( ElementString( key, value ) ); key = ""; value = ""; state = state_e::UNKNOWN; } } } break; case state_e::VAL_ARRAY: value += i; break; case state_e::VAL_OBJECT: value += i; break; } break; case ':': switch ( state ) { case state_e::UNKNOWN: break; case state_e::KEY: key += i; break; case state_e::SPLIT: state = state_e::VAL_UNKNOWN; break; case state_e::VAL_UNKNOWN: break; case state_e::VAL_STRING: value += i; break; case state_e::VAL_ARRAY: value += i; break; case state_e::VAL_OBJECT: value += i; break; } break; case ',': switch ( state ) { case state_e::UNKNOWN: break; case state_e::KEY: value += i; break; case state_e::SPLIT: break; case state_e::VAL_UNKNOWN: store_value( is_array, serialize, array_key, key, value, state ); break; case state_e::VAL_STRING: value += i; break; case state_e::VAL_ARRAY: value += i; break; case state_e::VAL_OBJECT: value += i; break; } break; case '\n': case '\r' : case ' ': switch ( state ) { case state_e::UNKNOWN: break; case state_e::KEY: key += i; break; case state_e::SPLIT: break; case state_e::VAL_UNKNOWN: break; case state_e::VAL_STRING: value += i; break; case state_e::VAL_ARRAY: break; case state_e::VAL_OBJECT: value += i; break; } break; default: switch ( state ) { case state_e::UNKNOWN: break; case state_e::KEY: key += i; break; case state_e::SPLIT: break; case state_e::VAL_UNKNOWN: value += i; break; case state_e::VAL_STRING: value += i; break; case state_e::VAL_ARRAY: value += i; break; case state_e::VAL_OBJECT: value += i; break; } break; } } if ( value != "" ) { store_value( is_array, serialize, array_key, key, value, state ); } return serialize; } } Serialize convert( const std::string& input, error_e& error ) { auto reduced = input.substr( 1, input.size() - 2 ); return parse( reduced, error, state_e::UNKNOWN, false ); } Serialize convert( const std::vector<uint8_t>& input, error_e& error ) { std::string conv( input.begin(), input.end() ); auto reduced = conv.substr( 1, conv.size() - 2 ); return parse( reduced, error, state_e::UNKNOWN, false ); } } } }
true
f06645f5e0b4e23d666f45c05b89071b769889d0
C++
mariokonrad/marnav
/test/marnav/ais/Test_ais_message_20.cpp
UTF-8
2,011
2.609375
3
[ "BSD-3-Clause", "BSD-4-Clause" ]
permissive
#include <marnav/ais/message_20.hpp> #include <marnav/ais/ais.hpp> #include <gtest/gtest.h> namespace { using namespace marnav; class test_ais_message_20 : public ::testing::Test { }; TEST_F(test_ais_message_20, parse) { std::vector<std::pair<std::string, uint32_t>> v; v.emplace_back("D030p8@2tN?b<`O6DmQO6D0", 2); auto result = ais::make_message(v); ASSERT_TRUE(result != nullptr); auto m = ais::message_cast<ais::message_20>(result); ASSERT_TRUE(m != nullptr); } TEST_F(test_ais_message_20, wrong_number_of_bits) { EXPECT_ANY_THROW(ais::message_parse<ais::message_20>(ais::raw(69))); EXPECT_ANY_THROW(ais::message_parse<ais::message_20>(ais::raw(161))); } TEST_F(test_ais_message_20, get_entry_invalid_offset) { ais::message_20 m; EXPECT_ANY_THROW(m.get_entry(-1)); EXPECT_ANY_THROW(m.get_entry(4)); } TEST_F(test_ais_message_20, set_entry_invalid_offset) { ais::message_20 m; ais::message_20::entry entry; EXPECT_ANY_THROW(m.set_entry(-1, entry)); EXPECT_ANY_THROW(m.set_entry(4, entry)); } TEST_F(test_ais_message_20, read_fields) { // see: https://fossies.org/linux/gpsd/test/sample.aivdm std::vector<std::pair<std::string, uint32_t>> v; v.emplace_back("D030p8@2tN?b<`O6DmQO6D0", 2); auto result = ais::make_message(v); ASSERT_TRUE(result != nullptr); auto m = ais::message_cast<ais::message_20>(result); ASSERT_TRUE(m != nullptr); EXPECT_EQ(3160097u, m->get_mmsi()); { auto e = m->get_entry(0); EXPECT_EQ(47u, e.offset); EXPECT_EQ(1u, e.slots); EXPECT_EQ(7u, e.timeout); EXPECT_EQ(250u, e.increment); } { auto e = m->get_entry(1); EXPECT_EQ(2250u, e.offset); EXPECT_EQ(1u, e.slots); EXPECT_EQ(7u, e.timeout); EXPECT_EQ(1125u, e.increment); } { auto e = m->get_entry(2); EXPECT_EQ(856u, e.offset); EXPECT_EQ(5u, e.slots); EXPECT_EQ(7u, e.timeout); EXPECT_EQ(1125u, e.increment); } { auto e = m->get_entry(3); EXPECT_EQ(0u, e.offset); EXPECT_EQ(0u, e.slots); EXPECT_EQ(0u, e.timeout); EXPECT_EQ(0u, e.increment); } } }
true
bad90dba3252033b0ecbaff48b328bcea8dcf0f6
C++
roy4801/solved_problems
/uva/686.cpp
UTF-8
772
3.09375
3
[]
no_license
/* * Uva 686 - Goldbach's Conjecture (II) * author: roy4801 * AC(c++) 0.000 */ #include <iostream> using namespace std; #define TABLE_SIZE 33000 bool prime[TABLE_SIZE]; void buildPrimeTable() { prime[0] = prime[1] = false; for(int i = 2; i < TABLE_SIZE; i++) prime[i] = true; for(int i = 2; i < TABLE_SIZE; i++) { if(prime[i]) for(int a = 2*i; a < TABLE_SIZE; a += i) prime[a] = false; } } int main() { #ifndef ONLINE_JUDGE freopen("./testdata/686.in", "r", stdin); freopen("./testdata/686.out", "w", stdout); #endif buildPrimeTable(); int num; while(scanf("%d", &num) != EOF && num != 0) { int count = 0; for(int i = 2; i <= num/2; i++) { if(prime[i] && prime[num-i]) count++; } printf("%d\n", count); } return 0; }
true
a57e4c64b4301f679647a63aee2c8ce1d3132935
C++
emojicode/emojicode
/Compiler/Parsing/AbstractParser.hpp
UTF-8
3,818
2.546875
3
[ "Artistic-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
// // AbstractParser.hpp // Emojicode // // Created by Theo Weidmann on 27/04/16. // Copyright © 2016 Theo Weidmann. All rights reserved. // #ifndef AbstractParser_hpp #define AbstractParser_hpp #include "Emojis.h" #include "Lex/TokenStream.hpp" #include "Types/Generic.hpp" #include "Types/TypeContext.hpp" #include <memory> #include <utility> namespace EmojicodeCompiler { class Function; class ASTType; class Package; class FunctionParser; class Documentation { public: Documentation &parse(TokenStream *tokenStream) { if (tokenStream->nextTokenIs(TokenType::DocumentationComment)) { auto token = tokenStream->consumeToken(TokenType::DocumentationComment); position_ = token.position(); documentation_ = token.value(); found_ = true; } return *this; } const std::u32string &get() const { return documentation_; } void disallow() const { if (found_) { throw CompilerError(position_, "Misplaced documentation token."); } } private: std::u32string documentation_; bool found_ = false; SourcePosition position_ = SourcePosition(); }; struct TypeIdentifier { TypeIdentifier(std::u32string name, std::u32string ns, SourcePosition p) : name(std::move(name)), ns(std::move(ns)), position(std::move(p)) {} std::u32string name; std::u32string ns; SourcePosition position; const std::u32string& getNamespace() const { return ns.empty() ? kDefaultNamespace : ns; } }; class AbstractParser { protected: AbstractParser(Package *pkg, TokenStream &stream) : package_(pkg), stream_(stream) {} Package *package_; TokenStream &stream_; /// Reads a $type-identifier$ TypeIdentifier parseTypeIdentifier(); /// Reads a $type$ and fetches it std::unique_ptr<ASTType> parseType(); /// Parses $generic-parameters$ template<typename T, typename E> void parseGenericParameters(Generic <T, E> *generic) { if (stream_.consumeTokenIf(TokenType::Generic)) { while (stream_.nextTokenIsEverythingBut(E_AUBERGINE)) { bool rejectBoxing = stream_.consumeTokenIf(TokenType::Unsafe); auto variable = stream_.consumeToken(TokenType::Variable); generic->addGenericParameter(variable.value(), parseType(), rejectBoxing, variable.position()); } stream_.consumeToken(); } } template <typename T> void parseGenericArguments(T *t) { if (stream_.consumeTokenIf(TokenType::Generic)) { while (stream_.nextTokenIsEverythingBut(E_AUBERGINE)) { t->addGenericArgument(parseType()); } stream_.consumeToken(); } } /// Parses $parameters$ for a function if there are any specified. /// @param initializer If this is true, the method parses $init-parameters$ instead. void parseParameters(Function *function, bool initializer, bool allowEscaping = true); /// Parses a $return-type$ for a function one is specified. void parseReturnType(Function *function); bool parseErrorType(Function *function); /// Parses an $initializer-name$ or returns std::u32string parseInitializerName(); private: /// Parses a $multi-protocol$ std::unique_ptr<ASTType> parseMultiProtocol(); /// Parses a $callable-type$. The first token has already been consumed. std::unique_ptr<ASTType> parseCallableType(); std::unique_ptr<ASTType> parseGenericVariable(); /// Parses a $type-main$ std::unique_ptr<ASTType> parseTypeMain(); std::unique_ptr<ASTType> parseTypeAsValueType(); Token parseTypeEmoji() const; std::unique_ptr<ASTType> paresTypeId(); }; } // namespace EmojicodeCompiler #endif /* AbstractParser_hpp */
true
8f5b8b7f03d84aa3d9769e48c6187a307fe6a9b0
C++
Manjunath-Jakaraddi/Competitive-Coding
/codeforces/Good Bye 2017 Solutions/eleven2.cpp
UTF-8
604
2.609375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; bool f[5005][5005]; bool g[5005][5005]; int main() { string s; cin>>s; int ans=0; for(int i=0;i<s.length();i++) { int cur=0; for(int j=i;j<s.length();j++) { if(s[j]==')') cur--; else cur++; if(cur>=0) f[i][j]=true; else break; } } for(int i=0;i<s.length();i++) { int cur=0; for(int j=i;j>=0;j--) { if(s[j]=='(') cur--; else cur++; if(cur>=0) g[j][i]=true; else break; } } for(int i=0;i<s.length();i++) { for(int j=i+1;j<s.length();j+=2) if(f[i][j]&&g[i][j]) ans++; } cout<<ans<<endl; return 0; }
true
6937a0c2b855b8b5c7a0d9fd2b558b3eec87c8b4
C++
BartheG/SqlBasicCpp
/Users/UsersInfos.hpp
UTF-8
764
2.96875
3
[]
no_license
#ifndef USERSINFOS_HPP_ #define USERSINFOS_HPP_ #include <string> class UsersInfos { public: UsersInfos( const std::string &username, const std::string &passwordOne, const std::string &passwordTwo = "", const std::string &mail = "" ); ~UsersInfos(); std::string getUsername() const { return this->_username; } std::string getPasswordOne() const { return this->_passwordOne; } std::string getPasswordTwo() const { return this->_passwordTwo; } std::string getMail() const { return this->_mail; } bool isSignIn() const { return this->_signIn; } private: bool _signIn; std::string _username; std::string _passwordOne; std::string _passwordTwo; std::string _mail; }; #endif /* !USERSINFOS_HPP_ */
true
789a4820d93a96e34ea6ac92b21b47159f9ce1c7
C++
Zhangzhiyi/CPlusPlus
/HelloWorld/TestCopyAssign/Classes/TestCopyAssign.cpp
GB18030
3,194
3.265625
3
[]
no_license
// TestCopyAssign.cpp : ̨Ӧóڵ㡣 // #include "stdafx.h" #include <iostream> #include "StringBad.h" #include "StringGood.h" #include "DerivedStringGood.h" using namespace std; void callme1(StringBad & rsb); void callme2(StringBad sb); void callme1(StringGood & rsb); void callme2(StringGood sb); StringGood getStringGood(); int _tmain(int argc, _TCHAR* argv[]) { { /*StringBad headline1("Celery Stalks at Midnight"); StringBad headline2("Lettuce Prey"); StringBad sports("Spinash Leaves Bowl for Dollars"); cout << "headline1: " << headline1 << endl; cout << "headline2: " << headline2 << endl; cout << "sports: " << sports << endl; callme1(headline1); cout << "headline1: " << headline1 << endl; callme2(headline2); cout << "headline2: " << headline2 << endl; cout << "Initialize one object to another:\n"; StringBad sailor = sports; cout << "sailor: " << sailor << endl; cout << "Assign one object to another:\n"; StringBad knot; knot = headline1; cout << "knot: " << knot << endl; cout << "Exitting the block.\n";*/ } { StringGood headline1("Celery Stalks at Midnight"); StringGood headline2("Lettuce Prey"); StringGood sports("Spinash Leaves Bowl for Dollars"); cout << "headline1: " << headline1 << endl; cout << "headline2: " << headline2 << endl; cout << "sports: " << sports << endl; callme1(headline1); cout << "headline1: " << headline1 << endl; callme2(headline2); cout << "headline2: " << headline2 << endl; cout << "Initialize one object to another:\n"; StringGood sailor = sports; //ⲻǸֵǵøƹ캯һ½Ķǻù캯 cout << "sailor: " << sailor << endl; StringGood* psg = new StringGood(sports); //ַʽҲǵøƹ캯 cout << "psg: " << *psg << endl; delete psg; cout << "Assign one object to another:\n"; StringGood knot; knot = headline1; //øֵ operator = (const StringGood& st); cout << "knot: " << knot << endl; knot = "operator = (const char* s)";//øֵ operator = (const char* s); cout << "knot: " << knot << endl; StringGood kail = getStringGood(); cout << "kail: " << kail << endl; cout << "Exitting the block.\n"; } { DerivedStringGood d("DerivedStringGood"); DerivedStringGood d2 = d; int a = 10; } system("Pause"); return 0; } void callme1(StringBad & rsb) { cout << "String passed by reference:\n"; cout <<" \"" << rsb << "\"\n"; } void callme2(StringBad sb) //ֵݵøƹ캯뿪κιڶ󶼻ܶδ { cout << "String passed by value:\n"; cout <<" \"" << sb << "\"\n"; } void callme1(StringGood & rsg) { cout << "String passed by reference:\n"; cout <<" \"" << rsg << "\"\n"; } void callme2(StringGood sg) { cout << "String passed by value:\n"; cout <<" \"" << sg << "\"\n"; } StringGood getStringGood() { StringGood str("StringGood"); //ȹstrȻøƹ캯ظĿ return str; }
true
a17fc5b234b9bc58978b6872b6159b3a75121a16
C++
abdulsalamY/hw5
/handler.cpp
UTF-8
4,172
2.765625
3
[]
no_license
// // Created by abdul on 1/15/2020. // #include "handler.hpp" #include "RegisterManager.hpp" #include "bp.hpp" #include <iostream> #include <assert.h> string handle_operation(string r1, string r2, string op_char, TypeID reg1_type, TypeID reg2_type){ string type = "i32"; if(reg1_type == BYTETYPE && reg2_type == BYTETYPE){ type = "i8"; } if(type == "i32"){ if(reg1_type == BYTETYPE){ string new_reg = getReg(); code_buffer.emit(new_reg + " = zext i8 " + r1 + " to i32"); r1 = new_reg; } if(reg2_type == BYTETYPE){ string new_reg = getReg(); code_buffer.emit(new_reg + " = zext i8 " + r2 + " to i32"); r2 = new_reg; } } string res = getReg(); switch(op_char[0]){ case('-'): { code_buffer.emit(res + " = sub " + type + " " + r1 + ", " + r2); break; } case('+'): { code_buffer.emit(res + " = add " + type + " " + r1 + ", " + r2); break; } case('*'): { code_buffer.emit(res + " = mul " + type + " " + r1 + ", " + r2); break; } case('/'): { string is_zero_reg = getReg(); code_buffer.emit(is_zero_reg + " = icmp eq " + type + " 0 , " + r2); int location = code_buffer.emit("br i1 " + is_zero_reg + " , label @, label @"); string error_label = code_buffer.genLabel(); code_buffer.emit("call void @error_division_by_zero()"); int stam_location = code_buffer.emit("br label @"); string continue_label = code_buffer.genLabel(); if(type == "i32"){ code_buffer.emit(res + " = sdiv " + type + " " + r1 + ", " + r2); }else{ string new_reg = getReg(); code_buffer.emit(new_reg + " = zext i8 " + r1 + " to i32"); r1 = new_reg; new_reg = getReg(); code_buffer.emit(new_reg + " = zext i8 " + r2 + " to i32"); r2 = new_reg; new_reg =getReg(); code_buffer.emit(new_reg + " = sdiv i32 " + r1 + ", " + r2); code_buffer.emit(res + " = trunc i32 " + new_reg + " to i8"); } code_buffer.bpatch(code_buffer.makelist({location, SECOND}), continue_label); code_buffer.bpatch(code_buffer.makelist({location, FIRST}), error_label); code_buffer.bpatch(code_buffer.makelist({stam_location, FIRST}), continue_label); break; } default: code_buffer.emit("errrrorr!!! nayakat ya bahjat"); } return res; } string init_reg_int(int num){ string new_reg = getReg(); code_buffer.emit(new_reg + " = add i32 0, " + to_string(num)); return new_reg; } string init_reg_byte(int num){ string new_reg = getReg(); code_buffer.emit(new_reg + " = add i8 0, " + to_string(num)); return new_reg; } string init_reg_bool(bool value){ string new_reg = getReg(); if( value ){ code_buffer.emit(new_reg + " = add i1 0, 1"); }else{ code_buffer.emit(new_reg + " = add i1 0, 0"); } return new_reg; } string init_reg_not(string reg){ //assert(reg != ""); string new_reg = getReg(); code_buffer.emit(new_reg + " = xor i1 1, " + reg); return new_reg; } string init_reg_enum(int enum_id) { string new_reg = getReg(); code_buffer.emit(new_reg + " = add i32 0, " + to_string(enum_id)); return new_reg; } string init_reg_string(const string& value) { string global_var_name = getGlobal(); string ptr_reg = getReg(); string size = to_string(value.size()-1); code_buffer.emitGlobal(global_var_name + " = constant [" + size + " x i8] c" + value.substr(0,value.size()-1) + "\\00\""); code_buffer.emit(ptr_reg + " = getelementptr [" + size +" x i8], [" + size +" x i8]* " + global_var_name + ", i32 0, i32 0"); return ptr_reg; } int handle_bool_exp_jump(Exp exp) { string boolean_value = exp.reg; return code_buffer.emit("br i1 " + boolean_value + ", label @, label @"); }
true
74831fe3ab758dbb8f341bad92497a804f0ceeb2
C++
sabassamadashvilli423/51
/lector/lector/lector.cpp
UTF-8
518
3
3
[]
no_license
#include <iostream> #include"Lectori.h" #include<vector> using namespace std; void mySort(vector < Lectori> a) { for (int j = 0; j < a.size(); j++) { for (int i = 0; i < a.size() - 1; i++) { if (a[i].count > a[i + 1].count) swap(a[i] , a[i + 1]); } } } int main() { vector<Lectori> a; Lectori t; while (cin >> t.name >> t.lname >> t.count >> t.status) { a.push_back(t); } mySort(a); a[a.size()-1].printLector(); }
true
d15967136231c2b3283002e7af24e659aa40bf8d
C++
aayushjn2/LeetCode
/Consecutive Numbers Sum.cpp
UTF-8
291
2.734375
3
[]
no_license
class Solution { public: int consecutiveNumbersSum(int N) { int res = 0; int k = 1; while(k<(ceil(sqrt(2*N)))){ int t = k*(k-1)/2; if((N-t)%k==0){ res++; } k++; } return res; } };
true
a0824b2a193f7e6b04d982376a12b3d72191ccfe
C++
A-TNguyen/Text_RPG_Game
/Main/Cave.h
UTF-8
5,393
3.09375
3
[]
no_license
#pragma once #include <iostream> #include <string> #include <vector> using namespace std; class Cave { public: void Cave_Story(); private: int x = 0; // Switch counter int choice; // Choosing an answer from the switch case bool alive = true; //Statment to keep true to be alive }; //Scope resolution for the class Cave for cave story function in order to utilize defined variables in pricate void Cave::Cave_Story() { //Switch case while ( alive != false ) { //Implement later for whole switch case story switch ( x ) { case 0: system( "CLS" ); cout << "You approach the front of the cave you notice a sign \n ***** Beware Enter at your own Risk***** \n"; cout << "\nWhat marvelous path sha'll you venture human? \n\n"; cout << "1. Walk into the dark abyss with nothing but your shorts and tank top\n"; cout << "2. Sit under the shaded Oak Tree and fall asleep\n"; cout << "3. Chicken out from reading the sign , and go home\n"; begin:cin >> choice; if ( choice == 1 ) { x = 1; } else if ( choice == 2 ) { x = 10; } else if ( choice == 3 ) { x = 13; } break; case 1:system( "CLS" ); cout << "You choose not to chicken out in your trousers and decide to venture deeper into the cave\n"; cout << "The path you walk begins to fork to the left and right, what do you choose?\n"; cout << "1. Walk Left\n"; cout << "2. Walk Right\n"; cin >> choice; if ( choice == 1 ) { x = 2; } if ( choice == 2 ) { x = 12; } break; case 2: system( "CLS" ); cout << "As you continue down the path you hear running water echoing rapidily throughout the cave,\n"; cout << "You become curious and wander towards the path only to find someone's armor and weapon.\n"; cout << "1. Put on the armor and weapon\n"; cout << "2. Ignore, the loot and continue towards the rapid water\n"; cout << "3. Poke at the remains of the owner of the armor and weapon\n"; cin >> choice; if ( choice == 1 ) { x = 3; } if ( choice == 2 ) { x = 4; } if ( choice == 3 ) { x = 11; } break; case 3: system( "CLS" ); cout << "The armor is a tight fit, looking snazzy in the rusty armor :)\n"; cout << "Before you know it you end up in front of the rapid waters within the labryinth abyss\n"; cout << "A melodic song could be heard from afar catching your attention\n"; cout << "1. You are too tired, so you decide to take a nap behind the suspicious giant boulder\n"; cout << "2. Walk towards the hypnotic singing\n"; cout << "3. Run away because you remember you left the stove on\n"; cin >> choice; if ( choice == 1 ) { x = 14; } if ( choice == 2 ) { x = 6; } if ( choice == 3 ) { x = 12; } break; case 4: system( "CLS" ); cout << "You end up in front of the rapid waters within the labryinth abyss\n"; cout << "A melodic song could be heard from afar catching your attention\n"; cout << "1. You are too tired, so you decide to take a nap behind the suspicious giant boulder\n"; cout << "2. Walk towards the hypnotic singing\n"; cout << "3. Run away because you remember you left the stove on\n"; cin >> choice; if ( choice == 1 ) { x = 14; } if ( choice == 2 ) { x = 6; } if ( choice == 3 ) { x = 12; } break; c5:case 5: system( "CLS" ); cout << "After narrowly escaping the ghoulish skeleton remains of a former adventurer\n"; cout << "You end up in front of the rapid waters within the labryinth abyss\n"; cout << "A melodic song could be heard from afar catching your attention\n"; cout << "1. You are too tired, so you decide to take a nap behind the suspicious giant boulder\n"; cout << "2. Walk towards the hypnotic singing\n"; cout << "3. Run away because you remember you left the stove on\n"; cin >> choice; if ( choice == 1 ) { x = 14; } if ( choice == 2 ) { x = 6; } if ( choice == 3 ) { x = 12; } break; case 6: system( "CLS" ); cout << "Never gonna give you up\nNever gonna let you down\nNever gonna run around and desert you\n"; cout << "You just been Ricked Roll . . . .\n"; cout << "Rick Astly Hands you a Gold Sword\n"; cout << "1. Take the sword\n"; cout << "2. Walk away from being mememed."; cin >> choice; if ( choice == 1 ) { x = 7; } if ( choice == 2 ) { x = 15; } break; case 7: system( "CLS" ); cout << "You swing the sword around, Congratulations you are now an adventurer! ! !"; alive = false; break; case 10: system( "CLS" ); cout << "Yikes ! ! ! The Tree became alive and ate you :D \n"; alive = false; break; case 11: system( "CLS" ); cout << "The corps became alive and bit you for 30 HP \n"; { goto c5; } break; case 12: system( "CLS" ); cout << "The Cave collapsed and you were crushed. . . :(\n"; alive = false; break; case 13: system( "CLS" ); cout << "Well.... not all of us can be adventurers\n"; alive = false; break; case 14: system( "CLS" ); cout << "Bunch of Cave Trolls come out of nowhere and beat you to death while you were sleeping :(\n"; alive = false; break; case 15: system( "CLS" ); cout << "Traumatized from Rick Astly you decide to go home\n"; alive = false; break; } } }
true
5a30c50c6b36a9d1881a068364a80e88a98cbf23
C++
Kaustav97/CPP_Reference
/CC-JuneLong/PlusEqn.cpp
UTF-8
1,471
3.09375
3
[]
no_license
#include <vector> #include <set> #include <unordered_map> #include <algorithm> #include <iostream> using namespace std; #define tr1(cont) for(auto it=cont.begin();it!=cont.end();it++) #define tr2(cont,it) for(;it!=cont.end();it++) #define rep(n) for(int i=0;i<n;i++) // std::unordered_map<string,int> hist; string ans; // METHOD TO SPLIT A STRING IN STL int eval(const string &str){ // std::unordered_map<string,int>::iterator rep=hist.find(str); // if(rep!=hist.end())return hist[str]; string del="+",token; int pos=0; int sum=0; string tmp=str; // cout<<"->"<<tmp<<endl; // std::string::find returns std::string::npos if not found while( (pos=tmp.find(del))!=std::string::npos){ token = tmp.substr(0,pos); sum+=std::stoi(token); tmp.erase(0,pos+del.length()); } sum+=std::stoi(tmp); // hist[str]=sum; return sum; } int search(std::string str,int tgt,int pos){ // cout<<str<<" "<<"--"<<pos<<"&"<<str.size()<<endl; if(eval(str)==tgt){ans=str;return 0;} if(pos==str.size())return 0; // leave blank search(str,tgt,pos+1); // cout<<str<<" "<<"--"<<pos<<"&"<<str.size()<<endl; // place + if(str[pos]!='+' & str[pos-1]!='+'){ str.insert(pos,"+"); search(str,tgt,pos+2); } return 0; } int main(){ int t;cin>>t; rep(t){ // hist.clear(); string str;int req; cin>>str>>req; search(str,req,1); cout<<ans<<endl; } // std::string eqn="15489001"; // search(eqn,10549,1); }
true
2cb623cab727a05a25b87bd3d0eea93b87195a43
C++
marchenko2k16/GameOfLife
/GameOfLife/World.cpp
UTF-8
1,969
2.953125
3
[]
no_license
#include "World.h" unsigned int World::height; unsigned int World::width; extern int windowHeight; extern int windowWidth; void World::checkForChanges(unsigned int row, unsigned int col) { bool flag = false; int count = 0; int i; if (row == 0) { i = 0; } else { i = row - 1; } int _j; if (col == 0) { _j = 0; } else { _j = col - 1; } for (; i <= (row + 1) && i < World::height; ++i) { for (auto j = _j; j <= (col + 1) && j < World::width; ++j) { if (!(i == row && j == col) && worldMap[i][j].getState() == State::ALIVE) { count++; } } } if (worldMap[row][col].getState() == State::DEAD && count == 3) { flag = true; } else if (worldMap[row][col].getState() == State::ALIVE && (count == 2 || count == 3)) { flag = true; } else if (worldMap[row][col].getState() == State::ALIVE && (count < 2 || count > 3)) { flag = false; } worldMap[row][col].setNext(flag); } void World::checkStates() { for (auto i = 0; i < height; ++i) { for (auto j = 0; j < width; ++j) { checkForChanges(i, j); } } } void World::update() { for (auto i = 0; i < height; ++i) { for (auto j = 0; j < width; ++j) { worldMap[i][j].update(); } } } World::World(unsigned int row, unsigned int column) { World::width = row; World::height = column; worldMap = new GameUnit*[height]; for (auto i = 0; i < height; ++i) { worldMap[i] = new GameUnit[width]; } for (auto i = 0; i < height; ++i) { for (auto j = 0; j < width; ++j) { worldMap[i][j] = GameUnit(); } } for (auto i = 0; i < height; ++i) { for (auto j = 0; j < width; ++j) { worldMap[i][j].setPosition(sf::Vector2f((windowWidth / World::width) * j, (windowHeight / World::height) * i)); worldMap[i][j].setSize(sf::Vector2f(windowWidth / World::width, windowHeight / World::height)); } } } World::~World() { for (int i = 0; i < height; ++i) { delete[] worldMap[i]; } delete[] worldMap; worldMap = 0; }
true
409c86288a24d938018764f3cd5b02a8b0b15108
C++
Refeel/WordsCollocations
/methods.cpp
UTF-8
3,343
2.71875
3
[]
no_license
#include "methods.h" #include "QStringList" Methods::Methods(WordsStatisticNGrams *wordsStats) { ranking(wordsStats); } Methods::~Methods() { } void Methods::ranking(WordsStatisticNGrams *ws) { QString collocation = ""; int biGram = 2; QHash<QString, int>::const_iterator iter = ws->wordsStatistic[biGram-1].constBegin(); while(iter != ws->wordsStatistic[biGram-1].constEnd()) { collocation = iter.key(); QStringList wordsInColl = collocation.split(" "); int numberOfInstancesOfWord1 = ws->wordsStatistic[0][wordsInColl[0]]; int numberOfInstancesOfWord2 = ws->wordsStatistic[0][wordsInColl[1]]; int numberOfInstancesOfWordPair = ws->wordsStatistic[biGram-1][collocation]; int allWordsInCorpusCount = ws->getWordsCount(); double rankFSCP = getFSCPRank((double)numberOfInstancesOfWordPair, (double)numberOfInstancesOfWord1,(double) numberOfInstancesOfWord2); double rankZScore = getZScoreRank((double)numberOfInstancesOfWordPair, (double)numberOfInstancesOfWord1, (double)numberOfInstancesOfWord2, (double)allWordsInCorpusCount); double rankPMI = getPMIRank((double)numberOfInstancesOfWordPair, (double)numberOfInstancesOfWord1, (double)numberOfInstancesOfWord2, (double)allWordsInCorpusCount); collocationsRankFSCP.push_back(std::make_pair(collocation, rankFSCP)); collocationsRankZScore.push_back(std::make_pair(collocation, rankZScore)); collocationsRankPMI.push_back(std::make_pair(collocation, rankPMI)); iter++; } } double Methods::getE(double numberOfInstancesOfWord1, double numberOfInstancesOfWord2, double numberOfAllInstances) { return (numberOfInstancesOfWord1 * numberOfInstancesOfWord2) / numberOfAllInstances; } double Methods::getD(double numberOfInstancesOfWord1, double numberOfInstancesOfWord2, double numberOfAllInstances) { return sqrt((numberOfInstancesOfWord1 * numberOfInstancesOfWord2) / numberOfAllInstances); } double Methods::getPropabilityOfWordPair(double numberOfInstancesOfWordPair, double numberOfAllInstances) { return numberOfInstancesOfWordPair / numberOfAllInstances; } double Methods::getPropabilityOfWord(double numberOfInstancesOfWord, double numberOfAllInstances) { return numberOfInstancesOfWord / numberOfAllInstances; } double Methods::getFSCPRank(double numberOfInstancesOfWordPair, double numberOfInstancesOfWord1, double numberOfInstancesOfWord2) { return (pow(numberOfInstancesOfWordPair, 3)) / (numberOfInstancesOfWord1 * numberOfInstancesOfWord2); } double Methods::getZScoreRank(double numberOfInstancesOfWordPair, double numberOfInstancesOfWord1, double numberOfInstancesOfWord2, double numberOfAllInstances) { return (numberOfInstancesOfWordPair - getE(numberOfInstancesOfWord1, numberOfInstancesOfWord2, numberOfAllInstances)) / getD(numberOfInstancesOfWord1, numberOfInstancesOfWord2, numberOfAllInstances); } double Methods::getPMIRank(double numberOfInstancesOfWordPair, double numberOfInstancesOfWord1, double numberOfInstancesOfWord2, double numberOfAllInstances) { return log2((getPropabilityOfWordPair(numberOfInstancesOfWordPair, numberOfAllInstances)) / (getPropabilityOfWord(numberOfInstancesOfWord1, numberOfAllInstances) * getPropabilityOfWord(numberOfInstancesOfWord2, numberOfAllInstances))); }
true
b608872313dde81ee2217c8cf779bf8762603331
C++
Banghyungjin/DataStructure
/Balanced_String/balanced_string.cpp
UTF-8
816
3.03125
3
[]
no_license
//made by HyungJin //10-10-2019 //---------------------------------------------------------------------------------------------------------------------- #include <iostream> using namespace std; int main() { int inputNum; cout << "Please input a number that is bigger than 0 you want or type -1 to quit" << endl; while (inputNum != -1) { cin >> inputNum; if (inputNum != -1) { cout << "Input number = " << inputNum << endl; int tempAns = (inputNum+1)/2; int ans = 1; while (tempAns>0) { ans = ans*2; ans = ans%16769023; tempAns--; } cout << ans << endl; cout << "Want some more?" << endl; } } cout << "As you wish" << endl; return 0; }
true
04752df637e80e226b1ea943ee9dea85ab1c6eb3
C++
LonglongSang/Life_of_XDU
/OiWiki_Learning/线段树/1235规划兼职工作动态规划.cpp
UTF-8
1,176
2.703125
3
[]
no_license
//https://leetcode-cn.com/problems/maximum-profit-in-job-scheduling/ #include <stdio.h> #include <string> #include <iostream> #include <stdlib.h> #include <unordered_map> #include <unordered_set> #include <map> #include <set> #include <vector> #include <string.h> #include <algorithm> using namespace std; #define N 100000 int v[N],dp[N]; class Solution { public: int getVal(vector<int>& endTime,int high,int val){ int low=0,mid,ans=-1; while(high>=low){ mid=(low+high)/2; if(endTime[v[mid]]<=val){ ans=mid; low=mid+1; }else{ high=mid-1; } } return ans==-1?0:dp[ans]; } int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) { int n=startTime.size(); for(int i=0;i<n;i++) v[i]=i; sort(v,v+n,[&](int a,int b){ return endTime[a]<endTime[b]; }); dp[0]=profit[v[0]]; for(int i=0;i<n;i++){ dp[i]=profit[v[i]]+getVal(endTime,i-1,startTime[v[i]]); if(i) dp[i]=std::max(dp[i],dp[i-1]); } return dp[n-1]; } };
true
5de053f07ac335fda420f8b17dd3e290502760b7
C++
SS2015TUMGED/GED
/projects/Game/src/T3d.cpp
UTF-8
4,408
2.828125
3
[]
no_license
#include "T3d.h" #include <sstream> #include "DirectXTex.h" using namespace std; struct T3dHeader { int16_t magicNumber; // Must be 0x003D int16_t version; // Must be 1 int32_t verticesSize; // vertex buffer data size int32_t indicesSize; // index buffer data size }; // Sizes are always in bytes HRESULT T3d::readFromFile(const std::string& filename, std::vector<T3dVertex>& vertexBufferData, std::vector<uint32_t>& indexBufferData) { HRESULT hr; // Open the file FILE* file; /*errno_t error =*/ fopen_s(&file, filename.c_str(), "rb"); if (file == nullptr) { MessageBoxA (NULL, (std::string("Could not open ") + filename).c_str(), "File error", MB_ICONERROR | MB_OK); return E_FAIL; } // Read the header T3dHeader header; { auto r = fread (&header, sizeof (T3dHeader), 1, file); if (r != 1) { MessageBoxA (NULL, "Could not read the header.", "Invalid t3d file", MB_ICONERROR | MB_OK); return E_FAIL; } } // Check the magic number if (header.magicNumber != 0x003D) { MessageBoxA (NULL, "The magic number is incorrect.", "Invalid t3d file header", MB_ICONERROR | MB_OK); return E_FAIL; } // Check the version if (header.version != 1) { MessageBoxA (NULL, "The header version is incorrect.", "Invalid t3d file header", MB_ICONERROR | MB_OK); return E_FAIL; } //Read vertex buffer vertexBufferData.resize(header.verticesSize / sizeof(T3dVertex)); fread(&vertexBufferData[0], sizeof(T3dVertex), vertexBufferData.size(), file); //Read index buffer indexBufferData.resize(header.indicesSize / sizeof(uint32_t)); fread(&indexBufferData[0], sizeof(uint32_t), indexBufferData.size(), file); fclose(file); return S_OK; } HRESULT T3d::readFromFile(const std::wstring& filename, std::vector<T3dVertex>& vertexBufferData, std::vector<uint32_t>& indexBufferData) { HRESULT hr; // Open the file FILE* file; /*errno_t error =*/ _wfopen_s(&file, filename.c_str(), L"rb"); if (file == nullptr) { MessageBoxW (NULL, (std::wstring(L"Could not open ") + filename).c_str(), L"File error", MB_ICONERROR | MB_OK); return E_FAIL; } // Read the header T3dHeader header; { auto r = fread (&header, sizeof (T3dHeader), 1, file); if (r != 1) { MessageBoxW (NULL, L"Could not read the header.", L"Invalid t3d file", MB_ICONERROR | MB_OK); return E_FAIL; } } // Check the magic number if (header.magicNumber != 0x003D) { MessageBoxW (NULL, L"The magic number is incorrect.", L"Invalid t3d file header", MB_ICONERROR | MB_OK); return E_FAIL; } // Check the version if (header.version != 1) { MessageBoxW (NULL, L"The header version is incorrect.", L"Invalid t3d file header", MB_ICONERROR | MB_OK); return E_FAIL; } //Read vertex buffer vertexBufferData.resize(header.verticesSize / sizeof(T3dVertex)); fread(&vertexBufferData[0], sizeof(T3dVertex), vertexBufferData.size(), file); //Read index buffer indexBufferData.resize(header.indicesSize / sizeof(uint32_t)); fread(&indexBufferData[0], sizeof(uint32_t), indexBufferData.size(), file); fclose(file); return S_OK; } HRESULT T3d::createT3dInputLayout(ID3D11Device* pd3dDevice, ID3DX11EffectPass* pass, ID3D11InputLayout** t3dInputLayout) { HRESULT hr; // Define the input layout const D3D11_INPUT_ELEMENT_DESC layout[] = // http://msdn.microsoft.com/en-us/library/bb205117%28v=vs.85%29.aspx { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; UINT numElements = sizeof( layout ) / sizeof( layout[0] ); // Create the input layout D3DX11_PASS_DESC pd; V_RETURN(pass->GetDesc(&pd)); V_RETURN( pd3dDevice->CreateInputLayout( layout, numElements, pd.pIAInputSignature, pd.IAInputSignatureSize, t3dInputLayout ) ); return S_OK; }
true
418232e917fd9aade8bcafe07f9d7cec90a0a110
C++
risooonho/GameBase
/Source/GameBase/Private/Extensions/PlayerControllerExtensions.cpp
UTF-8
3,420
2.53125
3
[]
no_license
#include "PlayerControllerExtensions.h" #include "Kismet/GameplayStatics.h" #include "GameFramework/PlayerController.h" #include "GameFrameworkExtensions.h" #include "ActorExtensions.h" FVector2D FPlayerControllerExtensions::GetMousePosition(UObject* WorldContextObject) { check(WorldContextObject); check(WorldContextObject->GetWorld()); const auto PlayerController = FGameFrameworkExtensions::GetPlayerControllerAs<APlayerController>(WorldContextObject); return GetMousePosition_FromPlayerController(PlayerController); } FVector2D FPlayerControllerExtensions::GetMousePosition_FromPlayerController(APlayerController* PlayerController) { check(PlayerController); auto X = 0.0f; auto Y = 0.0f; PlayerController->GetMousePosition(X, Y); return FVector2D(X, Y); } bool FPlayerControllerExtensions::GetMouseRay(UObject* WorldContextObject, FVector& Start, FVector& Direction) { check(WorldContextObject); check(WorldContextObject->GetWorld()); const auto PlayerController = FGameFrameworkExtensions::GetPlayerControllerAs<APlayerController>(WorldContextObject); return GetMouseRay_FromPlayerController(PlayerController, Start, Direction); } bool FPlayerControllerExtensions::GetMouseRay_FromPlayerController(APlayerController* PlayerController, FVector& Start, FVector& Direction) { check(PlayerController); const auto MousePosition = GetMousePosition_FromPlayerController(PlayerController); return UGameplayStatics::DeprojectScreenToWorld(PlayerController, MousePosition, Start, Direction); } void FPlayerControllerExtensions::GetCenterScreenRay(UObject* WorldContextObject, FVector& Start, FVector& Direction) { check(WorldContextObject); check(WorldContextObject->GetWorld()); const auto PlayerController = FGameFrameworkExtensions::GetPlayerControllerAs<APlayerController>(WorldContextObject); GetCenterScreenRay_FromPlayerController(PlayerController, Start, Direction); } void FPlayerControllerExtensions::GetCenterScreenRay_FromPlayerController(APlayerController* PlayerController, FVector& Start, FVector& Direction) { check(PlayerController); FRotator Rotator; PlayerController->PlayerCameraManager->GetCameraViewPoint(Start, Rotator); Start = Start; Direction = Rotator.Vector(); } bool FPlayerControllerExtensions::GetScreenspaceBounds(UObject* WorldContextObject, AActor* Actor, FBox2D& Bounds) { check(WorldContextObject); check(WorldContextObject->GetWorld()); check(Actor); const auto PlayerController = FGameFrameworkExtensions::GetPlayerControllerAs<APlayerController>(WorldContextObject); return GetScreenspaceBounds_FromPlayerController(PlayerController, Actor, Bounds); } bool FPlayerControllerExtensions::GetScreenspaceBounds_FromPlayerController(APlayerController* PlayerController, AActor* Actor, FBox2D& Bounds) { check(PlayerController); check(Actor); Bounds = FBox2D(EForceInit::ForceInitToZero); int32 Width, Height; PlayerController->GetViewportSize(Width, Height); const FVector2D Size(Width, Height); TArray<FVector> Points; FActorExtensions::GetBoundsPoints(Actor, Points); auto bPartiallyOnScreen = false; for (auto i = 0; i < Points.Num(); i++) { FVector2D Point2D; if (PlayerController->ProjectWorldLocationToScreen(Points[i], Point2D)) if (Point2D.X > 0 && Point2D.X <= Width && Point2D.Y > 0 && Point2D.Y <= Height) bPartiallyOnScreen = true; Bounds += Point2D / Size; } return bPartiallyOnScreen; }
true
16f81ed611c0a89f0435e4cd5ccf4205be9ccfeb
C++
MarkOates/LabyrinthOfLore
/include/LabyrinthOfLore/Hud/TitleText.hpp
UTF-8
564
2.53125
3
[]
no_license
#pragma once #include <string> namespace LabyrinthOfLore { namespace Hud { class TitleText { private: std::string above_text; std::string headline_text; float time_changed_at; protected: public: TitleText(); ~TitleText(); std::string get_above_text() const; std::string get_headline_text() const; float get_time_changed_at() const; void set(std::string above_text="", std::string headline_text="", float time_now=0.0f); }; } }
true
b18fc22c82a2dd7dacb5a7d99e4fed35fa0e871c
C++
hikaen2/tenuki
/position.cpp
UTF-8
8,225
3.015625
3
[ "MIT" ]
permissive
#include "tenuki.h" using std::map; using std::string; using std::vector; namespace tenuki { /** * SFENを局面にする */ const position parse_position(const string& sfen) { const map<string, square_t> TO_SQUARE { {"1", square::EMPTY }, {"P", square::B_PAWN }, {"L", square::B_LANCE }, {"N", square::B_KNIGHT }, {"S", square::B_SILVER }, {"B", square::B_BISHOP }, {"R", square::B_ROOK }, {"G", square::B_GOLD }, {"K", square::B_KING }, {"+P", square::B_PROMOTED_PAWN }, {"+L", square::B_PROMOTED_LANCE }, {"+N", square::B_PROMOTED_KNIGHT }, {"+S", square::B_PROMOTED_SILVER }, {"+B", square::B_PROMOTED_BISHOP }, {"+R", square::B_PROMOTED_ROOK }, {"p", square::W_PAWN }, {"l", square::W_LANCE }, {"n", square::W_KNIGHT }, {"s", square::W_SILVER }, {"b", square::W_BISHOP }, {"r", square::W_ROOK }, {"g", square::W_GOLD }, {"k", square::W_KING }, {"+p", square::W_PROMOTED_PAWN }, {"+l", square::W_PROMOTED_LANCE }, {"+n", square::W_PROMOTED_KNIGHT }, {"+s", square::W_PROMOTED_SILVER }, {"+b", square::W_PROMOTED_BISHOP }, {"+r", square::W_PROMOTED_ROOK }, }; static const map<string, type_t> TO_TYPE { {"P", type::PAWN}, {"L", type::LANCE}, {"N", type::KNIGHT}, {"S", type::SILVER}, {"B", type::BISHOP}, {"R", type::ROOK}, {"G", type::GOLD}, {"p", type::PAWN}, {"l", type::LANCE}, {"n", type::KNIGHT}, {"s", type::SILVER}, {"b", type::BISHOP}, {"r", type::ROOK}, {"g", type::GOLD}, }; // スペースでsplitする vector<string> v; boost::algorithm::split(v, sfen, boost::is_space()); if (v.size() != 4) { throw std::runtime_error(sfen); } string board_state = v[0]; string side_to_move = v[1]; string pieces_in_hand = v[2]; string move_count = v[3]; position p; std::fill(std::begin(p.squares), std::end(p.squares), square::WALL); std::fill(std::begin(p.pieces_in_hand[side::BLACK]), std::end(p.pieces_in_hand[side::BLACK]), 0); std::fill(std::begin(p.pieces_in_hand[side::WHITE]), std::end(p.pieces_in_hand[side::WHITE]), 0); // 手番 if (side_to_move != "b" && side_to_move != "w") { throw std::runtime_error(sfen); } p.side_to_move = side_to_move == "b" ? side::BLACK : side::WHITE; // 盤面 for (int i = 9; i >= 2; i--) { boost::algorithm::replace_all(board_state, std::to_string(i), string(i, '1')); // 2~9を1に開いておく } boost::algorithm::replace_all(board_state, "/", ""); static const std::regex re("\\+?."); // 例:l, n, s, g, k, p, +p, +P, / std::sregex_iterator it(board_state.begin(), board_state.end(), re); for (int rank = 1; rank <= 9; rank++) { for (int file = 9; file >= 1; file--) { p.squares[file * 10 + rank] = TO_SQUARE.at((*it++).str()); } } // 持ち駒 if (pieces_in_hand != "-") { static const std::regex re("(\\d*)(\\D)"); // 例:S, 4P, b, 3n, p, 18P for (std::sregex_iterator it(pieces_in_hand.begin(), pieces_in_hand.end(), re), end; it != end; ++it) { const int num = (*it)[1].length() == 0 ? 1 : stoi((*it)[1].str()); const string piece = (*it)[2].str(); p.pieces_in_hand[isupper(piece.at(0)) ? side::BLACK : side::WHITE][TO_TYPE.at(piece)] += num; } } return p; } /** * to_sfen */ const string to_sfen(const position& p) { // 歩, 香, 桂, 銀, 角, 飛, 金, 王, と, 成香, 成桂, 成銀, 馬, 龍, 空, 壁 static const vector<string> TO_SFEN { "P", "L", "N", "S", "B", "R", "G", "K", "+P", "+L", "+N", "+S", "+B", "+R", "1", "", "p", "l", "n", "s", "b", "r", "g", "k", "+p", "+l", "+n", "+s", "+b", "+r", }; vector<string> lines; for (int rank = 1; rank <= 9; rank++) { string line; for (int file = 9; file >= 1; file--) { line += TO_SFEN.at(p.squares[address(file, rank)]); } lines.push_back(line); } string s = boost::algorithm::join(lines, "/"); for (int i = 9; i >= 2; i--) { boost::algorithm::replace_all(s, string(i, '1'), std::to_string(i)); // '1'をまとめる } return s; } /** * pの静的評価値を返す */ int16_t static_value(const position& p) { // 歩, 香, 桂, 銀, 角, 飛, 金, 王, と, 成香, 成桂, 成銀, 馬, 龍, 空, 壁 static const int16_t SCORE[] = { 87, 235, 254, 371, 571, 647, 447, 9999, 530, 482, 500, 489, 832, 955, 0, 0, -87, -235, -254, -371, -571, -647, -447, -9999, -530, -482, -500, -489, -832, -955, }; if (p.pieces_in_hand[side::BLACK][type::KING] > 0) { return 15000; } if (p.pieces_in_hand[side::WHITE][type::KING] > 0) { return -15000; } int16_t result = 0; for (int i = 11; i <= 99; i++) { result += SCORE[p.squares[i]]; } for (int t = type::PAWN; t <= type::ROOK; t++) { result += (p.pieces_in_hand[side::BLACK][t] - p.pieces_in_hand[side::WHITE][t]) * SCORE[t]; } return result; } /** * 局面をKI2形式の文字列にする */ const string to_ki2(const position& p) { static const vector<string> BOARD { " 歩", " 香", " 桂", " 銀", " 角", " 飛", " 金", " 玉", " と", " 杏", " 圭", " 全", " 馬", " 龍", " ・", " 壁", "v歩", "v香", "v桂", "v銀", "v角", "v飛", "v金", "v玉", "vと", "v杏", "v圭", "v全", "v馬", "v龍", }; static const vector<string> HAND { "歩", "香", "桂", "銀", "角", "飛", "金", }; static const vector<string> NUM { "〇", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", }; string hand[2]; for (side_t s = side::BLACK; s <= side::WHITE; s++) { for (type_t t = type::PAWN; t <= type::GOLD; t++) { const int n = p.pieces_in_hand[s][t]; if (n > 0) { hand[s] += HAND.at(t) + (n > 1 ? NUM.at(n) : "") + " "; } } } string s; s += "後手の持駒:" + (hand[1].empty() ? "なし" : hand[1]) + "\n"; s += " 9 8 7 6 5 4 3 2 1\n"; s += "+---------------------------+\n"; for (int rank = 1; rank <= 9; rank++) { s += "|"; for (int file = 9; file >= 1; file--) { s += BOARD.at(p.squares[address(file, rank)]); } s += "|" + NUM.at(rank) + "\n"; } s += "+---------------------------+\n"; s += "先手の持駒:" + (hand[0].empty() ? "なし" : hand[0]) + "\n"; return s; } const string to_string(const position& p) { string s; s += "static_value: " + std::to_string(static_value(p)) + "\n"; s += string("side_to_move: ") + (p.side_to_move == side::BLACK ? "side::BLACK" : "side::WHITE") + "\n"; s += "sfen: " + to_sfen(p) + "\n"; s += to_ki2(p) + "\n"; return s; } }
true
d25534857fa602b7c99e123342e65c943715d32b
C++
Rainboylvx/pcs
/loj/132/1.cpp
UTF-8
3,264
2.84375
3
[]
no_license
/*----------------- * author: Rainboy * email: rainboylvx@qq.com * time: 2020年 05月 20日 星期三 08:37:52 CST * problem: loj-132 *----------------*/ #include <bits/stdc++.h> #define For(i,start,end) for(i = start ;i <= end; ++i) #define Rof(i,start,end) for(i = start ;i >= end; --i) typedef long long ll; using namespace std; /* ======= 全局变量 =======*/ const int maxn = 1e7+5; const int maxe = 1e6+5; int n,m; /* ======= 全局变量 END =======*/ /* ======== 树状数组 BIT * 1.单点增减,区间和 * 1.1 逆序对 * 2.区间增减,单点值 * 3.区间增减,区间和 * 4.单点修改,末尾压入,区间最值 * */ namespace bit { typedef long long ll; ll c[maxn],SIZE=maxn; ll c2[maxn]; // c2[i] = i*c[i] inline void bit_init(){} /* 区间和 */ inline ll lowbit(ll x) { return x & -x;} void update(ll pos,ll add){ while(pos<=SIZE) c[pos]+=add,pos+=lowbit(pos);} /* 差分,区间增减,单点查询*/ void update_range(ll l,ll r,ll add){ update(l,add);update(r+1,-add); } ll query(int pos){ll sum=0;while(pos>0) sum+=c[pos],pos-=lowbit(pos); return sum;} /* 差分,区间增减,区间查询*/ //核心公式:sum_a[i] = (i+1)×sum_c[i] - sum_{i×c[i]} void update_c_c2(ll pos,ll add){ //同时更新c,c2 ll t = pos; while( pos <= SIZE){ c[pos] += add; c2[pos] += t*add; pos+=lowbit(pos);} } void update_range_c_c2(ll l,ll r ,ll add){ update_c_c2(l, add);update_c_c2(r+1, -add); } ll query2(ll pos){ ll sum = 0; while( pos > 0) sum += c2[pos], pos -=lowbit(pos); return sum; } ll query_range_sum(ll l,ll r){ return (r+1)*query(r) - query2(r) - l*query(l-1) + query2(l-1); } // ===== 4.单点修改,末尾压入,区间最值 ll a[maxn]; // 原数组 void update_by_child(ll pos,ll v){ // alias push c[pos] = a[pos] = v; ll i,lb = lowbit(pos); for(i=1 ; i < lb ; i <<= 1) c[pos] = std::max(c[pos],c[pos-i]); } void update_ex(ll pos,ll v){ update_by_child(pos,v); int tmp = c[pos]; for( pos += lowbit(pos); pos <=SIZE; pos+=lowbit(pos)){ if( c[pos] < tmp) c[pos] = tmp; else break; //没有更新父亲 } } ll query_ex(ll l ,ll r){ ll ex = -1; while( l <= r){ ll left = r - lowbit(r) +1; //范围内的最左点 if( left >= l) ex = std::max(ex,c[r]) , r = left-1; else ex = std::max(ex,a[r]),r--; } return ex; } } void init(){ scanf("%d%d",&n,&m); using namespace bit; int i,t; For(i,1,n){ scanf("%d",&t); update_range_c_c2(i, i, t); } } int main(){ clock_t program_start_clock = clock(); //开始记时 //=================== init(); int i; int o,l,r,x; using namespace bit; For(i,1,m){ scanf("%d",&o); if( o == 1){ scanf("%d%d%d",&l,&r,&x); update_range_c_c2(l,r,x); } else { scanf("%d%d",&l,&r); ll ans = query_range_sum(l, r); printf("%lld\n",ans); } } //=================== fprintf(stderr,"\n Total Time: %lf ms",double(clock()-program_start_clock)/(CLOCKS_PER_SEC / 1000)); return 0; }
true
d195c2679394bff6924f31bc29af7d1dadbdb3df
C++
Anubhav12345678/competitive-programming
/RemoveDuplicatesInASINGLYLINKEDLIST.cpp
UTF-8
1,337
3.40625
3
[]
no_license
{ #include <bits/stdc++.h> using namespace std; struct Node { int data; struct Node *next; Node(int x) { data = x; next = NULL; } }; void print(Node *root) { Node *temp = root; while(temp!=NULL) { cout<<temp->data<<" "; temp=temp->next; } } Node* removeDuplicates(Node *root); int main() { // your code goes here int T; cin>>T; while(T--) { int K; cin>>K; Node *head = NULL; Node *temp = head; for(int i=0;i<K;i++){ int data; cin>>data; if(head==NULL) head=temp=new Node(data); else { temp->next = new Node(data); temp=temp->next; } } Node *result = removeDuplicates(head); print(result); cout<<endl; } return 0; } } /*This is a function problem.You only need to complete the function given below*/ /* struct Node { int data; struct Node *next; Node(int x) { data = x; next = NULL; } };*/ // root: head node Node *removeDuplicates(Node *root) { if(root==NULL) return root; Node * h = root; while(h->next!=NULL) { if(h&&h->next&&h->data==h->next->data) { Node *cur = h->next->next; free(h->next); h->next=cur; // h->next = h->next->next; // free(cur); } else h=h->next; } return root; // your code goes here }
true
34f30f13f603c6f6ef047aca9410bc41e2464f84
C++
P1nk1e/zadacha2
/anti-aliasing/anti-aliasing/main.cpp
UTF-8
1,519
2.859375
3
[]
no_license
// // main.cpp // anti-aliasing // // Created by Владимир Киселев on 21.12.2020. // Copyright © 2020 Владимир Киселев. All rights reserved. // #include <iostream> #include "tgaimage.h" #include "linesMod.hpp" #include "linesMod.hpp" const TGAColor white = TGAColor(255, 255, 255, 255); const TGAColor red = TGAColor(255, 0, 0, 255); int main(int argc, char** argv) { TGAImage image(100, 100, TGAImage::RGB); int way = 0; std::cout << "1 - Bresenham's modified line algorithm" << std::endl << "2 - syaolin vu" << std::endl << "-> "; std::cin >> way; if (way == 1) { // Bresenham's modified line algorithm std::cout << std::endl << "enter x1, y1, x2, x2 -> "; int x1, x2, y1, y2; std::cin >> x1 >> y1 >> x2 >> y2; lineBrasenhemMod(x1, y1, x2, y2, image, white); // Алгоритм Брезенхема для отрезков image.set(x1, y1, red); image.set(x2, y2, red); } if (way == 2) { // simple DDA line algorithm std::cout << std::endl << "enter x1, y1, x2, x2 -> "; int x1, x2, y1, y2; std::cin >> x1 >> y1 >> x2 >> y2; lineVu(x1, y1, x2, y2, image, white); // Алгоритм Брезенхема для отрезков image.set(x1, y1, red); image.set(x2, y2, red); } image.flip_vertically(); // i want to have the origin at the left bottom corner of the image image.write_tga_file("output.tga"); return 0; }
true
2cac34582238ecdf49886a295952ff0166271b16
C++
mkoldaev/bible50cpp
/lang/fa/gen/Bible22.h
UTF-8
27,678
2.8125
3
[]
no_license
#include <map> #include <string> class Bible22 { struct fa1 { int val; const char *msg; }; struct fa2 { int val; const char *msg; }; struct fa3 { int val; const char *msg; }; struct fa4 { int val; const char *msg; }; struct fa5 { int val; const char *msg; }; struct fa6 { int val; const char *msg; }; struct fa7 { int val; const char *msg; }; struct fa8 { int val; const char *msg; }; public: static void view1() { struct fa1 poems[] = { {1, "1 غزل‌ غزلها كه‌ از آن‌ سلیمان‌ است‌. "}, {2, "2 محبوبه‌: او مرا به‌ بوسه‌های‌ دهان‌ خود ببوسد زیرا كه‌ محبّت‌ تو از شراب‌ نیكوتر است‌. "}, {3, "3 عطرهای‌ تو بوی‌ خوش‌ دارد و اسم‌ تو مثل‌ عطر ریخته‌ شده‌ می‌باشد. بنابراین‌ دوشیزگان‌، تو را دوست‌ می‌دارند. "}, {4, "4 مرا بِكِش‌ تا در عقب‌ تو بدویم‌. پادشاه‌ مرا به‌ حجله‌های‌ خود آورد. از تو وجد و شادی‌ خواهیم‌ كرد. محبّت‌ تو را از شراب‌ زیاده‌ ذكر خواهیم‌ نمود. تو را از روی‌ خلوص‌ دوست‌ می‌دارند. "}, {5, "5 ای‌ دختران‌ اورشلیم‌، من‌ سیه‌ فام‌ امّا جمیل‌ هستم‌، مثل‌ خیمه‌های‌ قیدار و مانند پرده‌های‌ سلیمان‌. "}, {6, "6 بر من‌ نگاه‌ نكنید چونكه‌ سیه‌فام‌ هستم‌، زیرا كه‌ آفتاب‌ مرا سوخته‌ است‌. پسران‌ مادرم‌ بر من‌ خشم‌ نموده‌، مرا ناطور تاكستانها ساختند، امّا تاكستان‌ خود را دیده‌بانی‌ ننمودم‌. "}, {7, "7 ای‌ حبیب‌ جان‌ من‌، مرا خبر ده‌ كه‌ كجا می‌چرانی‌ و در وقت‌ ظهر گلّه‌ را كجا می‌خوابانی‌؟ زیرا چرا نزد گله‌های‌ رفیقانت‌ مثل‌ آواره‌ گردم‌. "}, {8, "8 محبوب‌: ای‌ جمیل‌تر از زنان‌، اگر نمی‌دانی‌، در اثر گله‌ها بیرون‌ رو و بزغاله‌هایت‌ را نزد مسكن‌های‌شبانان‌ بچران‌. "}, {9, "9 ای‌ محبوبه‌ من‌، تو را به‌ اسبی‌ كه‌ در ارابۀ فرعون‌ باشد تشبیه‌ داده‌ام‌. "}, {10, "10 رخسارهایت‌ به‌ جواهرها و گردنت‌ به‌ گردن‌بندها چه‌ بسیار جمیل‌ است‌. "}, {11, "11 محبوبه‌: زنجیرهای‌ طلا با حَبّه‌های‌ نقره‌ برای‌ تو خواهیم‌ ساخت‌. "}, {12, "12 چون‌ پادشاه‌ بر سفره‌ خود می‌نشیند، سنبل‌ من‌ بوی‌ خود را می‌دهد. "}, {13, "13 محبوب‌ من‌، مرا مثل‌ طَبله‌ مرّ است‌ كه‌ در میان‌ پستانهای‌ من‌ می‌خوابد. "}, {14, "14 محبوب‌: محبوب‌ من‌، برایم‌ مثل‌ خوشه‌بان‌ در باغهای‌ عین‌جدی‌ می‌باشد. "}, {15, "15 اینك‌ تو زیبا هستی‌ ای‌ محبوبه‌ من‌، اینك‌ تو زیبا هستی‌ و چشمانت‌ مثل‌ چشمان‌ كبوتر است‌. "}, {16, "16 محبوبه‌: اینك‌ تو زیبا و شیرین‌ هستی‌ ای‌ محبوب‌ من‌ و تخت‌ ما هم‌ سبز است‌. "}, {17, "17 محبوب‌: تیرهای‌ خانه‌ ما از سرو آزاد است‌ و سقف‌ ما از چوب‌ صنوبر. "}, }; size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);} } static void view2() { struct fa2 poems[] = { {1, "1 محبوبه‌: من‌ نرگس‌ شارون‌ و سوسن‌ وادیها هستم‌. "}, {2, "2 محبوب‌: چنانكه‌ سوسن‌ در میان‌ خارها همچنان‌ محبوبه‌ من‌ در میان‌ دختران‌ است‌. "}, {3, "3 محبوبه‌: چنانكه‌ سیب‌ در میان‌ درختان‌ جنگل‌، همچنان‌ محبوب‌ من‌ در میان‌ پسران‌ است‌. در سایه‌ وی‌ به‌ شادمانی‌ نشستم‌ و میوه‌اش‌ برای‌ كامم‌ شیرین‌ بود. "}, {4, "4 مرا به‌ میخانه‌ آورد و عَلَم‌ وی‌ بالای‌ سر من‌ محبّت‌ بود. "}, {5, "5 مرا به‌ قرصهای‌ كشمش‌ تقویت‌ دهید و مرا به‌ سیبها تازه‌ سازید، زیرا كه‌ من‌ از عشق‌ بیمار هستم‌. "}, {6, "6 دست‌ چپش‌ در زیر سر من‌ است‌ و دست‌ راستش‌ مرا در آغوش‌ می‌كشد. "}, {7, "7 ای‌ دختران‌ اورشلیم‌، شما را به‌ غزالها و آهوهای‌ صحرا قسم‌ می‌دهم‌ كه‌ محبوب‌ مرا تا خودش‌ نخواهد بیدار نكنید و برنینگیزانید. "}, {8, "8 آواز محبوب‌ من‌ است‌، اینك‌ بر كوهها جستان‌ و بر تلّها خیزان‌ می‌آید. "}, {9, "9 محبوب‌ من‌ مانند غزال‌ یا بچه‌ آهو است‌. اینك‌ او در عقب‌ دیوار ما ایستاده‌، از پنجره‌ها می‌نگرد و از شبكه‌ها خویشتن‌ را نمایان‌ می‌سازد. "}, {10, "10 محبوب‌ من‌ مرا خطاب‌ كرده‌، گفت‌: ای‌ محبوبه‌ من‌ و ای‌ زیبایی‌ من‌ برخیز و بیا. "}, {11, "11 زیرا اینك‌ زمستان‌ گذشته‌ و باران‌ تمام‌ شده‌ و رفته‌ است‌. "}, {12, "12 گلها بر زمین‌ ظاهر شده‌ و زمان‌ اَلحان‌ رسیده‌ و آواز فاخته‌ در ولایت‌ ما شنیده‌ می‌شود. "}, {13, "13 درخت‌ انجیر میوه‌ خود را می‌رساند و موها گل‌ آورده‌، رایحه‌ خوش‌ می‌دهد. ای‌ محبوبه‌ من‌ و ای‌ زیبایی‌ من‌، برخیز و بیا. "}, {14, "14 محبوب‌: ای‌ كبوتر من‌ كه‌ در شكافهای‌ صخره‌ و در ستر سنگهای‌ خارا هستی‌، چهره‌ خود را به‌ من‌ بنما و آوازت‌ را به‌ من‌ بشنوان‌ زیرا كه‌ آواز تو لذیذ و چهره‌ات‌ خوشنما است‌. "}, {15, "15 شغالها، شغالهای‌ كوچك‌ را كه‌ تاكستانها را خراب‌ می‌كنند برای‌ ما بگیرید، زیرا كه‌ تاكستانهای‌ ما گل‌ آورده‌ است‌. "}, {16, "16 محبوبه‌: محبوبم‌ از آن‌ من‌ است‌ و من‌ از آن‌ وی‌ هستم‌. در میان‌ سوسنها می‌چراند. "}, {17, "17 ای‌ محبوب‌ من‌، برگرد و تا نسیم‌ روز بوزد و سایه‌ها بگریزد، (مانند) غزال‌ یا بچه‌ آهو بر كوههای‌ باتر باش‌. "}, }; size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);} } static void view3() { struct fa3 poems[] = { {1, "1 شبانگاه‌ در بستر خود او را كه‌ جانم‌ دوست‌می‌دارد طلبیدم‌. او را جستجو كردم‌ امّا نیافتم‌. "}, {2, "2 گفتم‌ الان‌ برخاسته‌، در كوچه‌ها و شوارع‌ شهر گشته‌، او را كه‌ جانم‌ دوست‌ می‌دارد خواهم‌ طلبید. او را جستجو كردم‌ امّا نیافتم‌. "}, {3, "3 كشیكچیانی‌ كه‌ در شهر گردش‌ می‌كنند، مرا یافتند. گفتم‌ كه‌ آیا محبوب‌ جان‌ مرا دیده‌اید؟ "}, {4, "4 از ایشان‌ چندان‌ پیش‌ نرفته‌ بودم‌ كه‌ او را كه‌ جانم‌ دوست‌ می‌دارد، یافتم‌. و او را گرفته‌، رها نكردم‌ تا به‌ خانه‌ مادر خود و به‌ حجره‌ والده‌خویش‌ در آوردم‌. "}, {5, "5 ای‌ دختران‌ اورشلیم‌، شما را به‌ غزالها و آهوهای‌ صحرا قسم‌ می‌دهم‌ كه‌ محبوب‌ مرا تا خودش‌ نخواهد بیدار مكنید و برمینگیزانید. "}, {6, "6 این‌ كیست‌ كه‌ مثل‌ ستونهای‌ دود از بیابان‌ برمی‌آید و به‌ مرّ و بخور و به‌ همه‌ عطریات‌ تاجران‌ معطّر است‌؟ "}, {7, "7 اینك‌ تخت‌ روان‌ سلیمان‌ است‌ كه‌ شصت‌ جبّار از جبّاران‌ اسرائیل‌ به‌ اطراف‌ آن‌ می‌باشند. "}, {8, "8 همگی‌ ایشان‌ شمشیر گرفته‌ و جنگ‌ آزموده‌ هستند. شمشیر هر یك‌ به‌ سبب‌ خوف‌شب‌ بر رانش‌ بسته‌ است‌. "}, {9, "9 سلیمان‌ پادشاه‌ تخت‌ روانی‌ برای‌ خویشتن‌ از چوب‌ لبنان‌ ساخت‌. "}, {10, "10 ستونهایش‌ را از نقره‌ و سقفش‌ را از طلا و كرسی‌اش‌ را از ارغوان‌ ساخت‌، و وسطش‌ به‌ محبّت‌ دختران‌ اورشلیم‌ مُعَرَّق‌ بود. "}, {11, "11 ای‌ دختران‌ صهیون‌، بیرون‌ آیید و سلیمان‌ پادشاه‌ را ببینید، با تاجی‌ كه‌ مادرش‌ در روز عروسی‌ وی‌ و در روز شادی‌ دلش‌ آن‌ را بر سر وی‌ نهاد. "}, }; size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);} } static void view4() { struct fa4 poems[] = { {1, "1 محبوب‌: اینك‌ تو زیبا هستی‌ ای‌ محبوبه‌ من‌، اینك تو زیبا هستی‌ و چشمانت‌ از پشت‌ بُرقِع‌ تو مثل‌ چشمان‌ كبوتر است‌ و موهایت‌ مثل‌ گله‌ بزها است‌ كه‌ بر جانب‌ كوه‌ جلعاد خوابیده‌اند. "}, {2, "2 دندانهایت‌ مثل‌ گله‌ گوسفندان‌ پشم‌ بریده‌ كه‌ از شستن‌ برآمده‌ باشند و همگی‌ آنها توأم‌ زاییده‌ و در آنها یكی‌ هم‌ نازاد نباشد. "}, {3, "3 لبهایت‌ مثل‌ رشته‌ قرمز و دهانت‌ جمیل‌ است‌ و شقیقه‌هایت‌ در عقب‌ بُرقِع‌ تو مانند پاره‌ انار است‌. "}, {4, "4 گردنت‌ مثل‌ برج‌ داود است‌ كه‌ به‌ جهت‌ سلاح‌ خانه‌ بنا شده‌ است‌ و در آن‌ هزار سپر یعنی‌ همه‌ سپرهای‌ شجاعان‌ آویزان‌ است‌. "}, {5, "5 دو پستانت‌ مثل‌ دو بچه‌ توأم‌ آهو می‌باشد كه‌ در میان‌ سوسنها می‌چرند، "}, {6, "6 تا نسیم‌ روز بوزد و سایه‌ها بگریزد. به‌ كوه‌ مرّ و به‌ تلّ كندر خواهم‌ رفت‌. "}, {7, "7 ای‌ محبوبه‌ من‌، تمامی‌ تو زیبا می‌باشد. در تو عیبی‌ نیست‌. "}, {8, "8 بیا با من‌ از لبنان‌ ای‌ عروس‌، با من‌ از لبنان‌ بیا. از قلّه‌ اَمانه‌ از قلّه‌ شَنیر و حَرمون‌ از مَغارَه‌های‌ شیرها و از كوههای‌ پلنگها بنگر. "}, {9, "9 ای‌ خواهر و عروس‌ من‌، دلم‌ را به‌ یكی‌ از چشمانت‌ و به‌ یكی‌ از گردن‌بندهای‌ گردنت‌ ربودی‌. "}, {10, "10 ای‌ خواهر و عروس‌ من‌، محبّتهایت‌ چه‌ بسیار لذیذاست‌. محبّتهایت‌ از شراب‌ چه‌ بسیار نیكوتر است‌ و بوی‌ عطرهایت‌ از جمیع‌ عطرها. "}, {11, "11 ای‌ عروس‌ من‌، لبهای‌ تو عسل‌ را می‌چكاند زیر زبان‌ تو عسل‌ و شیر است‌ و بوی‌ لباست‌ مثل‌ بوی‌ لبنان‌ است‌. "}, {12, "12 خواهر و عروس‌ من‌، باغی‌ بسته‌ شده‌ است‌. چشمه‌ مُقَفّل‌ و منبع‌ مختوم‌ است‌. "}, {13, "13 نهالهایت‌ بستان‌ انارها با میوه‌های‌ نفیسه‌ و بان‌ و سنبل‌ است‌. "}, {14, "14 سنبل‌ و زعفران‌ و نی‌ و دارچینی‌ با انواع‌ درختان‌ كندر، مرّ و عود با جمیع‌ عطرهای‌ نفیسه‌. "}, {15, "15 چشمه‌ باغها و بركه‌ آب‌ زنده‌ و نهرهایی‌ كه‌ از لبنان‌ جاری‌ است‌. "}, {16, "16 محبوبه‌: ای‌ باد شمال‌، برخیز و ای‌ باد جنوب‌، بیا. بر باغ‌ من‌ بوز تا عطرهایش‌ منتشر شود. محبوب‌ من‌ به‌ باغ‌ خود بیاید و میوه‌ نفیسه‌ خود را بخورد. "}, }; size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);} } static void view5() { struct fa5 poems[] = { {1, "1 محبوب‌: ای‌ خواهر و عروس‌ من‌، به‌ باغ‌ خود آمدم‌.مرّ خود را با عطرهایم‌ چیدم‌. شانه‌ عسل‌ خود را با عسل‌ خویش‌ خوردم‌. شراب‌ خود را با شیر خویش‌ نوشیدم‌. دختران‌ اورشلیم‌: ای‌ دوستان‌ بخورید، و ای‌ یاران‌ بنوشید، و به‌ سیری‌ بیاشامید. "}, {2, "2 محبوبه‌: من‌ در خواب‌ هستم‌ امّا دلم‌ بیدار است‌. آواز محبوب‌ من‌ است‌ كه‌ در را می‌كوبد (و می‌گوید): از برای‌ من‌ باز كن‌ ای‌ خواهر من‌! ای‌ محبوبه‌ من‌ و كبوترم‌ و ای‌ كامله‌ من‌! زیرا كه‌ سر من‌ از شبنم‌ وزلفهایم‌ از ترشّحات‌ شب‌ پر است‌. "}, {3, "3 رخت‌ خود را كندم‌ چگونه‌ آن‌ را بپوشم‌؟ پایهای‌ خود را شستم‌ چگونه‌ آنها را چركین‌ نمایم‌؟ "}, {4, "4 محبوب‌ من‌ دست‌ خویش‌ را از سوراخ‌ در داخل‌ ساخت‌ و احشایم‌ برای‌ وی‌ به‌ جنبش‌ آمد. "}, {5, "5 من‌ برخاستم‌ تا در را به‌ جهت‌ محبوب‌ خود باز كنم‌، و از دستم‌ مرّ و از انگشتهایم‌ مرّ صافی‌ بر دسته‌ قفل‌ بچكید. "}, {6, "6 به‌ جهت‌ محبوب‌ خود باز كردم‌؛ امّا محبوبم‌ روگردانیده‌، رفته‌ بود. چون‌ او سخن‌ می‌گفت‌ جان‌ از من‌ بدر شده‌ بود. او را جستجو كردم‌ و نیافتم‌ او را خواندم‌ و جوابم‌ نداد. "}, {7, "7 كشیكچیانی‌ كه‌ در شهر گردش‌ می‌كنند مرا یافتند، بزدند و مجروح‌ ساختند. دیده‌بانهای‌ حصارها بُرقِع‌ مرا از من‌ گرفتند. "}, {8, "8 ای‌ دختران‌ اورشلیم‌، شما را قسم‌ می‌دهم‌ كه‌ اگر محبوب‌ مرا بیابید، وی‌ را گویید كه‌ من‌ مریض‌ عشق‌ هستم‌. "}, {9, "9 دختران‌ اورشلیم‌: ای‌ زیباترین‌ زنان‌، محبوب‌ تو از سایر محبوبان‌ چه‌ برتری‌ دارد و محبوب‌ تو را بر سایر محبوبان‌ چه‌ فضیلت‌ است‌ كه‌ ما را چنین‌ قسم‌ می‌دهی‌؟ "}, {10, "10 محبوبه‌: محبوب‌ من‌ سفید و سرخ‌ فام‌ است‌، و بر هزارها افراشته‌ شده‌ است‌. "}, {11, "11 سر او طلای‌ خالص‌ است‌ و زلفهایش‌ به‌ هم‌ پیچیده‌ و مانند غُراب‌ سیاه‌ فام‌ است‌. "}, {12, "12 چشمانش‌ كبوتران‌ نزد نهرهای‌ آب‌ است‌، با شیر شسته‌ شده‌ و در چشمخانه‌ خود نشسته‌. "}, {13, "13 رخسارهایش‌ مثل‌ باغچه‌ بَلَسان‌ و پشته‌های‌ ریاحین‌ می‌باشد. لبهایش‌ سوسنها است‌ كه‌ از آنها مرّ صافی‌می‌چكد. "}, {14, "14 دستهایش‌ حلقه‌های‌ طلاست‌ كه‌ به‌ زبرجدّ مُنَقَّش‌ باشد و بَرِ او عاج‌ شفّاف‌ است‌ كه‌ به‌ یاقوت‌ زرد مُرَصَّع‌ بُوَد. "}, {15, "15 ساقهایش‌ ستونهای‌ مرمر بر پایه‌های‌ زرِ ناب‌ مؤسّس‌ شده‌، سیمایش‌ مثل‌ لبنان‌ و مانند سروهای‌ آزاد برگزیده‌ است‌. "}, {16, "16 دهان‌ او بسیار شیرین‌ و تمام‌ او مرغوبترین‌ است‌. این‌ است‌ محبوب‌ من‌ و این‌ است‌ یار من‌، ای‌ دختران‌ اورشلیم‌. "}, }; size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);} } static void view6() { struct fa6 poems[] = { {1, "1 دختران‌ اورشلیم‌: محبوب‌ تو كجا رفته‌ است‌ ای‌ زیباترین‌زنان‌؟ محبوب‌ تو كجا توجّه‌ نموده‌ است‌ تا او را با تو بطلبیم‌؟ "}, {2, "2 محبوبه‌: محبوب‌ من‌ به‌ باغ‌ خویش‌ و نزد باغچه‌های‌ بَلَسان‌ فرود شده‌ است‌، تا در باغات‌ بچراند و سوسنها بچیند. "}, {3, "3 من‌ از آن‌ محبوب‌ خود و محبوبم‌ از آن‌ من‌ است‌. در میان‌ سوسنها گله‌ را می‌چراند. "}, {4, "4 محبوب‌: ای‌ محبوبه‌ من‌، تو مثل‌ تِرْصَه‌ جمیل‌ و مانند اورشلیم‌ زیبا و مثل‌ لشكرهای‌ بیدق‌دار مَهیب‌ هستی‌. "}, {5, "5 چشمانت‌ را از من‌ برگردان‌ زیرا آنها بر من‌ غالب‌ شده‌ است‌. مویهایت‌ مثل‌ گله‌ بزها است‌ كه‌ بر جانب‌ كوه‌ جلعاد خوابیده‌ باشند. "}, {6, "6 دندانهایت‌ مانند گله‌ گوسفندان‌ است‌ كه‌ از شستن‌ برآمده‌ باشند. و همگی‌ آنها توأم‌ زاییده‌ و در آنها یكی‌ هم‌ نازاد نباشد. "}, {7, "7 شقیقه‌هایت‌ در عقب‌ برقع‌ تو مانند پاره‌ انار است‌. "}, {8, "8 شصت‌ ملكه‌ و هشتاد مُتعِه‌ و دوشیزگان‌ بیشماره‌ هستند. "}, {9, "9 امّا كبوتر من‌ و كامله‌ من‌ یكی‌ است‌. او یگانه‌ مادر خویش‌ و مختاره‌ والده‌ خود می‌باشد. دختران‌ او را دیده‌، خجسته‌ گفتند. ملكه‌ها و متعه‌ها بر او نگریستند و او را مدح‌ نمودند. "}, {10, "10 دختران‌ اورشلیم‌: این‌ كیست‌ كه‌ مثل‌ صبح‌ می‌درخشد؟ و مانند ماه‌ جمیل‌ و مثل‌ آفتاب‌ طاهر و مانند لشكر بیدق‌دار مهیب‌ است‌؟ "}, {11, "11 محبوب‌: به‌ باغ‌ درختان‌ جوز فرود شدم‌ تا سبزیهای‌ وادی‌ را بنگرم‌ و ببینم‌ كه‌ آیا مو شكوفه‌ آورده‌ و انار گل‌ كرده‌ است‌. "}, {12, "12 بی‌آنكه‌ ملتفت‌ شوم‌ كه‌ ناگاه‌ جانم‌ مرا مثل‌ عرابه‌های‌ عمّیناداب‌ ساخت‌. "}, {13, "13 دختران‌ اورشلیم‌: برگرد، برگرد ای‌ شولمّیت‌ برگرد، برگرد تا بر تو بنگریم‌. "}, }; size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);} } static void view7() { struct fa7 poems[] = { {1, "1 محبوب‌: در شولمیت‌ چه‌ می‌بینی‌؟ مثل‌ محفل‌ دو لشكر. ای‌ دخترِ مردِ شریف‌، پایهایت‌ در نعلین چه‌ بسیار زیبا است‌. حلقه‌های‌ رانهایت‌ مثل‌ زیورها می‌باشد كه‌ صنعت‌ دست‌ صنعت‌گر باشد. "}, {2, "2 ناف‌ تو مثل‌ كاسه‌ مدوّر است‌ كه‌ شراب‌ ممزوج‌ در آن‌ كم‌ نباشد. بَرِ تو توده‌ گندم‌ است‌ كه‌ سوسنها آن‌ را احاطه‌ كرده‌ باشد. "}, {3, "3 دو پستان‌ تو مثل‌ دو بچه‌ توأم‌ غزال‌ است‌. "}, {4, "4 گردن‌ تو مثل‌ برج‌ عاج‌ و چشمانت‌ مثل‌ بركه‌های‌ حَشبُون‌ نزد دروازه‌ بیت‌ رَبّیم‌. بینی‌ تو مثل‌ برج‌ لبنان‌ است‌ كه‌بسوی‌ دمشق‌ مشرف‌ می‌باشد. "}, {5, "5 سرت‌ بر تو مثل‌ كَرْمَلْ و موی‌ سرت‌ مانند ارغوان‌ است‌. و پادشاه‌ در طُرهّهایش‌ اسیر می‌باشد. "}, {6, "6 ای‌ محبوبه‌، چه‌ بسیار زیبا و چه‌ بسیار شیرین‌ به‌ سبب‌ لذّتها هستی‌. "}, {7, "7 این‌ قامت‌ تو مانند درخت‌ خرما و پستانهایت‌ مثل‌ خوشه‌های‌ انگور می‌باشد. "}, {8, "8 گفتم‌ كه‌ به‌ درخت‌ خرما برآمده‌، شاخه‌هایش‌ را خواهم‌ گرفت‌. و پستانهایت‌ مثل‌ خوشه‌های‌ انگور و بوی‌ نفس‌ تو مثل‌ سیبها باشد. "}, {9, "9 و دهان‌ تو مانند شراب‌ بهترین‌ برای‌ محبوبم‌ كه‌ به‌ ملایمت‌ فرو رود و لبهای‌ خفتگان‌ را متكلّم‌ سازد. "}, {10, "10 محبوبه‌: من‌ از آن‌ محبوب‌ خود هستم‌ و اشتیاق‌ وی‌ بر من‌ است. "}, {11, "11 بیا ای‌ محبوب‌ من‌ به‌ صحرا بیرون‌ برویم‌، و در دهات‌ ساكن‌ شویم‌. "}, {12, "12 و صبح‌ زود به‌ تاكستانها برویم‌ و ببینیم‌ كه‌ آیا انگور گل‌ كرده‌ و گلهایش‌ گشوده‌ و انارها گل‌ داده‌ باشد. در آنجا محبت‌ خود را به‌ تو خواهم‌ داد. "}, {13, "13 مهر گیاهها بوی‌ خود را می‌دهد و نزد درهای‌ ما، هر قسم‌ میوه‌ نفیس‌ تازه‌ و كُهنه‌ هست‌ كه‌ آنها را برای‌ تو ای‌ محبوب‌ من‌ جمع‌ كرده‌ام‌. "}, }; size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);} } static void view8() { struct fa8 poems[] = { {1, "1 كاش‌ كه‌ مثل‌ برادر من‌ كه‌ پستانهای‌ مادر مرا مكید می‌بودی‌، تا چون‌ تو را بیرون‌ می‌یافتم‌، تو را می‌بوسیدم‌ و مرا رسوا نمی‌ساختند. "}, {2, "2 تو را رهبری‌ می‌كردم‌ و به‌ خانه‌ مادرم‌ در می‌آوردم‌ تا مرا تعلیم‌ می‌دادی‌ تا شراب‌ ممزوج‌ و عَصیر انار خود را به‌ تو می‌نوشانیدم‌. "}, {3, "3 دست‌ چپ‌ او زیر سر من‌ می‌بود و دست‌ راستش‌ مرا در آغوش‌ می‌كشید. "}, {4, "4 ای‌ دختران‌ اورشلیم‌ شما را قسم‌ می‌دهم‌ كه‌ محبوب‌ مرا تا خودش‌ نخواهد بیدار نكنید و برنینگیزانید. "}, {5, "5 دختران‌ اورشلیم‌: این‌ كیست‌ كه‌ بر محبوب‌ خود تكیه‌ كرده‌، از صحرا برمی‌آید؟ محبوبه‌: زیر درخت‌ سیب‌ تو را برانگیختم‌ كه‌ در آنجا مـادرت‌ تـو را زاییـد. در آنجـا والـده‌ تـو را درد زه‌ گرفت‌. "}, {6, "6 مـرا مثل‌ خاتـم‌ بر دلت‌ و مثـل‌ نگیـن‌ بر بازویت‌ بگذار، زیرا كه‌ محبت‌ مثل‌ موت‌ زورآور است‌ و غیرت‌ مثل‌ هاویه‌ ستم‌كیش‌ می‌باشد. شعله‌هایش‌ شعله‌های‌ آتش‌ و لَهیب‌ یهوه‌ است‌. "}, {7, "7 آبهای‌ بسیار محبت‌ را خاموش‌ نتوانـد كـرد و سیلهـا آن‌ را نتوانـد فـرو نشانیـد. اگـر كسـی‌ تمامـی‌ امــوال‌ خانــه‌ خویـش‌ را بـرای‌ محبـت‌ بدهـد، آن‌ را البتّه‌ خـوار خواهنـد شمـرد. "}, {8, "8 دختران‌ اورشلیم‌: ما را خواهری‌ كوچك‌ است‌ كه‌ پستان‌ ندارد. به‌ جهت‌ خواهر خود در روزی‌ كه‌ او را خواستگاری‌ كنند، چه‌ بكنیم‌؟ "}, {9, "9 اگر دیوارمی‌بود، بر او برج‌ نقره‌ای‌ بنا می‌كردیم‌؛ و اگر دروازه‌ می‌بود، او را به‌ تخته‌های‌ سرو آزاد می‌پوشانیدیم‌. "}, {10, "10 محبوبه‌: من‌ دیوار هستم‌ و پستانهایم‌ مثل‌ برجها است‌. لهذا در نظر او از جمله‌ یابندگان‌ سلامتی‌ شده‌ام. "}, {11, "11 سلیمان‌ تاكستانی‌ در بَعْل‌ هامون‌ داشت‌ و تاكستان‌ را به‌ ناطوران‌ سپرد، كه‌ هر كس‌ برای‌ میوه‌اش‌ هزار نقره‌ بدهد. "}, {12, "12 تاكستانم‌ كه‌ از آن‌ من‌ است‌ پیش‌ روی‌ من‌ می‌باشد. برای‌ تو ای‌ سلیمان‌ هزار و برای‌ ناطورانِ میوه‌اش‌، دویست‌ خواهد بود. "}, {13, "13 محبوب‌: ای‌ (محبوبه‌) كه‌ در باغات‌ می‌نشینی‌، رفیقان‌ آواز تو را می‌شنوند، مرا نیز بشنوان‌. "}, {14, "14 محبوبه‌: ای‌ محبوب‌ من‌، فرار كن‌ و مثل‌ غزال‌ یا بچه‌ آهو بر كوههای‌ عطرّیات‌ باش‌. "}, }; size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);} } };
true