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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
4aeee868256cae8c31f5a6d16039eec8374c1ac7 | C++ | deeptadevkota/Compiler-Design-lab | /Week_7/Q3/p1.cpp | UTF-8 | 3,239 | 3.28125 | 3 | [] | no_license | #include <iostream>
using namespace std;
struct equation
{
char lf;
string rt;
};
int main()
{
int n;
cin >> n;
equation inp[n];
for (int i = 0; i < n; i++)
{
cout << "\nEquation: " << i + 1 << endl
<< endl;
cout << "LHS:";
cin >> inp[i].lf;
cout << "RHS:";
cin >> inp[i].rt;
}
cout << "The given segment of code is as follows:" << endl;
for (int i = 0; i < n; i++)
{
cout << inp[i].lf << " = " << inp[i].rt << endl;
}
cout << "\n\nRemoving the dead code...." << endl
<< endl;
// the loop is till n-1 the last equation LHS stores the answers
equation d_op[n];
int itr = 0;
for (int i = 0; i < n - 1; i++)
{
int flag = 0;
char temp = inp[i].lf;
for (int j = 0; j < n; j++)
{
for (int k = 0; k < inp[j].rt.size(); k++)
{
if (temp == inp[j].rt[k])
{
flag = 1;
break;
}
}
if (flag == 1)
{
d_op[itr].lf = temp;
d_op[itr].rt = inp[i].rt;
itr++;
break;
}
}
}
d_op[itr].lf = inp[n - 1].lf;
d_op[itr].rt = inp[n - 1].rt;
itr++;
cout << "\nCode segment after dead code removal" << endl;
for (int i = 0; i < itr; i++)
{
cout << d_op[i].lf << " = " << d_op[i].rt << endl;
}
cout << "\n\nApplying variable propagation...." << endl
<< endl;
for (int i = 0; i < itr; i++)
{
string str = d_op[i].rt;
for (int j = i + 1; j < itr; j++)
{
if (str == d_op[j].rt)
{
char temp = d_op[j].lf;
//replacing the current LHS with the LHS of the previous equation with the same RHS
d_op[j].lf = d_op[i].lf;
for (int k = 0; k < itr; k++)
{
//checking the if the replaced LHS is present in any equations
if (temp == d_op[k].rt[k])
{
d_op[k].rt[k] = d_op[j].lf;
}
}
}
}
}
cout << "\nCode segment after applying variable propagation" << endl;
for (int i = 0; i < itr; i++)
{
cout << d_op[i].lf << " = " << d_op[i].rt << endl;
}
cout << "\nDead code can occur after applying variable propagation" << endl;
cout << "\n\nFurther removing the dead code...." << endl
<< endl;
for (int i = 0; i < itr; i++)
{
for (int j = i + 1; j < itr; j++)
{
if (d_op[i].lf == d_op[j].lf && d_op[i].rt == d_op[j].rt)
{
d_op[i].rt = "Null";
}
}
}
cout << "\nThe code segment obtained after optimization is as follows:\n"
<< endl;
for (int i = 0; i < itr; i++)
{
if (d_op[i].rt != "Null")
cout << d_op[i].lf << " = " << d_op[i].rt << endl;
}
}
/*
SAMPLE INPUT-1:
5
a
9
b
c+d
e
c+d
f
b+e
r
f
SAMPLE INPUT-2
3
e
a*b
x
a
d
x*b+4
SAMPLE INPUT-3:
3
c
a*b
x
a
d
a*b+4
*/ | true |
58249c12929ce9236dc41de6d2e6d261f53c92a6 | C++ | RedaBoumediene/dp | /countNumberOfPalindromeSubstring.cpp | UTF-8 | 738 | 3.015625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int countSubstrings(string s) {
int n=s.size() , ans=0 ;
bool dp[n][n]={false};
for(int i=0;i<n;i++)
dp[i][i]=true , ans++;
for(int taille=2;taille<=n;taille++){
for(int i=0;i<=n-taille;i++){
int j=taille+i-1;
if(s[i]==s[j]){
if(taille==2){
dp[i][j]=true;
}
else{
dp[i][j]=dp[i+1][j-1];
}
}
else{
dp[i][j]=false;
}
if(dp[i][j])
ans++;
}
}
return ans;
}
int main() {
string s;cin>>s;
cout<<countSubstrings(s);
return 0;
}
| true |
4b6183929b144776a807a8c2d300af7026968400 | C++ | tstr/TSEngine | /tools/rcschema/test/test.cpp | WINDOWS-1252 | 7,064 | 2.6875 | 3 | [
"MIT"
] | permissive | /*
Resource Schema Generator conformance tester
*/
#include <tscore/types.h>
#include <tscore/strings.h>
#include <sstream>
#include <iostream>
using namespace std;
using namespace ts;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Generated headers
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "Test0.rcs.h"
#include "Test1.rcs.h"
#include "Test2.rcs.h"
#include "Test3.rcs.h"
using namespace test;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Helper functions
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Assertion helper
void _assert(const char* func, const char* expr, bool eval)
{
if (!eval)
{
cerr << "[" << func << "] Assertion failed: " << expr << endl;
exit(-1);
}
}
#define assert(expr) _assert(__FUNCTION__, #expr, (expr))
#define array_length(x) sizeof(x) / sizeof(x[0])
template<typename Type, size_t expectLength>
void assertArrayEquals(Type(&expectArr)[expectLength], const rc::ArrayView<Type>& actualArr)
{
assert(expectLength == actualArr.length());
for (int i = 0; i < expectLength; i++)
{
assert(expectArr[i] == actualArr.at(i));
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Test cases
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void test0()
{
stringstream data(ios::binary | ios::out | ios::in);
Test0Builder builder;
builder.set_field0('\xff'); //byte
builder.set_field1(true); //bool
builder.set_field2(-1); //int16
builder.set_field3(-1); //int32
builder.set_field4(-1); //int64
builder.set_field5(1); //uint16
builder.set_field6(1); //uint32
builder.set_field7(1); //uint64
builder.set_field8(1.0f); //float32
builder.set_field9(1.0); //float64
builder.build(data);
assert(data.good());
//Test loader
rc::ResourceLoader loader(data);
assert(loader.success());
Test0& reader = loader.deserialize<Test0>();
assert(reader.field0() == (byte)'\xff');
assert(reader.field1() == true);
assert(reader.field2() == -1);
assert(reader.field3() == -1);
assert(reader.field4() == -1);
assert(reader.field5() == 1);
assert(reader.field6() == 1);
assert(reader.field7() == 1);
assert(reader.field8() == 1.0f);
assert(reader.field9() == 1.0);
}
void test1()
{
stringstream data(ios::binary | ios::out | ios::in);
uint32 array0[] = { 1, 3, 2, 5, 4 };
byte array1[] = { 0, 3, 127, 255, 1 };
vector<String> arrayOfStrings = { "abc", "123", "def", "456", "*&^$$%$7637GGyugy" };
//Test builder
Test1Builder builder;
builder.set_str(builder.createString("123abc"));
builder.set_array0(builder.createArray(array0, array_length(array0)));
builder.set_array1(builder.createArray(array1, array_length(array1)));
builder.set_strArray(builder.createArrayOfStrings(arrayOfStrings));
builder.build(data);
assert(data.good());
//Test loader
rc::ResourceLoader loader(data);
assert(loader.success());
Test1& reader = loader.deserialize<Test1>();
assert(String(reader.str().data()) == "123abc");
assertArrayEquals(array0, reader.array0());
assertArrayEquals(array1, reader.array1());
for (uint32 i = 0; i < reader.strArray().length(); i++)
{
assert(arrayOfStrings[i] == reader.strArray().at(i).data());
}
}
void test2()
{
stringstream data(ios::binary | ios::out | ios::in);
Vector3 pos = { 15.0f, 30.0f, 5.0f};
Vector3 vel = { 4.0f, 3.0f, 0.0f };
Matrix3x3 rot = {
{ 1.0f, 0.0f, 0.0f },
{ 0.0f, 1.0f, 0.0f },
{ 0.0f, 0.0f, 1.0f }
};
Test2Builder builder;
builder.set_position(pos);
builder.set_velocity(vel);
builder.set_rotation(rot);
builder.set_flag(FLAG_2);
builder.build(data);
assert(data.good());
//Test loader
rc::ResourceLoader loader(data);
assert(loader.success());
Test2& reader = loader.deserialize<Test2>();
assert(reader.position().x == pos.x);
assert(reader.position().y == pos.y);
assert(reader.position().z == pos.z);
assert(reader.velocity().x == vel.x);
assert(reader.velocity().y == vel.y);
assert(reader.velocity().z == vel.z);
assert(reader.flag() == FLAG_2);
}
void test3()
{
// Test binary tree
{
stringstream data(ios::binary | ios::out | ios::in);
/*
4
/ \
2 6
/
5
*/
BinaryTreeBuilder tBuilder;
NodeBuilder rootNode(tBuilder);
{
//Build left child of root node
NodeBuilder LNode(rootNode);
LNode.set_value(2);
rootNode.set_nodeLeft(LNode.build());
//Build right child of root node
NodeBuilder RNode(rootNode);
RNode.set_value(6);
{
//Build left child of right child of root node
RNode.set_nodeLeft(NodeBuilder(RNode).set_value(5).build());
}
rootNode.set_nodeRight(RNode.build());
}
//Build root node
tBuilder.set_rootNode(rootNode.set_value(4).build());
//Build tree
tBuilder.build(data);
assert(data.good());
rc::ResourceLoader loader(data);
assert(loader.success());
BinaryTree& tree = loader.deserialize<BinaryTree>();
assert(tree.rootNode().value() == 4);
assert(tree.rootNode().nodeLeft().value() == 2);
assert(tree.rootNode().nodeRight().value() == 6);
assert(tree.rootNode().nodeRight().nodeLeft().value() == 5);
}
////////////////////////////////////////////////////////////////////////////
// Test tree
{
stringstream data(ios::binary | ios::out | ios::in);
TreeBuilder t;
TreeNodeBuilder root(t);
//Create array of nodes
rc::Ref<TreeNode> nodes[] =
{
TreeNodeBuilder(root).set_value(1).build(),
TreeNodeBuilder(root).set_value(2).build(),
TreeNodeBuilder(root).set_value(3).build(),
TreeNodeBuilder(root).set_value(4).build(),
TreeNodeBuilder(root).set_value(5).build()
};
//Set array of nodes to root
root.set_nodes(root.createArrayOfRefs<TreeNode>(nodes, array_length(nodes)));
//Set root value
root.set_value(11);
//Set root node
t.set_root(root.build());
//Build tree
t.build(data);
rc::ResourceLoader loader(data);
assert(loader.success());
Tree& tree = loader.deserialize<Tree>();
assert(tree.has_root() == true);
assert(tree.root().nodes().at(0).has_nodes() == false);
assert(tree.root().value() == 11);
assert(tree.root().nodes().length() == 5);
assert(tree.root().nodes().at(0).value() == 1);
assert(tree.root().nodes().at(1).value() == 2);
assert(tree.root().nodes().at(2).value() == 3);
assert(tree.root().nodes().at(3).value() == 4);
assert(tree.root().nodes().at(4).value() == 5);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char** argv)
{
//Execute test cases
test0();
test1();
test2();
test3();
return 0;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
| true |
bbceac191c5f522aab99d9b8ca29ff74fd191166 | C++ | OliverGeisel/Matrix | /SQR_Matrix.cpp | UTF-8 | 472 | 2.9375 | 3 | [] | no_license |
#include "SQR_Matrix.h"
SQR_Matrix::SQR_Matrix(unsigned int n = 1) : Matrix(n, n, 0.0) {
}
SQR_Matrix::SQR_Matrix(unsigned int n, bool random = false) : Matrix(n, n, random) {
}
SQR_Matrix::SQR_Matrix(unsigned int n, double value = 0.0) : Matrix(n, n, value) {}
Matrix SQR_Matrix::Union_Matrix(unsigned int size) {
Matrix back = SQR_Matrix(size, 0.0);
for (unsigned int i = 0; i < size; i++) {
back.setContent(i, i, 1.0);
}
return back;
}
| true |
073b79875da1448ed3e53f52e60a6f0f86d8183b | C++ | ifknot/rpp | /rpp/data_frame.h | UTF-8 | 631 | 2.65625 | 3 | [
"MIT"
] | permissive |
#pragma once
#include <unordered_map>
#include "data_types.h"
#include "variant_vector.h"
namespace R {
/**
* @brief As per R language definition the following are the characteristics of an R-ish data frame:
*
* + The column names should be non-empty.
* + The row names should be unique.
* + The data stored in a data frame can be of an r-type.
* + Each column should contain same number of data items.
*
* @note *none* of these characteristics are checked for.
*/
using data_frame = std::unordered_map<r_string, variant_vector>;
}
std::ostream& operator << (std::ostream& os, const R::data_frame& df);
| true |
0ca5b2803ff4e5ee0e1e650a525cf243242944c0 | C++ | Pinming/NOJ_201909 | /t002.cpp | UTF-8 | 414 | 2.78125 | 3 | [] | no_license | # include <iostream>
# include <iomanip>
using namespace std;
# define PI 3.1415926
int main()
{
double r, h, l, s, sq, vq, vz;
cin >> r >> h;
l = 2 * PI * r;
s = PI * r * r;
sq = 4 * PI * r * r;
vq = 4.0 / 3 * PI * r * r * r;
vz = s * h;
cout << setiosflags(ios::fixed) << setprecision(2);
cout << l << endl;
cout << s << endl;
cout << sq << endl;
cout << vq << endl;
cout << vz << endl;
return 0;
} | true |
90639aa8fb9f2656ad73506c135b810d5586f6c8 | C++ | enderdaniil/OOP_labs | /lab_4/3.cpp | UTF-8 | 326 | 3.46875 | 3 | [] | no_license | #include <iostream>
using namespace std;
void zeroSmaller(int &a, int &b)
{
if (a < b)
{
a = 0;
}
else
{
b = 0;
}
}
int main()
{
setlocale(LC_ALL, "Russian");
cout << "Введите числа(a и b): ";
int a, b;
cin >> a >> b;
zeroSmaller(a, b);
cout << "a = " << a << ", b = " << b;
return 0;
}
| true |
808e747ff32ef20401d2cd85cbc5dd610b044565 | C++ | avast/retdec | /deps/eigen/Eigen/src/Core/Dot.h | UTF-8 | 11,484 | 2.71875 | 3 | [
"MPL-2.0",
"MIT",
"Zlib",
"JSON",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"GPL-2.0-only",
"NCSA",
"WTFPL",
"BSL-1.0",
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | permissive | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2008, 2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_DOT_H
#define EIGEN_DOT_H
namespace Eigen {
namespace internal {
// helper function for dot(). The problem is that if we put that in the body of dot(), then upon calling dot
// with mismatched types, the compiler emits errors about failing to instantiate cwiseProduct BEFORE
// looking at the static assertions. Thus this is a trick to get better compile errors.
template<typename T, typename U,
// the NeedToTranspose condition here is taken straight from Assign.h
bool NeedToTranspose = T::IsVectorAtCompileTime
&& U::IsVectorAtCompileTime
&& ((int(T::RowsAtCompileTime) == 1 && int(U::ColsAtCompileTime) == 1)
| // FIXME | instead of || to please GCC 4.4.0 stupid warning "suggest parentheses around &&".
// revert to || as soon as not needed anymore.
(int(T::ColsAtCompileTime) == 1 && int(U::RowsAtCompileTime) == 1))
>
struct dot_nocheck
{
typedef scalar_conj_product_op<typename traits<T>::Scalar,typename traits<U>::Scalar> conj_prod;
typedef typename conj_prod::result_type ResScalar;
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE
static ResScalar run(const MatrixBase<T>& a, const MatrixBase<U>& b)
{
return a.template binaryExpr<conj_prod>(b).sum();
}
};
template<typename T, typename U>
struct dot_nocheck<T, U, true>
{
typedef scalar_conj_product_op<typename traits<T>::Scalar,typename traits<U>::Scalar> conj_prod;
typedef typename conj_prod::result_type ResScalar;
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE
static ResScalar run(const MatrixBase<T>& a, const MatrixBase<U>& b)
{
return a.transpose().template binaryExpr<conj_prod>(b).sum();
}
};
} // end namespace internal
/** \fn MatrixBase::dot
* \returns the dot product of *this with other.
*
* \only_for_vectors
*
* \note If the scalar type is complex numbers, then this function returns the hermitian
* (sesquilinear) dot product, conjugate-linear in the first variable and linear in the
* second variable.
*
* \sa squaredNorm(), norm()
*/
template<typename Derived>
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE
typename ScalarBinaryOpTraits<typename internal::traits<Derived>::Scalar,typename internal::traits<OtherDerived>::Scalar>::ReturnType
MatrixBase<Derived>::dot(const MatrixBase<OtherDerived>& other) const
{
EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived)
EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)
EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(Derived,OtherDerived)
#if !(defined(EIGEN_NO_STATIC_ASSERT) && defined(EIGEN_NO_DEBUG))
typedef internal::scalar_conj_product_op<Scalar,typename OtherDerived::Scalar> func;
EIGEN_CHECK_BINARY_COMPATIBILIY(func,Scalar,typename OtherDerived::Scalar);
#endif
eigen_assert(size() == other.size());
return internal::dot_nocheck<Derived,OtherDerived>::run(*this, other);
}
//---------- implementation of L2 norm and related functions ----------
/** \returns, for vectors, the squared \em l2 norm of \c *this, and for matrices the Frobenius norm.
* In both cases, it consists in the sum of the square of all the matrix entries.
* For vectors, this is also equals to the dot product of \c *this with itself.
*
* \sa dot(), norm(), lpNorm()
*/
template<typename Derived>
EIGEN_STRONG_INLINE typename NumTraits<typename internal::traits<Derived>::Scalar>::Real MatrixBase<Derived>::squaredNorm() const
{
return numext::real((*this).cwiseAbs2().sum());
}
/** \returns, for vectors, the \em l2 norm of \c *this, and for matrices the Frobenius norm.
* In both cases, it consists in the square root of the sum of the square of all the matrix entries.
* For vectors, this is also equals to the square root of the dot product of \c *this with itself.
*
* \sa lpNorm(), dot(), squaredNorm()
*/
template<typename Derived>
EIGEN_STRONG_INLINE typename NumTraits<typename internal::traits<Derived>::Scalar>::Real MatrixBase<Derived>::norm() const
{
return numext::sqrt(squaredNorm());
}
/** \returns an expression of the quotient of \c *this by its own norm.
*
* \warning If the input vector is too small (i.e., this->norm()==0),
* then this function returns a copy of the input.
*
* \only_for_vectors
*
* \sa norm(), normalize()
*/
template<typename Derived>
EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::PlainObject
MatrixBase<Derived>::normalized() const
{
typedef typename internal::nested_eval<Derived,2>::type _Nested;
_Nested n(derived());
RealScalar z = n.squaredNorm();
// NOTE: after extensive benchmarking, this conditional does not impact performance, at least on recent x86 CPU
if(z>RealScalar(0))
return n / numext::sqrt(z);
else
return n;
}
/** Normalizes the vector, i.e. divides it by its own norm.
*
* \only_for_vectors
*
* \warning If the input vector is too small (i.e., this->norm()==0), then \c *this is left unchanged.
*
* \sa norm(), normalized()
*/
template<typename Derived>
EIGEN_STRONG_INLINE void MatrixBase<Derived>::normalize()
{
RealScalar z = squaredNorm();
// NOTE: after extensive benchmarking, this conditional does not impact performance, at least on recent x86 CPU
if(z>RealScalar(0))
derived() /= numext::sqrt(z);
}
/** \returns an expression of the quotient of \c *this by its own norm while avoiding underflow and overflow.
*
* \only_for_vectors
*
* This method is analogue to the normalized() method, but it reduces the risk of
* underflow and overflow when computing the norm.
*
* \warning If the input vector is too small (i.e., this->norm()==0),
* then this function returns a copy of the input.
*
* \sa stableNorm(), stableNormalize(), normalized()
*/
template<typename Derived>
EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::PlainObject
MatrixBase<Derived>::stableNormalized() const
{
typedef typename internal::nested_eval<Derived,3>::type _Nested;
_Nested n(derived());
RealScalar w = n.cwiseAbs().maxCoeff();
RealScalar z = (n/w).squaredNorm();
if(z>RealScalar(0))
return n / (numext::sqrt(z)*w);
else
return n;
}
/** Normalizes the vector while avoid underflow and overflow
*
* \only_for_vectors
*
* This method is analogue to the normalize() method, but it reduces the risk of
* underflow and overflow when computing the norm.
*
* \warning If the input vector is too small (i.e., this->norm()==0), then \c *this is left unchanged.
*
* \sa stableNorm(), stableNormalized(), normalize()
*/
template<typename Derived>
EIGEN_STRONG_INLINE void MatrixBase<Derived>::stableNormalize()
{
RealScalar w = cwiseAbs().maxCoeff();
RealScalar z = (derived()/w).squaredNorm();
if(z>RealScalar(0))
derived() /= numext::sqrt(z)*w;
}
//---------- implementation of other norms ----------
namespace internal {
template<typename Derived, int p>
struct lpNorm_selector
{
typedef typename NumTraits<typename traits<Derived>::Scalar>::Real RealScalar;
EIGEN_DEVICE_FUNC
static inline RealScalar run(const MatrixBase<Derived>& m)
{
EIGEN_USING_STD_MATH(pow)
return pow(m.cwiseAbs().array().pow(p).sum(), RealScalar(1)/p);
}
};
template<typename Derived>
struct lpNorm_selector<Derived, 1>
{
EIGEN_DEVICE_FUNC
static inline typename NumTraits<typename traits<Derived>::Scalar>::Real run(const MatrixBase<Derived>& m)
{
return m.cwiseAbs().sum();
}
};
template<typename Derived>
struct lpNorm_selector<Derived, 2>
{
EIGEN_DEVICE_FUNC
static inline typename NumTraits<typename traits<Derived>::Scalar>::Real run(const MatrixBase<Derived>& m)
{
return m.norm();
}
};
template<typename Derived>
struct lpNorm_selector<Derived, Infinity>
{
typedef typename NumTraits<typename traits<Derived>::Scalar>::Real RealScalar;
EIGEN_DEVICE_FUNC
static inline RealScalar run(const MatrixBase<Derived>& m)
{
if(Derived::SizeAtCompileTime==0 || (Derived::SizeAtCompileTime==Dynamic && m.size()==0))
return RealScalar(0);
return m.cwiseAbs().maxCoeff();
}
};
} // end namespace internal
/** \returns the \b coefficient-wise \f$ \ell^p \f$ norm of \c *this, that is, returns the p-th root of the sum of the p-th powers of the absolute values
* of the coefficients of \c *this. If \a p is the special value \a Eigen::Infinity, this function returns the \f$ \ell^\infty \f$
* norm, that is the maximum of the absolute values of the coefficients of \c *this.
*
* In all cases, if \c *this is empty, then the value 0 is returned.
*
* \note For matrices, this function does not compute the <a href="https://en.wikipedia.org/wiki/Operator_norm">operator-norm</a>. That is, if \c *this is a matrix, then its coefficients are interpreted as a 1D vector. Nonetheless, you can easily compute the 1-norm and \f$\infty\f$-norm matrix operator norms using \link TutorialReductionsVisitorsBroadcastingReductionsNorm partial reductions \endlink.
*
* \sa norm()
*/
template<typename Derived>
template<int p>
#ifndef EIGEN_PARSED_BY_DOXYGEN
inline typename NumTraits<typename internal::traits<Derived>::Scalar>::Real
#else
MatrixBase<Derived>::RealScalar
#endif
MatrixBase<Derived>::lpNorm() const
{
return internal::lpNorm_selector<Derived, p>::run(*this);
}
//---------- implementation of isOrthogonal / isUnitary ----------
/** \returns true if *this is approximately orthogonal to \a other,
* within the precision given by \a prec.
*
* Example: \include MatrixBase_isOrthogonal.cpp
* Output: \verbinclude MatrixBase_isOrthogonal.out
*/
template<typename Derived>
template<typename OtherDerived>
bool MatrixBase<Derived>::isOrthogonal
(const MatrixBase<OtherDerived>& other, const RealScalar& prec) const
{
typename internal::nested_eval<Derived,2>::type nested(derived());
typename internal::nested_eval<OtherDerived,2>::type otherNested(other.derived());
return numext::abs2(nested.dot(otherNested)) <= prec * prec * nested.squaredNorm() * otherNested.squaredNorm();
}
/** \returns true if *this is approximately an unitary matrix,
* within the precision given by \a prec. In the case where the \a Scalar
* type is real numbers, a unitary matrix is an orthogonal matrix, whence the name.
*
* \note This can be used to check whether a family of vectors forms an orthonormal basis.
* Indeed, \c m.isUnitary() returns true if and only if the columns (equivalently, the rows) of m form an
* orthonormal basis.
*
* Example: \include MatrixBase_isUnitary.cpp
* Output: \verbinclude MatrixBase_isUnitary.out
*/
template<typename Derived>
bool MatrixBase<Derived>::isUnitary(const RealScalar& prec) const
{
typename internal::nested_eval<Derived,1>::type self(derived());
for(Index i = 0; i < cols(); ++i)
{
if(!internal::isApprox(self.col(i).squaredNorm(), static_cast<RealScalar>(1), prec))
return false;
for(Index j = 0; j < i; ++j)
if(!internal::isMuchSmallerThan(self.col(i).dot(self.col(j)), static_cast<Scalar>(1), prec))
return false;
}
return true;
}
} // end namespace Eigen
#endif // EIGEN_DOT_H
| true |
6eed45211ebb393f57a4e29d0dd9b8486c576a41 | C++ | de-passage/basics.cpp | /tests/balanced_binary_tree.cpp | UTF-8 | 1,643 | 3.4375 | 3 | [] | no_license | #include <gtest/gtest.h>
#include <stdexcept>
#include "balanced_binary_tree.hpp"
#include "utility.hpp"
using BBT = BalancedBinaryTree<int>;
TEST(BalancedBinaryTree, DefaultCtor) {
BBT b{};
ASSERT_EQ(b.size(), 0_z);
ASSERT_EQ(b.begin(), b.end());
}
TEST(BalancedBinaryTree, ListCtor) {
BBT b{1, 2, 3, 4, 5, 6, 7};
ASSERT_EQ(b.size(), 7_z);
for (int i = 1; i <= 7; ++i) {
ASSERT_NO_THROW(b[i]);
ASSERT_NE(b.find(i), b.end());
}
int r = 1;
for (auto v : b) {
ASSERT_EQ(r++, v);
}
ASSERT_EQ(r, 8);
}
TEST(BalancedBinaryTree, CpyCtor) {
BBT b = {1, 2, 3, 4};
BBT b2 = b;
ASSERT_EQ(b.size(), 4_z);
ASSERT_EQ(b2.size(), 4_z);
int r = 1;
for (auto it = b.begin(), it2 = b2.begin(); it != b.end(); ++it, ++it2) {
ASSERT_EQ(*it, r);
ASSERT_EQ(*it2, r);
r++;
}
}
TEST(BalancedBinaryTree, MoveCtor) {
BBT b = {1, 2, 3, 4, 5};
BBT b2 = std::move(b);
ASSERT_EQ(b.size(), 0_z);
ASSERT_EQ(b2.size(), 5_z);
for (int r = 1; r <= 5; ++r) {
ASSERT_NO_THROW(b2[r]);
ASSERT_THROW(b[r], std::out_of_range);
}
}
TEST(BalancedBinaryTree, CopyAssignment) {
BBT b;
BBT b2 = {1, 2, 3, 4, 5};
b = b2;
ASSERT_EQ(b.size(), 5_z);
ASSERT_EQ(b2.size(), 5_z);
int r = 1;
for (auto it = b.begin(), it2 = b2.begin(); it != b.end(); ++it, ++it2) {
ASSERT_EQ(*it, r);
ASSERT_EQ(*it2, r);
r++;
}
}
TEST(BalancedBinaryTree, MoveAssignment) {
BBT b2;
BBT b = {1, 2, 3, 4, 5};
b2 = std::move(b);
ASSERT_EQ(b.size(), 0_z);
ASSERT_EQ(b2.size(), 5_z);
for (int r = 1; r <= 5; ++r) {
ASSERT_NO_THROW(b2[r]);
ASSERT_THROW(b[r], std::out_of_range);
}
} | true |
bb5cf39f653f3b04a251bc9944e658e08eac4a1a | C++ | leobelmontLu/DesignPattern | /FilterPattern/FilterPattern.cpp | UTF-8 | 4,186 | 3.171875 | 3 | [] | no_license | // FilterPattern.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "FilterPattern.h"
static void printPersons(std::vector<Person> persons);
int main()
{
std::vector<Person> m_VecPerson;
m_VecPerson.push_back( Person("Robert", "Male", "Single") );
m_VecPerson.push_back( Person("John", "Male", "Married") );
m_VecPerson.push_back( Person("Laura", "Female", "Married") );
m_VecPerson.push_back( Person("Diana", "Female", "Single") );
m_VecPerson.push_back( Person("Mike", "Male", "Single") );
m_VecPerson.push_back( Person("Bobby", "Male", "Single") );
Criteria *male = new CriteriaMale();
Criteria *female = new CriteriaFemale();
Criteria *single = new CriteriaSingle();
Criteria *singleMale = new AndCriteria(*single, *male);
Criteria *singleOrFemale = new OrCriteria(*single, *female);
cout << "Males: ";
printPersons(male->meetCriteria(m_VecPerson));
cout << "\nFemales: ";
printPersons(female->meetCriteria(m_VecPerson));
cout << "\nSingle Males: ";
printPersons(singleMale->meetCriteria(m_VecPerson));
cout << "\nSingle Or Females: ";
printPersons(singleOrFemale->meetCriteria(m_VecPerson));
}
static void printPersons(std::vector<Person> persons)
{
for (Person person : persons)
{
cout << "Person : [ Name : " + person.GetName() + ", Gender : " + person.GetGender() + ", Marital Status : " + person.GetMaritalStatus()+ " ]" << endl;
}
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
Person::Person(string _name, string _gender, string _maritalStatus)
{
name = _name;
gender = _gender;
maritalStatus = _maritalStatus;
}
std::vector<Person> CriteriaMale::meetCriteria(std::vector<Person> _VecPerson)
{
std::vector<Person> malePersons;
for (Person _person : _VecPerson)
{
if (_person.GetGender() == "Male")
{
malePersons.push_back(_person);
}
}
return malePersons;
}
std::vector<Person> CriteriaFemale::meetCriteria(std::vector<Person> _VecPerson)
{
std::vector<Person> femalePersons;
for (Person _person : _VecPerson)
{
if (_person.GetGender() == "Female")
{
femalePersons.push_back(_person);
}
}
return femalePersons;
}
std::vector<Person> CriteriaSingle::meetCriteria(std::vector<Person> _VecPerson)
{
std::vector<Person> SinglePersons;
for (Person _person : _VecPerson)
{
if (_person.GetMaritalStatus() == "Single")
{
SinglePersons.push_back(_person);
}
}
return SinglePersons;
}
AndCriteria::AndCriteria(Criteria &_criteria, Criteria &_otherCriteria)
{
criteria = &_criteria;
otherCriteria = &_otherCriteria;
}
std::vector<Person> AndCriteria::meetCriteria(std::vector<Person> _VecPerson)
{
std::vector<Person> firstPersons = criteria->meetCriteria(_VecPerson);
return otherCriteria->meetCriteria(firstPersons);
}
OrCriteria::OrCriteria(Criteria & _criteria, Criteria & _otherCriteria)
{
criteria = &_criteria;
otherCriteria = &_otherCriteria;
}
std::vector<Person> OrCriteria::meetCriteria(std::vector<Person> _VecPerson)
{
std::vector<Person> firstPersons = criteria->meetCriteria(_VecPerson);
std::vector<Person> otherPersons = otherCriteria->meetCriteria(_VecPerson);
std::vector<Person> outPersons;
bool bFind = false;
for (Person otherPerson : otherPersons)
{
for (Person firstPerson : firstPersons)
{
if (otherPerson.GetName() == firstPerson.GetName() && otherPerson.GetGender() == firstPerson.GetGender() && otherPerson.GetMaritalStatus() == firstPerson.GetMaritalStatus())
{
bFind = true;
break;
}
}
if(!bFind)
outPersons.push_back(otherPerson);
}
return outPersons;
}
| true |
e4b86e3075424e109e5bcdabe7fac4e03f5ae994 | C++ | Manan007224/street-coding | /Leetcode/unique_paths.cpp | UTF-8 | 474 | 3.015625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef vector<vi> vii;
class Solution {
public:
int uniquePaths(int m, int n) {
vii dp(m,vi(n));
for(int i=0; i<m; i++) dp[i][0] = 1;
for(int j=0; j<n; j++) dp[0][j] = 1;
for(int i=1; i<m; i++) {
for(int j=1; j<n; j++) {
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m-1][n-1];
}
};
int main() {
Solution sln;
cout << sln.uniquePaths(1,2) << endl;
return 0;
} | true |
25a8957526b8a089994dfe02579e11c7beadc400 | C++ | lis0517/BOJ_ | /apr.2020after/20200505/n_2752/n_2752.cpp | UTF-8 | 1,478 | 2.90625 | 3 | [
"MIT"
] | permissive | // n_2752.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다.
//
#include <iostream>
using namespace std;
int main()
{
int a[3];
cin >> a[0] >> a[1] >> a[2];
//sort를 쓰면 쉽게 할수있지만..
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 2; ++j)
{
if (a[j + 1] < a[j])
{
int temp = a[j + 1];
a[j + 1] = a[j];
a[j] = temp;
}
}
}
cout << a[0] << ' ' << a[1] << ' ' << a[2];
}
// 프로그램 실행: <Ctrl+F5> 또는 [디버그] > [디버깅하지 않고 시작] 메뉴
// 프로그램 디버그: <F5> 키 또는 [디버그] > [디버깅 시작] 메뉴
// 시작을 위한 팁:
// 1. [솔루션 탐색기] 창을 사용하여 파일을 추가/관리합니다.
// 2. [팀 탐색기] 창을 사용하여 소스 제어에 연결합니다.
// 3. [출력] 창을 사용하여 빌드 출력 및 기타 메시지를 확인합니다.
// 4. [오류 목록] 창을 사용하여 오류를 봅니다.
// 5. [프로젝트] > [새 항목 추가]로 이동하여 새 코드 파일을 만들거나, [프로젝트] > [기존 항목 추가]로 이동하여 기존 코드 파일을 프로젝트에 추가합니다.
// 6. 나중에 이 프로젝트를 다시 열려면 [파일] > [열기] > [프로젝트]로 이동하고 .sln 파일을 선택합니다.
| true |
19c52b0b0138758b5cf3181f2e206a6d8b89e3f0 | C++ | mikecancilla/CPlusPlusPlayground | /CPPPlayground/Tuple.cpp | UTF-8 | 331 | 3.09375 | 3 | [] | no_license | #include <string>
#include <tuple>
#include <iostream>
std::tuple<std::string, std::string> GetTuple()
{
return std::make_tuple("hello", "There");
}
void DoTupleStuff()
{
std::tuple<std::string, std::string> strings = GetTuple();
std::string s1 = std::get<0>(strings);
std::string s2 = std::get<1>(strings);
} | true |
dbc5941339c31dd92c1809353a488bc05d2ed67e | C++ | westlicht/teensy-template | /src/TextWidget.h | UTF-8 | 1,219 | 2.984375 | 3 | [] | no_license | #pragma once
#include "Print.h"
#include "Painter.h"
class TextWidget : public Print {
public:
TextWidget(const Point &pos, const Size &size,
Painter::HAlignment hAlignment, Painter::VAlignment vAlignment,
Painter::Font font,
uint16_t foreground, uint16_t background) :
_pos(pos),
_size(size),
_hAlignment(hAlignment),
_vAlignment(vAlignment),
_font(font),
_foreground(foreground),
_background(background),
_dirty(true)
{
_text[0] = '\0';
}
void draw(Painter &painter, bool force = false) {
if (_dirty || force) {
painter.setFont(_font);
painter.setTextColor(_foreground, _background);
painter.printAligned(_pos.x, _pos.y, _size.x, _size.y, _hAlignment, _vAlignment, _text);
_dirty = false;
}
}
protected:
virtual size_t write(uint8_t b) override {
return 0;
}
private:
Point _pos;
Size _size;
Painter::HAlignment _hAlignment;
Painter::VAlignment _vAlignment;
Painter::Font _font;
uint16_t _foreground;
uint16_t _background;
char _text[16];
bool _dirty;
};
| true |
c7637873a6a450b8d48fbdf21ada042eec8a8107 | C++ | denis-gubar/Leetcode | /Hash Table/0325. Maximum Size Subarray Sum Equals k.cpp | UTF-8 | 449 | 2.578125 | 3 | [] | no_license | class Solution {
public:
int maxSubArrayLen(vector<int>& nums, int k) {
int result = 0;
int N = nums.size();
vector<int> cum(N + 1);
unordered_map<int, int> M;
M[cum[0]] = 0;
for (int i = 0; i < N; ++i)
{
cum[i + 1] = cum[i] + nums[i];
M[cum[i + 1]] = i + 1;
}
for (int i = 0; i <= N; ++i)
{
int value = k + cum[i];
if (M.find(value) != M.end())
result = max({ result, M[value] - i });
}
return result;
}
}; | true |
38fba2860d71c64cbd02798bf6271b72e6afc701 | C++ | hoseogame/20121705 | /mini/Tetris/tetris.cpp | UHC | 8,696 | 2.75 | 3 | [] | no_license | #include "tetris.h"
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
//
void Tetris::Update()
{
int key = KeyInput();
switch( stage )
{
case INIT :
press_any_key( key );
break;
case READY :
level_select( key );
break;
case RUNNING :
m_block->Move( key );
// ٴ̳ ٸ Ҵٸ ħ
if( m_block->GetBlockState() == 2 )
merge_block( m_block->GetBlockX(), m_block->GetBlockY() );
// ִ Ȯ
m_full_line_num = check_full_line();
if( m_full_line_num != 0 )
full_line_Set();
if( stage_data[m_level].clear_line == m_line )
{
++m_level;
if( m_level >= MAX_STAGE )
{
stage = SUCCESS;
}
m_line = 0;
}
// ~
if( GameOver() )
stage = FAILED;
break;
case SUCCESS:
case FAILED:
if( key == 'y' || key == 'Y' )
{
stage = READY;
Init();
}
if( key == 'n' || key == 'N' )
stage = RESULT;
break;
case RESULT:
m_bIsGameOver = true;
break;
}
}
// -
void Tetris::Render()
{
switch( stage )
{
case INIT:
show_logo();
break;
case READY:
input_data();
break;
case RUNNING:
m_block->Draw();
show_gamestat();
if( m_full_line_num != 0 )
full_line_erase();
break;
case SUCCESS:
m_block->Draw();
show_gamestat();
show_cleargame();
break;
case FAILED:
m_block->Draw();
show_gamestat();
show_gameover();
break;
case RESULT :
break;
}
}
bool Tetris::Exit()
{
if( m_bIsGameOver )
{
stage = INIT;
Init();
return true;
}
return false;
}
//
void Tetris::show_gameover()
{
screen->SetColor( Screen::RED );
screen->ScreenPrint( 15, 8, "" );
screen->ScreenPrint( 15, 9, "**************************" );
screen->ScreenPrint( 15, 10, "* GAME OVER *" );
screen->ScreenPrint( 15, 11, "* Y : replay N : exit *" );
screen->ScreenPrint( 15, 12, "**************************" );
screen->ScreenPrint( 15, 13, "" );
}
// Ŭ
void Tetris::show_cleargame()
{
screen->SetColor( Screen::GREEN );
screen->ScreenPrint( 15, 8, "" );
screen->ScreenPrint( 15, 9, "**************************" );
screen->ScreenPrint( 15, 10, "* GAME CLEAR *" );
screen->ScreenPrint( 15, 11, "* Y : replay N : exit *" );
screen->ScreenPrint( 15, 12, "**************************" );
screen->ScreenPrint( 15, 13, "" );
}
// ,
void Tetris::show_gamestat()
{
char string[50];
screen->SetColor( Screen::GRAY );
screen->ScreenPrint( 35, 7, "STAGE" );
sprintf_s( string, "%d", m_level + 1 );
screen->ScreenPrint( 41, 7, string );
screen->ScreenPrint( 35, 9, "SCORE" );
sprintf_s( string, "%d", m_score );
screen->ScreenPrint( 35, 10, string );
screen->ScreenPrint( 35, 12, "LINES" );
sprintf_s( string, "%d", stage_data[m_level].clear_line - m_line );
screen->ScreenPrint( 35, 13, string );
}
// ΰ ȭ
void Tetris::show_logo()
{
clock_t curTime = clock();
screen->SetColor( Screen::SKY_BLUE );
screen->ScreenPrint( 13, 3, "" );
screen->ScreenPrint( 13, 4, "ߡߡ ߡߡ ߡߡ ߡ " );
screen->ScreenPrint( 13, 5, " ߡ " );
screen->ScreenPrint( 13, 6, " ߡߡ ߡ " );
screen->ScreenPrint( 13, 7, " ߡ " );
screen->ScreenPrint( 13, 8, " ߡߡ " );
screen->ScreenPrint( 13, 9, "" );
screen->ScreenPrint( 28, 20, "Please Press Any Key~!" );
if( curTime - m_oldTime > m_printTime )
{
for( int i = 0; i < 4; ++i )
{
angle[i] = rand() % 4;
shape[i] = rand() % 7;
}
m_oldTime = curTime;
}
m_block->show_cur_block( shape[0], angle[0], 6, 14 );
m_block->show_cur_block( shape[1], angle[1], 12, 14 );
m_block->show_cur_block( shape[2], angle[2], 19, 14 );
m_block->show_cur_block( shape[3], angle[3], 24, 14 );
}
// Ű Է READY Ѿ
void Tetris::press_any_key( int nKey )
{
if( nKey != 0 )
stage = READY;
}
//
void Tetris::level_select( int nKey )
{
if( nKey != 0 && nKey != '0' && nKey <= '8')
{
char clevel = nKey;
int level = atoi( &clevel );
m_level = level - 1;
stage = RUNNING;
LevelSet();
}
}
// ġ Լ
void Tetris::merge_block( int x, int y )
{
int i, j;
for( i = 0; i<4; i++ )
{
for( j = 0; j<4; j++ )
{
m_block->SetTotalBlock( y + i, x + j, m_block->GetTotalBlock( y + i, x + j ) | m_block->GetBlock( i, j ) );
//m_total_block[y + i][x + j] |= m_block[shape][angle][i][j];
}
}
m_block->NextBlockInit();
}
// ä ȯ
int Tetris::check_full_line()
{
int i, j;
for( i = 0; i<MAX_SIZE_Y - 1; i++ )
{
for( j = 1; j<MAX_SIZE_X - 1; j++ )
{/*m_total_block[i][j]*/
if( m_block->GetTotalBlock( i, j ) == 0 )
break;
}
if( j == MAX_SIZE_X - 1 ) // ä
{
return i;
}
}
return 0;
}
// ä ʱȭ Ŵ
void Tetris::full_line_Set()
{
++m_line;
for( int k = m_full_line_num; k>0; k-- )
{
for( int j = 1; j < MAX_SIZE_X - 1; j++ )
m_block->SetTotalBlock( k, j, m_block->GetTotalBlock( k - 1, j ) );
//m_total_block[k][j] = m_total_block[k - 1][j];
}
for( int j = 1; j < MAX_SIZE_X - 1; j++ )
m_block->SetTotalBlock( 0, j, 0 );
//m_total_block[0][j] = 0;
m_score += 100 + (m_level * 10) + (rand() % 10);
}
// ä
void Tetris::full_line_erase()
{
int j;
//show_total_block();
screen->SetColor( Screen::BLUE );
for( j = 1; j<MAX_SIZE_X - 1; j++ )
{
screen->ScreenPrint( (j * 2 + AB_X), m_full_line_num + AB_Y, " " );
}
m_full_line_num = 0;
}
// ȭ
void Tetris::input_data()
{
screen->SetColor( Screen::GRAY );
screen->ScreenPrint( 10, 7, "<GAME KEY>" );
screen->ScreenPrint( 10, 8, " UP : Rotate Block " );
screen->ScreenPrint( 10, 9, " DOWN : Move One-Step Down " );
screen->ScreenPrint( 10, 10, " SPACE: Move Bottom Down " );
screen->ScreenPrint( 10, 11, " LEFT : Move Left " );
screen->ScreenPrint( 10, 12, " RIGHT: Move Right " );
screen->ScreenPrint( 10, 13, "" );
screen->ScreenPrint( 10, 3, "Select Start level[1-8]: \b\b\b\b\b\b\b" );
}
bool Tetris::GameOver()
{
if( m_block->GetBlockState() == 1 )
{
return true;
}
return false;
}
// Ŭ ӵ Ȯ
void Tetris::LevelSet()
{
m_block->SetMoveTime( stage_data[m_level].speed );
m_block->SetStickRate( stage_data[m_level].stick_rate );
}
// ʱ
void Tetris::Init()
{
m_block = new Block();
stage = INIT;
m_printTime = 1000;
m_level = 0;
m_line = 0;
m_score = 0;
m_full_line_num = 0;
m_bIsGameOver = false;
// ʱȭ ------------------
stage_data[0].speed = 1000;
stage_data[0].stick_rate = 20;
stage_data[0].clear_line = 20;
stage_data[1].speed = 1000;
stage_data[1].stick_rate = 18;
stage_data[1].clear_line = 20;
stage_data[2].speed = 800;
stage_data[2].stick_rate = 18;
stage_data[2].clear_line = 20;
stage_data[3].speed = 800;
stage_data[3].stick_rate = 17;
stage_data[3].clear_line = 20;
stage_data[4].speed = 700;
stage_data[4].stick_rate = 16;
stage_data[4].clear_line = 20;
stage_data[5].speed = 700;
stage_data[5].stick_rate = 14;
stage_data[5].clear_line = 20;
stage_data[6].speed = 400;
stage_data[6].stick_rate = 14;
stage_data[6].clear_line = 20;
stage_data[7].speed = 400;
stage_data[7].stick_rate = 13;
stage_data[7].clear_line = 20;
stage_data[8].speed = 300;
stage_data[8].stick_rate = 12;
stage_data[8].clear_line = 20;
stage_data[9].speed = 300;
stage_data[9].stick_rate = 11;
stage_data[9].clear_line = 100;
// ------------------------------------
// ʱ ȭ鿡
for( int i = 0; i < 4; ++i )
{
angle[i] = rand() % 4;
shape[i] = rand() % 7;
}
LevelSet();
}
void Tetris::Release()
{
if( m_block != nullptr )
delete m_block;
m_block = nullptr;
} | true |
dcbbb74416c375c77fde190226dd660c03e0f8dc | C++ | yechang1897/algorithm | /Array/leetcode_15_3sum.cpp | UTF-8 | 7,281 | 3.15625 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<vector>
#include<unordered_map>
#include<set>
// #include<map>
using namespace std;
//先排序,然后遍历
// vector<vector<int>> threeSum(vector<int>& nums) {
// sort(nums.begin(), nums.end());
// int len = (int)nums.size();
// int l = 0, r = len - 1;
// int mid = 0;
// vector<vector<int>> res;
// while(l <= r - 2) {
// cout << "before" << " l: " << l << " r: " << r << " mid: " << mid << endl;
// vector<int> tempRes;
// int temp = nums[l] + nums[r];
// mid = 0;
// cout << temp << endl;
// if (temp <= 0) {
// mid = r - 1;
// while (mid > l) {
// if (nums[mid] + temp == 0) {
// tempRes.push_back(nums[l]);
// tempRes.push_back(nums[mid]);
// tempRes.push_back(nums[r]);
// res.push_back(tempRes);
// r--;
// mid = 0;
// for (int num : tempRes) {
// cout << num << " ";
// }
// cout << endl;
// break;
// }
// mid--;
// }
// if(nums[mid] < 0) {
// l++;
// mid = 0;
// }
// mid = 0;
// } else {
// mid = l + 1;
// while (mid < r) {
// if (nums[mid] + temp == 0) {
// tempRes.push_back(nums[l]);
// tempRes.push_back(nums[mid]);
// tempRes.push_back(nums[r]);
// res.push_back(tempRes);
// res.push_back(tempRes);
// l++;
// mid = 0;
// for (int num : tempRes) {
// cout << num << " ";
// }
// cout << endl;
// break;
// }
// mid++;
// }
// if(nums[mid] >= 0) {
// r--;
// mid = 0;
// }
// mid = 0;
// }
// cout << "after" << " l: " << l << " r: " << r << " mid: " << mid << endl;
// }
// sort(res.begin(), res.end());
// res.erase(unique(res.begin(), res.end()), res.end());
// return res;
// }
//无法得到所有的三元组
// vector<vector<int>> threeSum_2(vector<int>& nums) {
// sort(nums.begin(), nums.end());
// int len = (int)nums.size();
// int l = 0, r = len - 1;
// vector<vector<int>> res;
// while(l <= r - 2) {
// int temp = nums[l] + nums[r];
// int i = l + 1;
// while(i < r) {
// if(nums[i] + temp == 0) {
// vector<int> temp;
// temp.push_back(nums[l]);
// temp.push_back(nums[i]);
// temp.push_back(nums[r]);
// res.push_back(temp);
// break;
// }
// i++;
// }
// if((i - l) > (r - i)) {
// l++;
// } else {
// r--;
// }
// }
// sort(res.begin(), res.end());
// res.erase(unique(res.begin(), res.end()), res.end());
// return res;
// }
// vector<int> twoSum(vector<int>& nums, int begin, int target) {
// vector<int> res(2, 0);
// unordered_map<int,int> map;
// for(int i = 0; i < (int)nums.size(); i++) {
// if (i == begin) continue;
// int temp = target - nums[i];
// if (map.find(temp) != map.end()) {
// res[0] = i;
// res[1] = map.find(temp)->second;
// return res;
// } else {
// map.insert(pair<int, int>(nums[i], i));
// }
// }
// sort(res.begin(), res.end());
// res.erase(unique(res.begin(), res.end()), res.end());
// return res;
// }
// void two_sum(vector<int>& nums,int i,int target,vector<vector<int>> &result){
// int j = (int)nums.size()-1;
// int b = i-1;
// while(i<j){
// if(nums[i]+nums[j] == target){
// result.push_back(vector<int>{nums[b],nums[i],nums[j]});
// //处理重复的情况
// i++;
// j--;
// while(i<j && nums[i] == nums[i-1]) i++;
// while(i<j && nums[j+1] == nums[j]) j--;
// }else{
// if(nums[i]+nums[j] < target)
// i++;
// else
// j--;
// }
// }
// return;
// }
// vector<vector<int>> threeSum(vector<int>& nums) {
// // set<vector<int>> result;
// vector<vector<int>> result2;
// sort(nums.begin(),nums.end());
// for(int i=0;i<(int)nums.size();i++)
// if(i>0&&nums[i-1]== nums[i])
// continue;
// else
// two_sum(nums,i+1,-nums[i],result2);
// return result2;
// }
void two_sum2(vector<int>& nums, int beg, int target, vector<vector<int>>& res) {
int j = (int)nums.size() - 1;
int i = beg - 1;
while (beg < j) {
if(nums[beg] + nums[j] == target) {
res.push_back(vector<int>{nums[i], nums[beg], nums[j]});
beg++;
j--;
while(beg < j && nums[beg] == nums[beg + 1]) {
beg++;
}
while(beg < j && nums[j] == nums[j - 1]) {
j--;
}
} else {
if(nums[beg] + nums[j] < target) {
beg++;
} else {
j--;
}
}
}
}
vector<vector<int>> threesum2(vector<int>& nums) {
vector<vector<int>> res;
sort(nums.begin(), nums.end());
for(int i = 0; i < (int)nums.size(); i++) {
if(i > 0 && nums[i - 1] == nums[i]) {
continue;
} else {
two_sum2(nums, i + 1, -nums[i], res);
}
}
return res;
}
// vector<vector<int>> threeSum_2(vector<int>& nums) {
// sort(nums.begin(), nums.end());
// int len = (int) nums.size();
// int target = 0;
// vector<vector<int>> res;
// vector<int> temp(3,0);
// while(target < len) {
// vector<int> temp2 = twoSum(nums, target + 1, -nums[target]);
// if(temp2[0] != temp2[1]) {
// temp[0] = nums[target];
// temp[1] = nums[temp2[0]];
// temp[2] = nums[temp2[1]];
// res.push_back(temp);
// }
// target++;
// }
// return res;
// }
int main() {
// vector<int> nums = {-2,0,1,1,2};
// vector<int> nums = {-4, -1, -1, 0, 1, 2};
vector<int> nums = {-1,0,1,2,-1,-4,-2,-3,3,0,4};
// vector<int> nums = {-4, -3, -2, -1, -1, 0, 0, 1, 2, 3, 4};
// vector<vector<int>> test = {{0, 0, 0}, {0, 0, 0}};
// sort(test.begin(), test.end());
// test.erase(unique(test.begin(), test.end()), test.end());
// for(vector<int> temp: test) {
// for (int i : temp) {
// cout << i << " ";
// }
// cout << endl;
// }
vector<vector<int>> res;
res = threesum2(nums);
for(vector<int> temp: res) {
for (int i : temp) {
cout << i << " ";
}
cout << endl;
}
} | true |
31dcb31d65d9e03a91732324aac6b78b27ff3c9f | C++ | shriyam26/Data-Structures-and-Algortihms | /Tree/Inorder successor of BST.cpp | UTF-8 | 2,315 | 4.1875 | 4 | [] | no_license | // C program for above approach
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* minValue(struct node* node);
/*
If right subtree of node is not NULL, then succ lies in right subtree. Do the following.
Go to right subtree and return the node with minimum key value in the right subtree.
If right subtree of node is NULL, then start from the root and use search-like technique. Do the following.
Travel down the tree, if a node’s data is greater than root’s data then go right side, otherwise, go to left side.
*/
struct node* inOrderSuccessor(struct node* root, struct node* n)
{
if (n->right != NULL)
return minValue(n->right);
struct node* succ = NULL;
while (root != NULL)
{
if (n->data < root->data)
{
succ = root;
root = root->left;
}
else if (n->data > root->data)
root = root->right;
else
break;
}
return succ;
}
struct node* minValue(struct node* node)
{
struct node* current = node;
while (current->left != NULL)
{
current = current->left;
}
return current;
}
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(
struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
struct node* insert(struct node* root,
int data)
{
if(!root){
return newNode(data);
}
if(root->data > data){
root->left = insert(root->left, data);
}
else{
root->right = insert(root->right, data);
}
return root;
}
/* Driver program to test above functions*/
int main()
{
struct node *root = NULL, *temp, *succ;
root = insert(root, 20);
root = insert(root, 8);
root = insert(root, 22);
root = insert(root, 4);
root = insert(root, 12);
root = insert(root, 10);
root = insert(root, 14);
temp = root->left->right->right;
succ = inOrderSuccessor(root, temp);
if (succ != NULL)
printf(
"\n Inorder Successor of %d is %d ",
temp->data, succ->data);
else
printf("\n Inorder Successor doesn't exit");
return 0;
} | true |
eb3d63fc0dc2390b9605dbdb89d94d81206f493e | C++ | bedjovski/iptool | /iptool/iptools/utility/utility.h | UTF-8 | 832 | 2.546875 | 3 | [] | no_license | #ifndef UTILITY_H
#define UTILITY_H
#include "../image/image.h"
#include <sstream>
#include <math.h>
class utility
{
public:
utility();
virtual ~utility();
static std::string intToString(int number);
static int checkValue(int value);
static void gamp(image &src, image &tgt, int ROI[3][6], int n); // gradient amplitude
static void bamp(image &src, image &tgt, int ROI[3][6], int n); // binary derived from gradient amplitude by threshholding
static void bang(image &src, image &tgt, int ROI[3][6], int n); // binary derived from angle from gradient amplitude by threshholding
static void colgamp(image &src, image &tgt, int ROI[3][6], int n); // gradient amplitude for colorful pics
static void HSIamp(image &src, image &tgt, int ROI[3][6], int n); // binary derived from gradient amplitude on I
};
#endif
| true |
bf56f5f89b286994a8f577b73ae7a046f8b076c9 | C++ | syo0e/Algorithm | /cpp/baekjoon/1003 fibonacci/main.cpp | UTF-8 | 540 | 2.953125 | 3 | [] | no_license | /*
피보나치 수에서 0이 나타나는 개수와 1이 나타나는 개수 또한 피보나치 수임을 수학적 귀납법으로 증명할 수 있다.
*/
#include <iostream>
using namespace std;
int main() {
int a[41],b[41];
int N,num;
a[0]=1, a[1]=0;
b[0]=0, b[1]=1;
for(int i=2; i<=40; i++)
{
a[i]=a[i-1]+a[i-2];
b[i]=b[i-1]+b[i-2];
}
scanf("%d",&N);
for(int i =0; i<N; i++)
{
scanf("%d",&num);
printf("%d %d\n",a[num],b[num]);
}
return 0;
}
| true |
d32a021350bac77251bf26e5a19d5f2859feaaa3 | C++ | CSUF-CPSC121-2021S01/siligame-05-HRB-NO1 | /game.h | UTF-8 | 6,052 | 2.625 | 3 | [] | no_license | #ifndef GAME_H
#define GAME_H
#include <vector>
#include "cpputils/graphics/image.h"
#include "cpputils/graphics/image_event.h"
#include "game_element.h"
#include "opponent.h"
#include "player.h"
class Game : public graphics::AnimationEventListener,
public graphics::MouseEventListener {
public:
Game(int width, int height)
: width_(width), height_(height), screen(width, height) {}
Game() : Game(800, 600) {}
graphics::Image &GetGameScreen() { return screen; }
std::vector<std::unique_ptr<Opponent>> &GetOpponents() { return oppo; }
std::vector<std::unique_ptr<OpponentProjectile>> &GetOpponentProjectiles() {
return oppopro;
}
std::vector<std::unique_ptr<PlayerProjectile>> &GetPlayerProjectiles() {
return playpro;
}
Player &GetPlayer() { return player; }
void CreateOpponents() {
for (int i = 0; i < 2; i++) {
Opponent opponent(50 + 100 * i, 50);
std::unique_ptr<Opponent> opponentFactory =
std::make_unique<Opponent>(10, 10);
oppo.push_back(std::move(opponentFactory));
}
}
void Init() {
player.SetX(200);
player.SetY(200);
screen.AddMouseEventListener(*this);
screen.AddAnimationEventListener(*this);
}
void MoveGameElements() {
for (int d = 0; d < oppo.size(); d++) {
if (oppo[d]->GetIsActive()) {
oppo[d]->Move(screen);
}
}
for (int e = 0; e < oppopro.size(); e++) {
if (oppopro[e]->GetIsActive()) {
oppopro[e]->Move(screen);
}
}
for (int f = 0; f < playpro.size(); f++) {
if (playpro[f]->GetIsActive()) {
playpro[f]->Move(screen);
}
}
}
void FilterIntersections() {
for (int g = 0; g < oppo.size(); g++) {
if (player.GetIsActive() && oppo[g]->GetIsActive() &&
player.IntersectsWith(oppo[g].get())) {
oppo[g]->SetIsActive(false);
player.SetIsActive(false);
has_lost_ = true;
}
}
for (int h = 0; h < oppopro.size(); h++) {
if (player.GetIsActive() && oppopro[h]->GetIsActive() &&
player.IntersectsWith(oppopro[h].get())) {
oppopro[h]->SetIsActive(false);
player.SetIsActive(false);
has_lost_ = true;
}
}
for (int m = 0; m < playpro.size(); m++) {
for (int l = 0; l < oppo.size(); l++) {
if (playpro[m]->GetIsActive() && oppo[l]->GetIsActive() &&
oppo[l]->IntersectsWith(playpro[m].get())) {
playpro[m]->SetIsActive(false);
oppo[l]->SetIsActive(false);
if (player.GetIsActive()) {
score_++;
}
}
}
}
}
void UpdateScreen() {
screen.DrawRectangle(0, 0, 800, 600, 255, 255, 255);
screen.DrawText(1, 1, "Score:" + std::to_string(score_), 50, 0, 0, 0);
for (int a = 0; a < oppo.size(); a++) {
if (oppo[a]->GetIsActive()) {
oppo[a]->Draw(screen);
}
}
for (int b = 0; b < oppopro.size(); b++) {
if (oppopro[b]->GetIsActive()) {
oppopro[b]->Draw(screen);
}
}
for (int c = 0; c < playpro.size(); c++) {
if (playpro[c]->GetIsActive()) {
playpro[c]->Draw(screen);
}
}
if (player.GetIsActive()) {
player.Draw(screen);
} else {
screen.DrawText(300, 200, "Game Over", 50, 0, 0, 0);
}
}
void Start() { screen.ShowUntilClosed(); }
void OnAnimationStep() {
if (oppo.size() < 1) {
CreateOpponents();
}
MoveGameElements();
LaunchProjectiles();
FilterIntersections();
RemoveInactive();
UpdateScreen();
screen.Flush();
}
void OnMouseEvent(const graphics::MouseEvent &mouseEvent) {
if (mouseEvent.GetMouseAction() == graphics::MouseAction::kMoved ||
mouseEvent.GetMouseAction() == graphics::MouseAction::kDragged) {
int temp_x = player.GetX();
int temp_y = player.GetY();
player.SetX(mouseEvent.GetX() - player.GetWidth() / 2);
player.SetY(mouseEvent.GetY() - player.GetHeight() / 2);
if (player.GetX() > 800 || player.GetX() < 0) {
player.SetX(temp_x);
}
if (player.GetY() > 600 || player.GetY() < 0) {
player.SetY(temp_y);
}
}
if (mouseEvent.GetMouseAction() == graphics::MouseAction::kPressed) {
std::unique_ptr<PlayerProjectile> OnMouseEvent_oppo =
std::make_unique<PlayerProjectile>(player.GetX(), player.GetY());
playpro.push_back(std::move(OnMouseEvent_oppo));
} else if (mouseEvent.GetMouseAction() == graphics::MouseAction::kDragged) {
std::unique_ptr<PlayerProjectile> OnMouseEvent_oppo =
std::make_unique<PlayerProjectile>(player.GetX(), player.GetY());
playpro.push_back(std::move(OnMouseEvent_oppo));
}
}
int GetScore() { return score_; }
bool HasLost() { return has_lost_; }
void LaunchProjectiles() {
for (int i = 0; i < oppo.size(); i++) {
std::unique_ptr<OpponentProjectile> oppoFactory =
oppo[i]->LaunchProjectile();
if (oppoFactory != nullptr) {
oppopro.push_back(std::move(oppoFactory));
}
}
}
void RemoveInactive() {
for (int i = oppo.size() - 1; i >= 0; i--) {
if (!oppo[i]->GetIsActive()) {
oppo.erase(oppo.begin() + i);
}
}
for (int j = oppopro.size() - 1; j >= 0; j--) {
if (!oppopro[j]->GetIsActive()) {
oppopro.erase(oppopro.begin() + j);
}
}
for (int k = playpro.size() - 1; k >= 0; k--) {
if (!playpro[k]->GetIsActive()) {
playpro.erase(playpro.begin() + k);
}
}
}
private:
graphics::Image screen;
std::vector<std::unique_ptr<Opponent>> oppo;
std::vector<std::unique_ptr<OpponentProjectile>> oppopro;
std::vector<std::unique_ptr<PlayerProjectile>> playpro;
Player player;
int width_;
int height_;
int score_ = 0;
bool has_lost_ = false;
};
#endif
| true |
818d5114916ae806c403063b073f3e40d501d738 | C++ | TyRoXx/lua-cpp | /luacpp/sink_from_lua.hpp | UTF-8 | 969 | 2.53125 | 3 | [
"MIT"
] | permissive | #ifndef LUACPP_SINK_FROM_LUA_HPP
#define LUACPP_SINK_FROM_LUA_HPP
#include <silicium/sink/sink.hpp>
#include "luacpp/stack.hpp"
namespace lua
{
template <class Sink>
struct sink_from_lua
{
explicit sink_from_lua(Sink original)
: m_original(std::move(original))
{
}
void append(lua::any_local elements, lua_State &L)
{
typedef typename Sink::element_type element_type;
auto element = lua::from_lua_cast<element_type>(L, elements.from_bottom());
Si::success success_expected = m_original.append(Si::make_iterator_range(&element, &element + 1));
boost::ignore_unused_variable_warning(success_expected);
}
private:
Sink m_original;
};
template <class Sink>
lua::stack_value create_sink_wrapper_meta_table(lua::stack &stack)
{
typedef sink_from_lua<Sink> wrapper;
lua::stack_value table = lua::create_default_meta_table<wrapper>(stack);
lua::add_method(stack, table, "append", &wrapper::append);
return table;
}
}
#endif
| true |
8a0dd253fb7c7ed7900d8a332098d4b586009f98 | C++ | 2quarius/SE347-DS | /lab1/rdt/rdt_receiver.cc | UTF-8 | 4,019 | 2.875 | 3 | [] | no_license | /*
* FILE: rdt_receiver.cc
* DESCRIPTION: Reliable data transfer receiver.
* NOTE: This implementation assumes there is no packet loss, corruption, or
* reordering. You will need to enhance it to deal with all these
* situations. In this implementation, the packet format is laid out as
* the following:
*
* |<- 1 byte ->|<- the rest ->|
* | payload size |<- payload ->|
*
* The first byte of each packet indicates the size of the payload
* (excluding this single-byte header)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <iostream>
#include "rdt_struct.h"
#include "rdt_receiver.h"
#include "rdt_protocol.h"
int last_end_of_msg = -1;
class ReceiveInfo {
public:
bool received;
bool is_end;
std::string data;
ReceiveInfo(): received(false), is_end(false) {}
};
ReceiveInfo receiver_packets[RDT_MAX_SEQ_NO];
/* receiver initialization, called once at the very beginning */
void Receiver_Init()
{
fprintf(stdout, "At %.2fs: receiver initializing ...\n", GetSimulationTime());
for(int i = 0; i<RDT_MAX_SEQ_NO; i++) {
receiver_packets[i].received = false;
}
}
/* receiver finalization, called once at the very end.
you may find that you don't need it, in which case you can leave it blank.
in certain cases, you might want to use this opportunity to release some
memory you allocated in Receiver_init(). */
void Receiver_Final()
{
fprintf(stdout, "At %.2fs: receiver finalizing ...\n", GetSimulationTime());
}
/* parse packet */
bool Receiver_ParsePacket(packet *pkt, int *payload_size, bool *end_of_msg, int *seq_no, char *payload)
{
// std::cout<< "receiver parse packet" << std::endl;
if(!crc32_check(pkt)) return false;
// get payload size
*payload_size = pkt->data[0] >> 1 & ((1 << RDT_PAYLOAD_SIZE_BITS) - 1);
if(*payload_size <= 0 || *payload_size > (int)RDT_MAX_PAYLOAD_SIZE) return false;
// get end of msg
*end_of_msg = pkt->data[0] & 1;
// get seqence number
*seq_no = *(int*)(pkt->data+1) & ((1 << RDT_SEQ_NO_BITS) - 1);
// get data
memcpy(payload, pkt->data + RDT_HEADER_SIZE, *payload_size);
return true;
}
/* construct ack packet */
void Receiver_ConstructACK(int seq_no, packet *pkt)
{
// std::cout<< "receiver check ack" << std::endl;
ASSERT(seq_no >= 0 && seq_no <= RDT_MAX_SEQ_NO);
ASSERT(pkt);
// add header
pkt->data[0] = 0;
memcpy(pkt->data+1, (char*)&seq_no, RDT_SEQ_NO_SIZE);
// fill payload with all 0
memset(pkt->data + RDT_HEADER_SIZE, 0, RDT_MAX_PAYLOAD_SIZE);
// add footer
crc32_padding(pkt);
}
/* event handler, called when a packet is passed from the lower layer at the
receiver */
void Receiver_FromLowerLayer(struct packet *pkt)
{
// std::cout<< "receiver from lower layer" << std::endl;
int payload_size;
bool end_of_msg;
int seq_no;
char payload[RDT_MAX_PAYLOAD_SIZE];
std::string message;
struct message msg;
// invalid packet
if(!Receiver_ParsePacket(pkt, &payload_size, &end_of_msg, &seq_no, payload)) return;
// return ack to sender
packet ack;
Receiver_ConstructACK(seq_no, &ack);
Receiver_ToLowerLayer(&ack);
// receive data
receiver_packets[seq_no].received = true;
receiver_packets[seq_no].is_end = end_of_msg;
receiver_packets[seq_no].data = std::string(payload, payload_size);
// reassemble
for(int i = last_end_of_msg + 1; i<RDT_MAX_SEQ_NO; i++) {
if(!receiver_packets[i].received) break;
if(receiver_packets[i].is_end) {
message.clear();
for(int j = last_end_of_msg + 1; j <= i; j++) {
message += receiver_packets[j].data;
}
msg.size = message.size();
msg.data = (char*)message.data();
Receiver_ToUpperLayer(&msg);
last_end_of_msg = i;
}
}
}
| true |
be480444f541389e14400a9a28cf87a969f41432 | C++ | calsaviour/sdc-term3 | /PVTPlanner_beta/PVTP/include/PVTP/PVT_S.hpp | UTF-8 | 2,983 | 3.046875 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef PVTP_S_H
#define PVTP_S_H
#include <iostream>
#include <PVTP/Interval.hpp>
#include <PVTP/TrajectorySegment.hpp>
namespace PVTP {
/**
* Interval set class. Objects of this class are used by the Forward
* algorithm to track and merge goal-reachable velocity intervals at PT
* points. The reachable interval is stored as a pair of representative
* trajetories representing the maximum and minimum arrival velocities
* (and corresponding max/min arrival times).
*
* When an optimal trajectory is reconstructed, reconstruction begins
* by following one of these representative trajectories back to a point
* in the obstacle field.
*/
class PVT_S {
/**
* Overload the output operator.
*/
friend std::ostream& operator<<(std::ostream& out, const PVT_S& s);
public:
/**
* Constructor: Used for intermediate states during propagation when
* only reachable interval and homotopic class information need to
* be stored
*/
PVT_S ( const Interval& i );
/**
* Constructor: Used for intermediate states during propagation when
* only reachable interval and homotopic class information need to
* be stored
*/
PVT_S ( const Interval& i, const std::vector<char>& B );
/**
* Constructor: Used for goal connections; for convenience, include
* a reference to the obstacle point the interval is for
*/
PVT_S ( const std::vector<TrajectorySegment*>& UB,
const std::vector<TrajectorySegment*>& LB,
const std::vector<char>& B,
const PVT_Point& p );
/**
* Constructor: Copy
*/
PVT_S ( const PVT_S& S );
/**
* Destructor
*/
~PVT_S ();
/**
* Set the UB to a copy of another
*/
void setUB( const std::vector<TrajectorySegment*>& UB );
/**
* Set the LB to a copy of another
*/
void setLB( const std::vector<TrajectorySegment*>& LB );
/**
* A convenience method for getting the reachable velocity interval
* for the point that UB and LB originate at
*/
void getReachableInterval( Interval& V ) const;
/**
* A reachable velocity interval at the goal
*/
Interval V;
/**
* The homotopic classification associated with the reachable interval
*/
std::vector<char> * B;
/**
* A representative trajectory terminating in the maximum achievable velocity
*/
std::vector<TrajectorySegment*> * UB;
/**
* A representative trajectory terminating in the maximum achievable velocity
*/
std::vector<TrajectorySegment*> * LB;
/**
* The point this reachable set corresponds to
*/
PVT_Point * p;
};
/**
* A function object used as a comparator for sorting goal intervals.
*
* Sort order: Ascending.
*/
struct PVT_S_Comparator {
bool operator() (PVT_S* A, PVT_S* B) {
double a_time = A->UB->back()->getFinalState().getTimeCoord();
double b_time = B->UB->back()->getFinalState().getTimeCoord();
return a_time < b_time;
}
};
} // end PVTP namespace
#endif | true |
f8845a6c7003e6c2d552c7c0e90c1a4063bbc8e5 | C++ | arangodb/arangodb | /3rdParty/boost/1.78.0/boost/multiprecision/concepts/mp_number_archetypes.hpp | UTF-8 | 8,262 | 2.921875 | 3 | [
"Apache-2.0",
"BSD-3-Clause",
"ICU",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"MIT",
"GPL-2.0-only",
"CC0-1.0",
"BSL-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception-2.2",
"LicenseRef-scancode... | permissive | ///////////////////////////////////////////////////////////////
// Copyright 2012 John Maddock. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt
#ifndef BOOST_MATH_CONCEPTS_ER_HPP
#define BOOST_MATH_CONCEPTS_ER_HPP
#include <iostream>
#include <sstream>
#include <iomanip>
#include <tuple>
#include <functional>
#include <cmath>
#include <cstdint>
#include <boost/multiprecision/number.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
namespace boost {
namespace multiprecision {
namespace concepts {
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable : 4244)
#endif
struct number_backend_float_architype
{
using signed_types = std::tuple<boost::long_long_type> ;
using unsigned_types = std::tuple<boost::ulong_long_type>;
using float_types = std::tuple<long double> ;
using exponent_type = int ;
number_backend_float_architype()
{
m_value = 0;
std::cout << "Default construct" << std::endl;
}
number_backend_float_architype(const number_backend_float_architype& o)
{
std::cout << "Copy construct" << std::endl;
m_value = o.m_value;
}
number_backend_float_architype& operator=(const number_backend_float_architype& o)
{
m_value = o.m_value;
std::cout << "Assignment (" << m_value << ")" << std::endl;
return *this;
}
number_backend_float_architype& operator=(boost::ulong_long_type i)
{
m_value = i;
std::cout << "UInt Assignment (" << i << ")" << std::endl;
return *this;
}
number_backend_float_architype& operator=(boost::long_long_type i)
{
m_value = i;
std::cout << "Int Assignment (" << i << ")" << std::endl;
return *this;
}
number_backend_float_architype& operator=(long double d)
{
m_value = d;
std::cout << "long double Assignment (" << d << ")" << std::endl;
return *this;
}
number_backend_float_architype& operator=(const char* s)
{
#ifndef BOOST_NO_EXCEPTIONS
try
{
#endif
m_value = boost::lexical_cast<long double>(s);
#ifndef BOOST_NO_EXCEPTIONS
}
catch (const std::exception&)
{
BOOST_THROW_EXCEPTION(std::runtime_error(std::string("Unable to parse input string: \"") + s + std::string("\" as a valid floating point number.")));
}
#endif
std::cout << "const char* Assignment (" << s << ")" << std::endl;
return *this;
}
void swap(number_backend_float_architype& o)
{
std::cout << "Swapping (" << m_value << " with " << o.m_value << ")" << std::endl;
std::swap(m_value, o.m_value);
}
std::string str(std::streamsize digits, std::ios_base::fmtflags f) const
{
std::stringstream ss;
ss.flags(f);
if (digits)
ss.precision(digits);
else
ss.precision(std::numeric_limits<long double>::digits10 + 3);
std::intmax_t i = m_value;
std::uintmax_t u = m_value;
if (!(f & std::ios_base::scientific) && m_value == i)
ss << i;
else if (!(f & std::ios_base::scientific) && m_value == u)
ss << u;
else
ss << m_value;
std::string s = ss.str();
std::cout << "Converting to string (" << s << ")" << std::endl;
return s;
}
void negate()
{
std::cout << "Negating (" << m_value << ")" << std::endl;
m_value = -m_value;
}
int compare(const number_backend_float_architype& o) const
{
std::cout << "Comparison" << std::endl;
return m_value > o.m_value ? 1 : (m_value < o.m_value ? -1 : 0);
}
int compare(boost::long_long_type i) const
{
std::cout << "Comparison with int" << std::endl;
return m_value > i ? 1 : (m_value < i ? -1 : 0);
}
int compare(boost::ulong_long_type i) const
{
std::cout << "Comparison with unsigned" << std::endl;
return m_value > i ? 1 : (m_value < i ? -1 : 0);
}
int compare(long double d) const
{
std::cout << "Comparison with long double" << std::endl;
return m_value > d ? 1 : (m_value < d ? -1 : 0);
}
long double m_value;
};
inline void eval_add(number_backend_float_architype& result, const number_backend_float_architype& o)
{
std::cout << "Addition (" << result.m_value << " += " << o.m_value << ")" << std::endl;
result.m_value += o.m_value;
}
inline void eval_subtract(number_backend_float_architype& result, const number_backend_float_architype& o)
{
std::cout << "Subtraction (" << result.m_value << " -= " << o.m_value << ")" << std::endl;
result.m_value -= o.m_value;
}
inline void eval_multiply(number_backend_float_architype& result, const number_backend_float_architype& o)
{
std::cout << "Multiplication (" << result.m_value << " *= " << o.m_value << ")" << std::endl;
result.m_value *= o.m_value;
}
inline void eval_divide(number_backend_float_architype& result, const number_backend_float_architype& o)
{
std::cout << "Division (" << result.m_value << " /= " << o.m_value << ")" << std::endl;
result.m_value /= o.m_value;
}
inline void eval_convert_to(boost::ulong_long_type* result, const number_backend_float_architype& val)
{
*result = static_cast<boost::ulong_long_type>(val.m_value);
}
inline void eval_convert_to(boost::long_long_type* result, const number_backend_float_architype& val)
{
*result = static_cast<boost::long_long_type>(val.m_value);
}
inline void eval_convert_to(long double* result, number_backend_float_architype& val)
{
*result = val.m_value;
}
inline void eval_frexp(number_backend_float_architype& result, const number_backend_float_architype& arg, int* exp)
{
result = std::frexp(arg.m_value, exp);
}
inline void eval_ldexp(number_backend_float_architype& result, const number_backend_float_architype& arg, int exp)
{
result = std::ldexp(arg.m_value, exp);
}
inline void eval_floor(number_backend_float_architype& result, const number_backend_float_architype& arg)
{
result = std::floor(arg.m_value);
}
inline void eval_ceil(number_backend_float_architype& result, const number_backend_float_architype& arg)
{
result = std::ceil(arg.m_value);
}
inline void eval_sqrt(number_backend_float_architype& result, const number_backend_float_architype& arg)
{
result = std::sqrt(arg.m_value);
}
inline int eval_fpclassify(const number_backend_float_architype& arg)
{
return (boost::math::fpclassify)(arg.m_value);
}
inline std::size_t hash_value(const number_backend_float_architype& v)
{
std::hash<long double> hasher;
return hasher(v.m_value);
}
using mp_number_float_architype = boost::multiprecision::number<number_backend_float_architype>;
} // namespace concepts
template <>
struct number_category<concepts::number_backend_float_architype> : public std::integral_constant<int, number_kind_floating_point>
{};
}} // namespace boost::multiprecision
namespace std {
template <boost::multiprecision::expression_template_option ExpressionTemplates>
class numeric_limits<boost::multiprecision::number<boost::multiprecision::concepts::number_backend_float_architype, ExpressionTemplates> > : public std::numeric_limits<long double>
{
using base_type = std::numeric_limits<long double> ;
using number_type = boost::multiprecision::number<boost::multiprecision::concepts::number_backend_float_architype, ExpressionTemplates>;
public:
static number_type(min)() noexcept { return (base_type::min)(); }
static number_type(max)() noexcept { return (base_type::max)(); }
static number_type lowest() noexcept { return -(max)(); }
static number_type epsilon() noexcept { return base_type::epsilon(); }
static number_type round_error() noexcept { return base_type::round_error(); }
static number_type infinity() noexcept { return base_type::infinity(); }
static number_type quiet_NaN() noexcept { return base_type::quiet_NaN(); }
static number_type signaling_NaN() noexcept { return base_type::signaling_NaN(); }
static number_type denorm_min() noexcept { return base_type::denorm_min(); }
};
} // namespace std
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
#endif
| true |
acc73d0eb4707e59cb646afcf7fd74068ec9c633 | C++ | mayank-tripathik/Geeksforgeeks | /Array/binary_search.cpp | UTF-8 | 854 | 3.453125 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
int binary_search_recursive(vector<int> &arr, int low, int high, int k){
if(high<low)
return -1;
int mid=(high+low)/2;
if(k==arr[mid])
return mid;
if(k<arr[mid])
return binary_search_recursive(arr,low,mid-1,k);
else
return binary_search_recursive(arr,mid+1,high,k);
}
int binary_search_iterative(vector<int> &arr, int low, int high, int k){
int mid;
while(low<=high){
mid=(high+low)/2;
if(k==arr[mid])
break;
if(k<arr[mid])
high=mid-1;
else
low=mid+1;
}
if(arr[mid]==k)
return mid;
else
return -1;
}
int main(){
int n,k;
cin>>n;
vector<int> arr(n);
for(int i=0;i<n;i++)
cin>>arr[i];
int test;
cin>>test;
while(test--){
cin>>k;
int ans=binary_search_iterative(arr,0,n-1,k);
if(ans==-1)
cout<<"not found\n";
else
cout<<"found\n";
}
}
| true |
0cf6a22bac1e9ed8f7d9a0fcce400b0976c2849d | C++ | Ursus14/TeraVTK | /BrokenLine.cpp | UTF-8 | 792 | 2.59375 | 3 | [] | no_license | #include "BrokenLine.h"
BrokenLine::BrokenLine() {};
vtkPoints* BrokenLine::GetPoints() {
return this->points;
}
void BrokenLine::SetPoints(vtkPoints* points) {
this->points = points;
}
void BrokenLine::build(vtkPoints* points, vtkSmartPointer<vtkRenderer> renderer) {
vtkSmartPointer<vtkLineSource> lineSource =
vtkSmartPointer<vtkLineSource>::New();
lineSource->SetPoints(points);
vtkSmartPointer<vtkPolyDataMapper> brokenLineMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
brokenLineMapper->SetInputConnection(lineSource->GetOutputPort());
vtkSmartPointer<vtkActor> brokenLineActor = vtkSmartPointer<vtkActor>::New();
brokenLineActor->SetMapper(brokenLineMapper);
brokenLineActor->GetProperty()->SetColor(0.32, 0.21, 0.123);
renderer->AddActor(brokenLineActor);
} | true |
392724a21403fe61bfc36cde39313d4802ae1520 | C++ | neuenablingengineering/LIS-Eyetracking | /src/3D-Eye-Tracker/main/Subscriber.cpp | UTF-8 | 573 | 2.546875 | 3 | [
"MIT"
] | permissive | #include "stdafx.h"
#include "Subscriber.h"
Subscriber::Subscriber(PubSubHandler* p) {
psh = p;
}
void Subscriber::receiveMessage(EventMessage e) {
receivedMessageQueue.push(e);
readMessages();
}
void Subscriber::SubscribeToTopic(EventTopic t) {
psh->AddSubscriber(this, t);
}
void Subscriber::UnSubscribeToTopic(EventTopic t) {
psh->RemoveSubscriber(this, t);
}
EventMessage Subscriber::getTopMessage() {
EventMessage em = receivedMessageQueue.front();
receivedMessageQueue.pop();
return em;
}
void Subscriber::EmptyQueue() {
receivedMessageQueue.empty();
} | true |
6a653c0a53982e571dfe982c2ee35382017aa90d | C++ | maayan92/experis_C_basicCpp | /cpp/tms/tokenizer.cpp | UTF-8 | 1,204 | 2.953125 | 3 | [] | no_license | #include "tokenizer.hpp"
#include <algorithm>
#include <ctype.h>
namespace experis {
static bool isDelimiter(const char a_element) {
return isspace(a_element) || (0 == isalnum(a_element));
}
Tokenizer::Tokens& Tokenizer::DivideIntoTokens(std::istream& a_inputFile) {
std::string wordFromFile;
while(getline(a_inputFile, wordFromFile)) {
DivideLineIntoTokens(wordFromFile);
m_tokens.push_back("\n");
}
return m_tokens;
}
void Tokenizer::DivideLineIntoTokens(std::string& a_wordFromFile) {
Itr wordItrFrom = a_wordFromFile.begin();
Itr wordItrTo = std::find_if(wordItrFrom, a_wordFromFile.end(), isDelimiter);
std::string token;
while(wordItrTo != a_wordFromFile.end()) {
token = std::string(wordItrFrom,wordItrTo);
if(0 < token.size()) { m_tokens.push_back(token); }
m_tokens.push_back(std::string(wordItrTo, wordItrTo + 1));
wordItrFrom = wordItrTo + 1;
wordItrTo = std::find_if(wordItrFrom, a_wordFromFile.end(), isDelimiter);
}
token = std::string(wordItrFrom,wordItrTo);
if(0 < token.size()) { m_tokens.push_back(token); }
}
const Tokenizer::Tokens& Tokenizer::GetTokens() const {
return m_tokens;
}
} // experis | true |
21dd67df7057813d2f1418a560aec1d3ecf4f706 | C++ | StefanKubsch/lwmf | /example/DemoSources/TextureRotationTest.hpp | UTF-8 | 1,099 | 2.875 | 3 | [
"LicenseRef-scancode-public-domain",
"Unlicense"
] | permissive | #pragma once
#include <cstdint>
#include <array>
#include <charconv>
namespace TextureRotationTest
{
inline lwmf::TextureStruct SourceTexture{};
inline void Init()
{
lwmf::LoadPNG(SourceTexture, "./DemoGFX/Head.png");
lwmf::ResizeTexture(SourceTexture, SourceTexture.Width * 3, SourceTexture.Height * 3, lwmf::FilterModes::BILINEAR);
}
inline void Draw()
{
static float Angle{};
lwmf::TextureStruct Texture{ SourceTexture };
lwmf::RotateTexture(Texture, Texture.WidthMid, Texture.HeightMid, Angle);
lwmf::BlitTexture(Texture, Canvas, Canvas.WidthMid - Texture.WidthMid, Canvas.HeightMid - Texture.HeightMid);
DisplayInfoBox("Texture rotation test (lwmf::RotateTexture)");
static std::uint_fast64_t RotateCounter{};
std::array<char, 20> CounterString{};
std::to_chars(CounterString.data(), CounterString.data() + CounterString.size(), ++RotateCounter);
lwmf::RenderText(Canvas, "Number of texture rotations: " + std::string(CounterString.data()), 10, 70, 0xFFFFFFFF);
(Angle >= 359.0F) ? Angle = 0.0F : Angle += 0.005F;
}
} // namespace TextureRotationTest
| true |
f66b1de73fbc32e760b14bac1f9e1be8af87fe7f | C++ | NeverStopMata/MTRT | /MTRT/checker_texture.h | UTF-8 | 492 | 3.171875 | 3 | [] | no_license | #pragma once
#include "texture.h"
class CheckerTexture :public Texture {
public:
CheckerTexture() {}
CheckerTexture(Texture const * t0, Texture const * t1) : odd_tex_(t0), even_tex_(t1) {}
virtual Vec3 Sample(float u, float v, const Vec3& p) const {
float sin = std::sin(10 * p.x()) * std::sin(10 * p.y()) * std::sin(10 * p.z());
if (sin < 0)
return odd_tex_->Sample(u, v, p);
else
return even_tex_->Sample(u, v, p);
}
Texture const * odd_tex_;
Texture const * even_tex_;
}; | true |
9387e2b45d5271a3b90d6519661d2aab79c154ed | C++ | SSPKUZX/cpp-comm | /enum.h | UTF-8 | 2,195 | 3.078125 | 3 | [] | no_license | #include "ptr.h"
#include "traits.h"
#include "variadic.h"
#include "demangle.h"
namespace utl
{
template<class... Labels>
class Enum
{
static_assert( !has_duplicate<Labels...>::value, "no duplicate label classes allowed in Enum's template class arguments");
public:
// similar to equal
template<class T>
bool Is() const
{
static_assert(one_of<T,Labels...>::value,"T must be one of Labels");
return m_index==index_of<T, Labels...>::value;
}
// tostring
std::string const& Str() const{ return meta.s_label_names[m_index]; }
// system enum can be converted to int
operator int() const{ return m_index;}
// total label count
constexpr uint8_t Count() const { return sizeof...(Labels); }
// factory method
template<class T>
static Enum Of()
{
static_assert(one_of<T,Labels...>::value,"T must be one of Labels");
return Enum(index_of<T, Labels...>::value);
}
template<class... _Labels>
friend std::ostream& operator<<( std::ostream&, Enum<_Labels...> const& val);
private:
// only accessible to 'Of'
Enum( uint8_t const idx) : m_index(idx){}
uint8_t m_index;
// static initor of member s_label_names
static struct MetaHolder
{
std::unique_ptr<std::string[]> s_label_names;
template<class T>
struct EnumHook
{
void operator()( std::unique_ptr<std::string[]>& names, uint8_t& index)
{
names[index++] = demangle(typeid(T));
}
};
MetaHolder() : s_label_names(make_unique<std::string[]>(sizeof...(Labels)))
{
uint8_t index = 0;
vtypes<EnumHook, Labels...>()( s_label_names, index);
}
} meta;
};
template<class... Labels >
typename Enum<Labels...>::MetaHolder Enum<Labels...>::meta;
template<class... _Labels>
std::ostream& operator<< ( std::ostream& os, Enum<_Labels...> const& val)
{
os << Enum<_Labels...>::meta.s_label_names[val.m_index];
return os;
}
} // end of utl
namespace std
{
template<class... Types>
struct hash<::utl::Enum<Types...>>
{
std::hash<int> hasher;
size_t operator()( ::utl::Enum<Types...> const& e) const
{
return hasher(static_cast<int>(e));
}
};
}
| true |
d2079b75565c980045b7472f92a40dd79c0b9d2f | C++ | DavidGoldMatejka/Black-Jack | /BlackJack/Card.h | UTF-8 | 528 | 3.5625 | 4 | [] | no_license | #pragma once
#include <iostream>
class Card{
public:
int value; // point value of the card (NOT THE ID!)
std::string name; // like Ace, One, Two, Three, ... Queen, King
std::string suit; // like Spades, Hearts, Diamonds, Clubs
Card(int ID = -1); // valid ID values go from 0 to 51; -1 means an invalid card aka JOKER
friend std::ostream& operator<<(std::ostream& os, Card const &n) {
return os << n.name << " of " << n.suit << "(" << n.value << ")" ;
}
}; | true |
20985f448eb2fa1113e3ff087c7120389f8f58bb | C++ | GaneshTambat/G-11_Project | /G11_Project/LightParticle.h | SHIFT_JIS | 3,280 | 2.625 | 3 | [] | no_license | //===========================================================
// Cgp[eBN
//Creater:Arai Yuhki
//===========================================================
#ifndef _LIGHT_PARTICLE_H_
#define _LIGHT_PARTICLE_H_
//===========================================================
//CN[h
//===========================================================
#include "main.h"
class CShader2D;
//===========================================================
//2D|SNX
//===========================================================
class LightParticle
{
protected:
D3DXVECTOR3 _Pos; //|S̈ʒu
D3DXVECTOR3 _Size; //|S̑傫
D3DXVECTOR3 _Speed; //|S̈ړx
D3DXVECTOR3 _Rot; //|S̊px
D3DXVECTOR4 uv; //x=left,y=top,z=width,w=heightƂĈ
D3DXCOLOR _Color;
D3DXMATRIX WorldMtx;
int frame; //t[JEg
bool ReleaseFlag;
static int _Num;
LPDIRECT3DTEXTURE9 Texture;
static bool PauseFlag;
static CShader2D* _Shader;
void LinkList(void); //gXgɒlj
void UnlinkList(void); //gXg폜
virtual void Update(void);
virtual void Pause(void);
virtual void Draw(void);
int Priority;
public:
LightParticle();
virtual ~LightParticle(){}
static LightParticle* Create(const D3DXVECTOR3 &pos,const D3DXVECTOR2 &size,const D3DXCOLOR &color);
static void UpdateAll(void);
static void DrawAll(void);
void Release(void); //폜
static void ReleaseAll(void);
static void Clear(void);
//Getter&Stter
static LightParticle* Top(void){ return LightParticle::Top_; }
static LightParticle* Cur(void){ return LightParticle::Cur_; }
LightParticle* Prev(void)const{ return Prev_; }
LightParticle* Next(void)const{ return Next_; }
D3DXCOLOR Color(void)const{ return _Color; }
D3DXVECTOR3 Pos(void)const{ return _Pos; }
D3DXVECTOR3 Rot(void)const{ return _Rot; }
D3DXVECTOR3 Speed(void)const{ return _Speed; }
D3DXVECTOR3 Size(void)const{ return _Size; }
static int Num(void){ return _Num; }
static void SetTop(LightParticle* top){ Top_ = top; }
static void SetCur(LightParticle* cur){ Cur_ = cur; }
static void SetPause(bool flag){ PauseFlag = flag; }
void SetPos(const D3DXVECTOR3 &pos){ _Pos = pos; }
void SetRot(const D3DXVECTOR3 &rot){ _Rot = rot; }
void SetRot(const float &rot){ _Rot.z = rot; }
void SetColor(const D3DXCOLOR &color){ _Color = color; }
void SetSize(const D3DXVECTOR3 &size){ _Size = size; }
void SetSpeed(const float base,float radian);
void SetTexture(LPDIRECT3DTEXTURE9 tex){ Texture = tex; }
void SetUV(int UNum = 0,int VNum = 0,int DivideUNum = 1,int DivideVNum = 1);
void SetNext(LightParticle* next){ Next_ = next; }
void SetPrev(LightParticle* prev){ Prev_ = prev; }
void SetRelease(void){ ReleaseFlag = true; }
void AddPos(const D3DXVECTOR3 &pos){ _Pos += pos; }
void AddRot(const D3DXVECTOR3 &rot){ _Rot += rot; }
void AddRot(const float &rot){ _Rot.z += rot; }
void AddSize(const D3DXVECTOR3 &size){ _Size += size; }
void AddColor(const D3DXCOLOR &color){ _Color += color; }
//---------------------------
private:
LightParticle* Prev_;
LightParticle* Next_;
static LightParticle* Top_;
static LightParticle* Cur_;
};
#endif | true |
0cea0d780dc0379b8c36d9c90756d9c6cb4c21a8 | C++ | ammitra/Grafana-Monitor | /src/main.cc | UTF-8 | 5,758 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <net_helpers.hh>
#include <Sensor.hh>
#include <TimeSensor.hh>
#include <IpmiTemperatureSensor.hh>
#include <IpmiFanSpeedSensor.hh>
#include <ApolloBlade.hh>
#include <unistd.h>
#include <string>
#include <fstream>
#include <iostream>
#include <boost/program_options.hpp>
#include <stdexcept>
namespace po = boost::program_options;
std::vector<std::string> split_sensor_string(std::string sensor, std::string delimiter);
int main(int argc, char ** argv){
std::string const &IP_addr = "127.0.0.1";
int port_number = 2003; // plaintext data port
// create map that we'll put sensors in
std::vector<Sensor*> sensors;
try {
po::options_description fileOptions{"File"};
fileOptions.add_options()
("sensor", po::value<std::string>(), "value")
("apollo", po::value<std::string>(), "value");
std::string configFileName = "sensors.config";
if(argc > 1){
configFileName=argv[1];
}
std::ifstream ifs{configFileName};
if(ifs){
po::parsed_options config_options = po::parse_config_file(ifs, fileOptions);
int num_options = config_options.options.size();
// values in config file are space-delimited
std::string delimiter = " ";
for ( int i = 0; i < num_options; i++ ) {
std::string option = config_options.options[i].string_key;
if(option == "sensor"){
// vector that we'll split the string into
std::vector<std::string> sensor_info;
// each element in config_options.options is a line in the config file
std::string sensor = config_options.options[i].value[0].c_str();
sensor_info = split_sensor_string(sensor, delimiter);
// currently sensor_type can be either IpmiTemperature or IpmiFanspeed
std::string sensor_type = sensor_info[0];
std::string fan_tray_number = sensor_info[1];
// wsp_filename is the path to the wsp file which grafana reads the data from
std::string wsp_filename = "Sensors." + sensor_type + "." + fan_tray_number;
int ipmi_sensor_number = std::stoi(sensor_info[2]); // this has to be c++ 11, check out atoi
// get the hostname of the machine where the sensor is located
char *shelf_hostname = (char *) sensor_info[3].c_str();
// get the IPMB address of the device within the machine
unsigned long rs_addr = strtoul((char *) sensor_info[4].c_str(), NULL, 0);
// uint8_t rs_addr = (uint8_t) rs_addr_int;
try {
printf("Adding Sensor %s:%s Sensor %s(%d) from %s,0x%02X to %s\n",
sensor_type.c_str(),
fan_tray_number.c_str(),
sensor_info[2].c_str(),ipmi_sensor_number,
shelf_hostname,
rs_addr,
wsp_filename.c_str()
);
// make sensor objects. We currently can only make Ipmi Temp or Fanspeed sensors
if (sensor_type == "IpmiTemperature") {
Sensor *tempSensor = new IpmiTemperatureSensor(ipmi_sensor_number, wsp_filename, shelf_hostname, rs_addr);
sensors.push_back(tempSensor);
// sensors[i]->Connect(IP_addr, port_number);
tempSensor->Connect(IP_addr, port_number);
// made esnsor of type ./..
} else if (sensor_type == "IpmiFanspeed") {
Sensor *fanspeedSensor = new IpmiFanSpeedSensor(ipmi_sensor_number, wsp_filename, shelf_hostname, rs_addr);
sensors.push_back(fanspeedSensor);
// sensors[i]->Connect(IP_addr, port_number);
fanspeedSensor->Connect(IP_addr, port_number);
} else {
printf("invalid sensor type: %s\n", sensor_type.c_str());
}
} catch (std::runtime_error &e){
std::cout << e.what() << std::endl;
}
}
else if(option == "apollo") {
// vector that we'll split the string into
std::vector<std::string> apollo_info;
std::string apollo = config_options.options[i].value[0].c_str();
apollo_info = split_sensor_string(apollo, delimiter);
std::string base_string = "Sensors." + apollo_info[0] + ".";
int ipmi_sensor_number = std::stoi(apollo_info[1]);
char *shelf_hostname = (char *) apollo_info[3].c_str();
unsigned long rs_addr = strtoul((char *) apollo_info[4].c_str(), NULL, 0);
printf("Adding Apollo %d %s: %d\n",
ipmi_sensor_number,
shelf_hostname,
rs_addr
);
Sensor *apolloBlade = new ApolloBlade(ipmi_sensor_number, base_string, shelf_hostname, rs_addr);
sensors.push_back(apolloBlade);
// sensors[i]->Connect(IP_addr, port_number);
apolloBlade->Connect(IP_addr, port_number);
}
}
}
} catch(const po::error &ex){
std::cerr << ex.what() << '\n';
}
unsigned int secondsToSleep = 30;
int attempts = 0;
int successful = 0;
int attempts_timer = 0;
// sleep and repeat this process
while(1){
for ( int i = 0; i < sensors.size(); i++ ) {
attempts++;
try{
sensors[i]->Report();
successful++;
}catch(const std::exception & e){
}
}
attempts_timer += secondsToSleep;
if ( attempts_timer >= 600){
printf("%d out of %d successful reports in the last 10 minutes\n", successful, attempts);
attempts = 0;
successful = 0;
attempts_timer = 0;
}
sleep(secondsToSleep);
}
/*if (NULL != ipmi_temperature_sensor_1){
delete ipmi_temperature_sensor_1;
}*/
return 0;
}
std::vector<std::string> split_sensor_string(std::string sensor, std::string delimiter){
size_t position = 0;
std::string token;
std::vector<std::string> sensor_info;
while( (position = sensor.find(delimiter)) != std::string::npos) {
token = sensor.substr(0, position);
sensor_info.push_back(token);
sensor.erase(0, position+delimiter.length());
}
sensor_info.push_back(sensor);
return sensor_info;
}
| true |
71d8684099fc7c5a40d7e6326df5b206f83ec9af | C++ | shnoh171/problem-solving | /backjoon-online-judge/10972-next-permutation/next_permutation.cpp | UTF-8 | 1,414 | 3.3125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
bool NextPermutation(int list[], int n);
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin >> n;
int list[n];
for (int i = 0; i < n; ++i) cin >> list[i];
if (NextPermutation(list, n))
for (int i = 0; i < n; ++i) cout << list[i] << " ";
else
cout << "-1";
cout << "\n";
/*
int list[n];
for (int i = 0; i < n; ++i) list[i] = i+1;;
int list_cmp[n];
for (int i = 0; i < n; ++i) list_cmp[i] = i+1;;
do {
for (int i = 0; i < n; ++i)
if (list[i] != list_cmp[i]) {
cout << "list: ";
for (int j = 0; j < n; ++j) cout << list[j] << " ";
cout << "\n";
cout << "list_cmp: ";
for (int j = 0; j < n; ++j) cout << list_cmp[j] << " ";
cout << "\n";
cout << "previous: ";
prev_permutation(list_cmp, list_cmp+n);
for (int j = 0; j < n; ++j) cout << list_cmp[j] << " ";
cout << "\n";
return 1;
}
next_permutation(list_cmp, list_cmp+n);
} while(NextPermutation(list, n));
*/
return 0;
}
bool NextPermutation(int list[], int n)
{
int pivot = n-1;
while (pivot > 0 && list[pivot] < list[pivot-1])
--pivot;
if (pivot == 0) return false;
int index = n-1;
while (list[pivot-1] > list[index]) --index;
swap(list[pivot-1],list[index]);
for (int i = 0; i < (n - pivot) / 2; ++i) {
swap(list[pivot+i], list[n-1-i]);
}
return true;
}
| true |
68d65af37bfe4955195c0f922ae6ef700f7924f7 | C++ | henfredemars/Fork-Lang | /parContextManager.cpp | UTF-8 | 8,849 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive |
//Implementation of the parallel statement execution manager
#include "parContextManager.h"
StatementContext::StatementContext() {
//Do nothing
}
StatementContext::StatementContext(StatementContext&& sc) {
this->int_future_id_map = std::move(sc.int_future_id_map);
this->float_future_id_map = std::move(sc.float_future_id_map);
this->intptr_future_id_map = std::move(sc.intptr_future_id_map);
this->floatptr_future_id_map = std::move(sc.floatptr_future_id_map);
this->void_future_id_map = std::move(sc.void_future_id_map);
}
/*=================================StatementContext=================================*/
void StatementContext::addIntFuture(std::future<int64_t>& f, const int64_t id) {
std::lock_guard<std::mutex> section_monitor(map_mutex);
assert(int_future_id_map.count(id)==0 && "Statement id already exists");
int_future_id_map.insert(std::pair<int64_t,std::future<int64_t>>(id,std::move(f)));
}
void StatementContext::addFloatFuture(std::future<double>& f, const int64_t id) {
std::lock_guard<std::mutex> section_monitor(map_mutex);
assert(float_future_id_map.count(id)==0 && "Statement id already exists");
float_future_id_map.insert(std::pair<int64_t,std::future<double>>(id,std::move(f)));
}
void StatementContext::addIntptrFuture(std::future<int64_t*>& f, const int64_t id) {
std::lock_guard<std::mutex> section_monitor(map_mutex);
assert(intptr_future_id_map.count(id)==0 && "Statement id already exists");
intptr_future_id_map.insert(std::pair<int64_t,std::future<int64_t*>>(id,std::move(f)));
}
void StatementContext::addFloatptrFuture(std::future<double*>& f, const int64_t id) {
std::lock_guard<std::mutex> section_monitor(map_mutex);
assert(floatptr_future_id_map.count(id)==0 && "Statement id already exists");
floatptr_future_id_map.insert(std::pair<int64_t,std::future<double*>>(id,std::move(f)));
}
void StatementContext::addVoidFuture(std::future<void>& f, const int64_t id) {
std::lock_guard<std::mutex> section_monitor(map_mutex);
assert(void_future_id_map.count(id)==0 && "Statement id already exists");
void_future_id_map.insert(std::pair<int64_t,std::future<void>>(id,std::move(f)));
}
std::future<int64_t> StatementContext::getIntFuture(const int64_t id) {
std::lock_guard<std::mutex> section_monitor(map_mutex);
auto f = std::move(int_future_id_map.at(id));
int_future_id_map.erase(id);
return f;
}
std::future<double> StatementContext::getFloatFuture(const int64_t id) {
std::lock_guard<std::mutex> section_monitor(map_mutex);
auto f = std::move(float_future_id_map.at(id));
float_future_id_map.erase(id);
return f;
}
std::future<int64_t*> StatementContext::getIntptrFuture(const int64_t id) {
std::lock_guard<std::mutex> section_monitor(map_mutex);
auto f = std::move(intptr_future_id_map.at(id));
intptr_future_id_map.erase(id);
return f;
}
std::future<double*> StatementContext::getFloatptrFuture(const int64_t id) {
std::lock_guard<std::mutex> section_monitor(map_mutex);
auto f = std::move(floatptr_future_id_map.at(id));
floatptr_future_id_map.erase(id);
return f;
}
std::future<void> StatementContext::getVoidFuture(const int64_t id) {
std::lock_guard<std::mutex> section_monitor(map_mutex);
auto f = std::move(void_future_id_map.at(id));
void_future_id_map.erase(id);
return f;
}
/*=================================ParContextManager=================================*/
ParContextManager::ParContextManager() {
set_max_threads();
thread_count = 0;
next_cid = 0;
}
int64_t ParContextManager::make_context() {
std::lock_guard<std::mutex> section_monitor(mutex);
int64_t cid = next_cid++;
context_map.insert(std::pair<int64_t,StatementContext>(cid,std::move(StatementContext())));
return cid;
}
void ParContextManager::destroy_context(const int64_t cid) {
std::lock_guard<std::mutex> section_monitor(mutex);
assert(context_map.count(cid)==1 && "Couldnt find exactly one context to destroy");
context_map.erase(cid);
}
void ParContextManager::sched_int(int64_t (*statement)(void*),void* env,const int64_t id,const int64_t cid) {
std::lock_guard<std::mutex> section_monitor(mutex);
std::future<int64_t> promise;
if (thread_count >= max_threads) {
promise = std::async(std::launch::deferred,statement,env);
} else {
promise = std::async(std::launch::async,statement,env);
thread_count++;
}
context_map.at(cid).addIntFuture(promise,id);
}
void ParContextManager::sched_float(double (*statement)(void*),void* env,const int64_t id,const int64_t cid) {
std::lock_guard<std::mutex> section_monitor(mutex);
std::future<double> promise;
if (thread_count >= max_threads) {
promise = std::async(std::launch::deferred,statement,env);
} else {
promise = std::async(std::launch::async,statement,env);
thread_count++;
}
context_map.at(cid).addFloatFuture(promise,id);
}
void ParContextManager::sched_intptr(int64_t* (*statement)(void*),void* env,int64_t id,const int64_t cid) {
std::lock_guard<std::mutex> section_monitor(mutex);
std::future<int64_t*> promise;
if (thread_count >= max_threads) {
promise = std::async(std::launch::deferred,statement,env);
} else {
promise = std::async(std::launch::async,statement,env);
thread_count++;
}
context_map.at(cid).addIntptrFuture(promise,id);
}
void ParContextManager::sched_floatptr(double* (*statement)(void*),void* env,int64_t id,const int64_t cid) {
std::lock_guard<std::mutex> section_monitor(mutex);
std::future<double*> promise;
if (thread_count >= max_threads) {
promise = std::async(std::launch::deferred,statement,env);
} else {
promise = std::async(std::launch::async,statement,env);
thread_count++;
}
context_map.at(cid).addFloatptrFuture(promise,id);
}
void ParContextManager::sched_void(void (*statement)(void*),void* env,int64_t id,const int64_t cid) {
std::lock_guard<std::mutex> section_monitor(mutex);
std::future<void> promise;
if (thread_count >= max_threads) {
promise = std::async(std::launch::deferred,statement,env);
} else {
promise = std::async(std::launch::async,statement,env);
thread_count++;
}
context_map.at(cid).addVoidFuture(promise,id);
}
int64_t ParContextManager::recon_int(const int64_t original,const int64_t known,
const int64_t id,const int64_t max,const int64_t cid) {
mutex.lock();
std::chrono::milliseconds span(0);
std::future<int64_t> fv = context_map.at(cid).getIntFuture(id);
int64_t v;
mutex.unlock();
if (fv.wait_for(span)==std::future_status::deferred) {
v = fv.get();
} else {
v = fv.get();
mutex.lock();
thread_count--;
mutex.unlock();
}
return v;
}
double ParContextManager::recon_float(const double original,const int64_t known,
const int64_t id,const int64_t max,const int64_t cid) {
mutex.lock();
std::chrono::milliseconds span(0);
std::future<double> fv = context_map.at(cid).getFloatFuture(id);
double v;
mutex.unlock();
if (fv.wait_for(span)==std::future_status::deferred) {
v = fv.get();
} else {
v = fv.get();
mutex.lock();
thread_count--;
mutex.unlock();
}
return v;
}
int64_t* ParContextManager::recon_intptr(const int64_t* original,const int64_t known,
const int64_t id,const int64_t max,const int64_t cid) {
mutex.lock();
std::chrono::milliseconds span(0);
std::future<int64_t*> fv = context_map.at(cid).getIntptrFuture(id);
int64_t* v;
mutex.unlock();
if (fv.wait_for(span)==std::future_status::deferred) {
v = fv.get();
} else {
v = fv.get();
mutex.lock();
thread_count--;
mutex.unlock();
}
return v;
}
double* ParContextManager::recon_floatptr(const double* original,const int64_t known,
const int64_t id,const int64_t max,const int64_t cid) {
mutex.lock();
std::chrono::milliseconds span(0);
std::future<double*> fv = context_map.at(cid).getFloatptrFuture(id);
double* v;
mutex.unlock();
if (fv.wait_for(span)==std::future_status::deferred) {
v = fv.get();
} else {
v = fv.get();
mutex.lock();
thread_count--;
mutex.unlock();
}
return v;
}
void ParContextManager::recon_void(const int64_t id,const int64_t max,const int64_t cid) {
mutex.lock();
std::chrono::milliseconds span(0);
std::future<void> fv = context_map.at(cid).getVoidFuture(id);
mutex.unlock();
if (fv.wait_for(span)==std::future_status::deferred) {
fv.get();
} else {
fv.get();
mutex.lock();
thread_count--;
mutex.unlock();
}
}
void ParContextManager::set_max_threads() {
unsigned long dth = std::thread::hardware_concurrency();
printf("Detected %d compute elements.\n",(int)dth);
if (dth < 2) max_threads = 2;
else if (dth > 4) max_threads = 4;
else max_threads = dth;
printf("Setting max execution threads: %d\n",(int)max_threads);
}
| true |
a6ecc931ee6db2fa7240a5fa7709c2d31e6ec44b | C++ | AleixFerre/Advent-of-Code-2020 | /Day08/Day08-1/main.cpp | UTF-8 | 828 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main() {
int accumulator = 0, index = 0;
int len = 638;
vector<bool> visited (len, false);
vector<pair<string,int>> commands;
for (int i = 0; i < len; i++) {
string com;
int param;
cin >> com >> param;
commands.push_back(make_pair(com, param));
}
while (not visited[index]) {
visited[index] = true;
// Process the current index
string com = commands[index].first;
int param = commands[index].second;
if (com == "nop") {
index++;
} else if (com == "acc") {
accumulator += param;
index++;
} else if (com == "jmp") {
index += param;
}
}
cout << accumulator << endl;
return 0;
}
| true |
ac4dc6acf6270f9782d173810be189548222320e | C++ | arnabgho/competitive_programming | /lib/longest_increasing_path_matrix.cpp | UTF-8 | 1,067 | 2.6875 | 3 | [] | no_license | class Solution {
public:
vector<vector<int>> DP;
int n,m;
int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};
bool isValid(int i,int j){
return 0<=i && i<n && 0<=j && j<m;
}
int dfs(int u,int v,vector<vector<int>>& matrix){
if(DP[u][v]!=-1)
return DP[u][v];
int val=1;
for(int i=0;i<4;i++){
if(isValid(u+dx[i],v+dy[i])){
if(matrix[u+dx[i]][v+dy[i]]>matrix[u][v]){
val=max(val,1+dfs(u+dx[i],v+dy[i],matrix));
}
}
}
return DP[u][v]=val;
}
int longestIncreasingPath(vector<vector<int>>& matrix) {
if(matrix.size()==0) return 0;
DP=matrix;
n=matrix.size();
m=matrix[0].size();
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
DP[i][j]=-1;
int ans=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
ans=max(ans,dfs(i,j,matrix));
}
}
return ans;
}
}; | true |
d64ff128d0e2b2a1cd80d6f9b4014519a1e52cf2 | C++ | c-Lris-xmu/bp | /main.cpp | GB18030 | 2,397 | 2.984375 | 3 | [] | no_license | //BP Neural Network
#include<iostream>
#include<fstream>
#include"headers/Matrix.hpp"
#include"headers/BP_net.h"
#include"headers/data_loader.h"
#include<Python.h>
#include<string>
using namespace std;
template<class T>
string creat_arr(T* arr, int n)
{
//c++תpythonlist
string str = "[";
for (int i = 0; i < n; i++)
{
str += to_string(arr[i]);
if (i < n - 1) str += ",";
}
str += "]";
return str;
}
template<class T>
void plot(T* x, int n, string s)
{
//PyRun_SimpleString("import matplotlib.pyplot as plt");
string cmd = "plt.plot(";
string s1 = creat_arr(x, n);
cmd += (s1 + s+")");
PyRun_SimpleString(cmd.c_str());
//PyRun_SimpleString("plt.show()");
}
void draw(int n, double* loss1, double* loss2, double* loss3, double* acc1, double* acc2, double* acc3)
{
Py_Initialize();
PyRun_SimpleString("import matplotlib.pyplot as plt");
PyRun_SimpleString("plt.figure(figsize = (10, 10), dpi = 100)");
PyRun_SimpleString("plt.figure(1)");
// draw loss
PyRun_SimpleString("plt.subplot(2, 1, 1)");
plot(loss1, n, ",label='loss of four neure'");
plot(loss2, n, ",label='loss of five neure'");
plot(loss3, n, ",label='loss of six neure'");
PyRun_SimpleString("plt.xlabel('epoch')");
PyRun_SimpleString("plt.ylabel('loss')");
PyRun_SimpleString("plt.legend()");
//draw acc
PyRun_SimpleString("plt.subplot(2, 1, 2)");
plot(acc1, n, ",label='acc of four neure'");
plot(acc2, n, ",label='acc of five neure'");
plot(acc3, n, ",label='acc of six neure'");
PyRun_SimpleString("plt.xlabel('epoch')");
PyRun_SimpleString("plt.ylabel('acc')");
PyRun_SimpleString("plt.legend()");
//suptitle
PyRun_SimpleString("plt.suptitle('loss and accuracy of the BPnet')");
//save pic
PyRun_SimpleString("plt.savefig('./loss_and_acc.jpg')");
PyRun_SimpleString("plt.show()");
Py_Finalize();
}
int main()
{
cout << "-----START-----" << endl;
data_loader data;
data.read_file("./data/iris.data");
cout << "=============Train 1==============" << endl;
BPnet net1(100, 0.01, 0.01,4);
net1.train(data);
cout << "=============Train 2==============" << endl;
BPnet net2(100, 0.01, 0.01, 5);
net2.train(data);
cout << "=============Train 3==============" << endl;
BPnet net3(100, 0.01, 0.01, 6);
net3.train(data);
cout << "-----END-----" << endl;
draw(100,net1.loss, net2.loss, net3.loss,net1.acc,net2.acc,net3.acc);
system("pause");
return 0;
}
| true |
4233942bbd0b8a9fc5cbdc166f3c26c3f5a01402 | C++ | snate/memoco_ex | /ex2_heur/src_GA/TSPSelector.cpp | UTF-8 | 962 | 3.4375 | 3 | [] | no_license | /**
* @file TSPSelector.cpp
* @brief Provides a couple of parents for the GA
*
*/
#include "TSPSelector.h"
#include <iostream>
#include <algorithm>
using namespace std;
vector<TSPSolution*> TSPSelector::
takeTwoParents(const TSPPopulation& pop) {
vector<TSPSolution*> result;
result.resize(2);
TSPSolution* firstParent = extractParentWithLinearRanking(pop.population);
TSPSolution* secondParent;
do
secondParent = extractParentWithLinearRanking(pop.population);
while((*firstParent).sequence == (*secondParent).sequence);
result[0] = firstParent;
result[1] = secondParent;
return result;
}
// POSTCONDITION: `result HAS EXACTLY TWO PARENTS
// PRECONDITION: `solutions MUST BE AN "ORDERED" VECTOR
TSPSolution* TSPSelector::
extractParentWithLinearRanking(vector<TSPSolution*> solutions) {
random_shuffle( roulette.begin(), roulette.end() );
int winner = roulette[0];
return solutions[winner];
}
| true |
dc6f084b68f5b8a944a6e596cd10db05fe992364 | C++ | choyunhae/Online-Ticket-Exchange-System | /src/소프트웨어공학_3조/LogIn.cpp | UTF-8 | 505 | 2.5625 | 3 | [] | no_license | #include "LogIn.h"
//function : bool showLogIn(string inputID, string inputPassword)
//description : �α����� ���� �Լ�
//parameter : string inputID-�Է¹��� ���̵�, string inputPassword-�Է¹��� �н�����
bool LogIn::showLogIn(string inputID, string inputPassword){
bool logInMember=false;
MemberManager *memberManager = MemberManager::getInstance();
logInMember = memberManager->requestLogIn(inputID, inputPassword);
return logInMember;
} | true |
1108791e1d1717e986cd7e504c3679f709ab909f | C++ | patcain34/smallchess | /testingGit/main.cpp | UTF-8 | 439 | 2.5625 | 3 | [] | no_license | //
// main.cpp
// testingGit
//
// Created by Ibrahim Saeed on 10/8/14.
// Copyright (c) 2014 Ibrahim Saeed. All rights reserved.
//
#include <iostream>
using namespace std;
int main(int argc, const char * argv[])
{
// insert code here...
cout << "Hello, World!\n";
cout << "More changes!\n";
cout << "Adding EVEN more changes";
int x = 24;
cout << "this will help us work pretty good";
return 0;
}
| true |
2583b7429daf4218749dc193957fce1227c3d8c8 | C++ | alexandraback/datacollection | /solutions_1595491_0/C++/feigao/B.cpp | UTF-8 | 1,193 | 2.59375 | 3 | [] | no_license | #include <algorithm>
#include <bitset>
#include <cmath>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
#define For(i, a, b) for (int i = (a); i != b; i++)
#define Rep(i,n) For(i,0,n)
#define debug(x) cout<<#x<<": "<<x<<endl
#define Pb push_back
#define Mp make_pair
template<class T>void show(T a,int n) {Rep(i,n)cout<<a[i]<<' ';cout<<endl;}
template<class T>void show(T a,int n,int m) {Rep(i,n){Rep(j,m)cout<<a[i][j]<<' ';cout<<endl;}}
int main() {
int T;
scanf("%d\n", &T);
int N, S, p, t, p3;
Rep(iT, T) {
printf("Case #%d: ", iT+1);
int good = 0, bad = 0;
scanf("%d%d%d", &N, &S, &p);
p3 = p * 3;
if (p == 0) {
Rep(iN, N) scanf("%d", &t);
good = N;
} else if (p == 1) {
Rep(iN, N) {
scanf("%d", &t);
if (t > 0) good++;
}
} else {
Rep(iN, N) {
scanf("%d", &t);
if (t >= p3 - 2) {
good++;
continue;
} else if (t <= p3 - 5) {
continue;
} else {
bad++;
continue;
}
}
}
printf("%d\n", good + min(bad, S));
}
return 0;
}
| true |
d3ad5e68f7ac3e2b0fdbe147e79de748769dc10b | C++ | cyrille42/2dGame | /src/SDL/Image.cpp | UTF-8 | 1,663 | 3 | 3 | [] | no_license | #include "Image.hpp"
Image::Image(SDL_Renderer* gRenderer, std::string str, int red, int green , int blue)
{
//The final texture
SDL_Texture* newTexture = NULL;
//Load image at specified path
SDL_Surface* loadedSurface = SDL_LoadBMP( str.c_str() );//IMG_LoadTexture
SDL_SetColorKey(loadedSurface, SDL_TRUE, SDL_MapRGB(loadedSurface->format, red, green, blue));//turn one color to invisible
if( loadedSurface == NULL )
ft_puterror( "Unable to load image ! SDL_image Error: ", SDL_GetError() );
//Create texture from surface pixels
newTexture = SDL_CreateTextureFromSurface( gRenderer, loadedSurface );
if( newTexture == NULL )
ft_puterror( "Unable to create texture from ! SDL Error: ", SDL_GetError() );
//Get rid of old loaded surface
SDL_FreeSurface( loadedSurface );
//std::cout << "[INFOS]: The texture have been loaded." << std::endl;
this->_texture = newTexture;
}
void Image::ft_puterror(std::string s1, std::string s2)
{
std::cout << RED << "[ERROR]: ";
std::cout << s1 << s2 << "." << RESET << std::endl;
SDL_Quit();
std::exit(EXIT_FAILURE);
}
Image::Image(SDL_Renderer* gRenderer, std::string str)
{
SDL_Texture* newTexture = NULL;
SDL_Surface* loadedSurface = SDL_LoadBMP( str.c_str() );//IMG_LoadTexture
if( loadedSurface == NULL )
ft_puterror( "Unable to load image ! SDL_image Error: ", SDL_GetError() );
newTexture = SDL_CreateTextureFromSurface( gRenderer, loadedSurface );
if( newTexture == NULL )
ft_puterror( "Unable to create texture from ! SDL Error: ", SDL_GetError() );
SDL_FreeSurface( loadedSurface );
this->_texture = newTexture;
}
SDL_Texture* Image::getTexture()
{
return (this->_texture);
}
| true |
7bff662c31b10b30889eb38b35324b22a73fbb8a | C++ | hfchong/fold | /tensorflow_fold/llgtm/examples/parsetree.h | UTF-8 | 3,734 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | /* Copyright 2017 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Simple tree data structure used by tree_rnn.cc.
#ifndef TENSORFLOW_FOLD_LLGTM_EXAMPLES_PARSETREE_H_
#define TENSORFLOW_FOLD_LLGTM_EXAMPLES_PARSETREE_H_
#include <initializer_list>
#include <memory>
#include <string>
#include "absl/memory/memory.h"
#include "absl/strings/string_view.h"
#include "tensorflow_fold/llgtm/llgtm.h"
namespace llgtm {
namespace parse_trees {
class LeafNode;
class PhraseNode;
// Base class for nodes in the parse tree.
// Trees are an algebraic data type:
// data TreeNode = LeafNode string | ParseNode TreeNode TreeNode
// [https://en.wikipedia.org/wiki/Algebraic_data_type]
class TreeNode {
public:
TreeNode() {}
TreeNode(const TreeNode&) = delete;
virtual ~TreeNode() {}
TreeNode& operator=(const TreeNode&) = delete;
// Derived classes must override one of the following to return this.
virtual LeafNode* get_leaf() { return nullptr; }
virtual PhraseNode* get_phrase() { return nullptr; }
// Pattern match on the type of the TreeNode.
// Execute leaf_case(this) or phrase_case(this) depending on type.
template<typename F1, typename F2>
auto SwitchOnType(F1 leaf_case, F2 phrase_case)
-> decltype(leaf_case(static_cast<LeafNode*>(nullptr))) {
if (auto* leaf = get_leaf()) {
return leaf_case(leaf);
} else {
auto* phrase = get_phrase();
CHECK(phrase != nullptr);
return phrase_case(phrase);
}
}
};
// A leaf (terminal) node in the parse tree, which contains a single word.
class LeafNode : public TreeNode {
public:
explicit LeafNode(string word) : word_(std::move(word)) {}
~LeafNode() override {}
absl::string_view word() const { return word_; }
LeafNode* get_leaf() override { return this; }
private:
const string word_;
};
// A phrase (non-terminal) in the parse tree, which contains sub-phrases.
class PhraseNode : public TreeNode {
public:
using NodeType = std::unique_ptr<TreeNode>;
PhraseNode() = delete;
~PhraseNode() override {}
explicit PhraseNode(NodeType a) {
sub_nodes_.emplace_back(std::move(a));
}
PhraseNode(NodeType a, NodeType b) {
sub_nodes_.emplace_back(std::move(a));
sub_nodes_.emplace_back(std::move(b));
}
PhraseNode(NodeType a, NodeType b, NodeType c) {
// std::initializer_list doesn't work with move-only types, so we have
// to do this the hard way.
sub_nodes_.emplace_back(std::move(a));
sub_nodes_.emplace_back(std::move(b));
sub_nodes_.emplace_back(std::move(c));
}
const std::vector<NodeType>& sub_nodes() const { return sub_nodes_; }
PhraseNode* get_phrase() override { return this; }
private:
std::vector<NodeType> sub_nodes_;
};
// Creates a new LeafNode.
inline std::unique_ptr<TreeNode> Leaf(string str) {
return absl::make_unique<LeafNode>(std::move(str));
}
// Creates a new PhraseNode.
template <class... Args>
inline std::unique_ptr<TreeNode> Phrase(Args... args) {
return absl::make_unique<PhraseNode>(std::move(args)...);
}
} // namespace parse_trees
} // namespace llgtm
#endif // TENSORFLOW_FOLD_LLGTM_EXAMPLES_PARSETREE_H_
| true |
29864e4470f8e9a62bc0ebdc243033b3e6b72398 | C++ | alex-zinin/coursera_cpp_projects | /red_belt/week4/text_editor/main.cpp | UTF-8 | 7,145 | 3.359375 | 3 | [] | no_license | #include <string>
#include "test_runner.h"
#include<string_view>
#include"profile.h"
#include<list>
#include<deque>
#include<algorithm>
#include<iterator>
using namespace std;
class Editor {
public:
// Реализуйте конструктор по умолчанию и объявленные методы
Editor(): text(), buffer_size(0)
{
text.clear();
pos = text.begin();
}
void Left()
{
if(pos != text.begin())
{
pos--;
}
}
void Right()
{
if(pos != text.end())
{
pos++;
}
}
void Insert(const char& token)
{
auto it = text.insert(pos, token);
it++;
pos = it;
}
void Cut(size_t tokens)
{
if(tokens == 0 || pos == text.end() || text.empty())
{
buffer_size = 0;
return;
}
auto it = pos;
int size = 0;
for(int i = 0; i < tokens; i++)
{
it++;
size++;
if(it == text.end())
break;
}
if(it != text.end())
{
move(pos, it, buffer.begin());
buffer_size = tokens;
pos = text.erase(pos, it);
} else
{
move(pos, text.end(), buffer.begin());
buffer_size = size;
text.erase(pos, text.end());
pos = text.end();
}
}
void Copy(size_t tokens)
{
if(tokens == 0 || pos == text.end() || text.empty())
{
buffer_size = 0;
return;
}
auto it = pos;
int size = 0;
for(int i = 0; i < tokens; i++)
{
it++;
size++;
if(it == text.end())
break;
}
if(it != text.end())
{
move(pos, it, buffer.begin());
buffer_size = tokens;
}
else
{
move(pos, text.end(), buffer.begin());
buffer_size = size;
}
}
void Paste()
{
if(buffer_size != 0)
pos = text.insert(pos, buffer.begin(), buffer.begin() + buffer_size);
for(int i = 0; i < buffer_size; i++)
pos++;
}
string GetText() const
{
return string(text.begin(), text.end());
}
public:
list<char> text;
list<char>::iterator pos;
int buffer_size;
deque<char> buffer;
};
void TypeText(Editor& editor, const string& text) {
for(char c : text) {
editor.Insert(c);
}
}
void TestEditing() {
{
Editor editor;
const size_t text_len = 12;
const size_t first_part_len = 7;
TypeText(editor, "hello, world");//cout << editor.text << endl;
for(size_t i = 0; i < text_len; ++i) {
editor.Left();
}//cout << *editor.it << endl;
editor.Cut(first_part_len);//cout << editor.buffer << "?" << endl;
for(size_t i = 0; i < text_len - first_part_len; ++i) {
editor.Right();
}
TypeText(editor, ", ");//cout << editor.text << endl;
editor.Paste();// cout << *editor.pos << endl;
editor.Left();
editor.Left();
editor.Cut(3);//
ASSERT_EQUAL(editor.GetText(), "world, hello");
}
{
Editor editor;
TypeText(editor, "misprnit");
editor.Left();
editor.Left();
editor.Left();
editor.Cut(1);
editor.Right();
editor.Paste();
ASSERT_EQUAL(editor.GetText(), "misprint");
}
}
void TestReverse() {
Editor editor;
const string text = "esreveR";
for(char c : text) {
editor.Insert(c);
editor.Left();
}
ASSERT_EQUAL(editor.GetText(), "Reverse");
}
void TestNoText() {
Editor editor;
ASSERT_EQUAL(editor.GetText(), "");
editor.Left();
editor.Left();
editor.Right();
editor.Right();
editor.Copy(0);
editor.Cut(0);
editor.Paste();
ASSERT_EQUAL(editor.GetText(), "");
}
void TestEmptyBuffer() {
Editor editor;
editor.Paste();
TypeText(editor, "example");
editor.Left();
editor.Left();
editor.Paste();
editor.Right();
editor.Paste();
editor.Copy(0);
editor.Paste();
editor.Left();
editor.Cut(0);
editor.Paste();
ASSERT_EQUAL(editor.GetText(), "example");
}
void MyTest()
{
Editor editor;
TypeText(editor, "sfa");
editor.Cut(10);
editor.Paste();
editor.Left();
editor.Right();
ASSERT_EQUAL(editor.GetText(), "sfa");
}
void Testing_Cut()
{
Editor editor;
//1
editor.Cut(10);
editor.Insert('a');
editor.Left();
//2
editor.Cut(1);
ASSERT_EQUAL(editor.GetText(), "");
editor.Paste();
ASSERT_EQUAL(editor.GetText(), "a");
//3
editor.Cut(0);
editor.Paste();
ASSERT_EQUAL(editor.GetText(), "a");
TypeText(editor, "bcde");
editor.Left();editor.Left();editor.Left();editor.Left();editor.Left();
//4
editor.Cut(10);
ASSERT_EQUAL(editor.GetText(), "");
editor.Paste();
ASSERT_EQUAL(editor.GetText(), "abcde");
editor.Left();editor.Left();editor.Left();editor.Left();editor.Left();
//5
editor.Cut(5);
ASSERT_EQUAL(editor.GetText(), "");
editor.Paste();
//6
editor.Left();editor.Left();editor.Left();editor.Left();editor.Left();
editor.Cut(1);
ASSERT_EQUAL(editor.GetText(), "bcde");
editor.Right();
editor.Cut(1);
ASSERT_EQUAL(editor.GetText(), "bde");
editor.Cut(1);
editor.Cut(1);
ASSERT_EQUAL(editor.GetText(), "b");
}
void Testing_Copy()
{
Editor editor;
//1
editor.Copy(10);
editor.Insert('a');
editor.Paste();
editor.Left();
ASSERT_EQUAL(editor.GetText(), "a");
//2
editor.Copy(1);
editor.Paste();
ASSERT_EQUAL(editor.GetText(), "aa");//between a
//3
editor.Copy(0);
editor.Paste();
ASSERT_EQUAL(editor.GetText(), "aa");
TypeText(editor, "bcde");
editor.Left();editor.Left();editor.Left();editor.Left();editor.Left();editor.Left();
//4
editor.Cut(10);
ASSERT_EQUAL(editor.GetText(), "");
editor.Paste();
ASSERT_EQUAL(editor.GetText(), "abcdea");
}
void RunTimeTest()
{
Editor editor;
LOG_DURATION("RUN_TIME_TEST:");
for(int i = 0; i < 199000; i++)
{
editor.Insert('a');
editor.Insert('q');
editor.Insert('f');
editor.Insert('u');
editor.Insert('k');
}
for(int i = 0; i < 500000; i++)
{
//int a = (editor.text.end() - editor.text.begin())/2;
//editor.pos = editor.text.begin() + a;(int) (editor.text.end() - editor.text.begin())/2;
editor.Paste();
editor.Copy(10);
editor.Right();
editor.Paste();
editor.Cut(10);
}
}
int main() {
TestRunner tr;
RUN_TEST(tr, TestEditing);
RUN_TEST(tr, TestReverse);
RUN_TEST(tr, TestNoText);
RUN_TEST(tr, TestEmptyBuffer);
RUN_TEST(tr, MyTest);
RUN_TEST(tr, Testing_Copy);
RUN_TEST(tr, Testing_Cut);
RUN_TEST(tr, RunTimeTest);
return 0;
} | true |
ac687b0dc28ac680d5c19bd8076c02e21bfe1403 | C++ | Quinny/Online-Judge | /euler/034 Digit factorials.cpp | UTF-8 | 420 | 3.546875 | 4 | [] | no_license | #include <iostream>
int fact(int);
int factDigits(int);
int main(){
int ans = 0;
for(int i = 3; i <= 40585; i++){
if(i == factDigits(i)) ans += i;
}
std::cout << ans << std::endl;
return 0;
}
int fact(int n){
if(n == 0)
return 1;
int ans = n;
for(int i = n - 1; i >= 2; i--)
ans *= i;
return ans;
}
int factDigits(int n){
int ans = 0;
while(n > 0){
ans += fact(n%10);
n /= 10;
}
return ans;
}
| true |
4acaf05cd3a62fedf1f19e7ee0da12cfb3ca2000 | C++ | Siriayanur/DSA | /DP/421PaintingFence.cpp | UTF-8 | 591 | 2.84375 | 3 | [] | no_license | #include<iostream>
using namespace std;
long long paintFence(int n,int k){
int mod = 1000000007;
if(n == 0 || k == 0){
return 0;
}
if(n == 1){
return k;
}
long long same = (k * 1) % mod;
long long diff = (k * (k - 1)) % mod;
long long total = (same + diff) % mod;
for (int i = 3; i <= n;i++){
same = (diff * 1) % mod;
diff = (total * (k - 1)) % mod;
total = (same + diff) % mod;
}
return (total % mod);
}
int main(){
int n, k;
cin >> n >> k;
cout << paintFence(n, k) << endl;
return 0;
} | true |
1071871bf863d7424004738f5c87202980c75c61 | C++ | joses97/SanchezJose_CSC5_41202 | /Class/Savitch__8thEd_Chapt2_Prob12_V2/main.cpp | UTF-8 | 1,202 | 3.484375 | 3 | [] | no_license | /*
* File: main.cpp
* Author: Jose Sanchez
* Purpose: Uses loop to end calculation
* Created on January 14, 2016, 10:29
*/
//System Libraries
#include <iostream>
#include <cmath>
using namespace std;
//User Libraries
//Global Constants
//Function prototypes
//Execution Begins Here
int main(int argc, char** argv) {
//Declare and initialize variables
float n;//Input the value to obtain its square root
float r, guess;
float tol=0.001f;//Accuracy of the result/tolerance
int counter=0;//see how many loops it took ti find the answer
//Input data
cout<<"Input the value to take the square root of "<<endl;
cin>>n;
//approx square root
guess=n/2;
//Output the results
cout<<"The input value = "<<n<<endl;
cout<<"The square of "<<n<<" = "<<sqrt(n)<<endl;
//approx square root
do {
r=n/guess;
guess=(guess+r)/2;
counter++;
} while (abs((r-guess)/guess)*100>tol); //ends the loop when close enough
//Output the results
cout<<"The r = "<<r<<endl;
cout<<"The guess = "<<guess<<endl;
cout<<"Loops executed = "<<counter<<endl;
//Exit stage right and close
return 0;
}
| true |
99facb61ef312a2c54c4882598239ccd765eb68d | C++ | SaberDa/LeetCode | /C++/246-strobogrammaticNumber.cpp | UTF-8 | 407 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <unordered_map>
using namespace std;
bool isStrobogrammatic(string num) {
string s = "";
if (num.empty()) return false;
unordered_map<char, char> mp{{'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'}, {'0', '0'}};
for (auto c : num) {
if (!mp.count(c)) return false;
s.push_back(mp[c]);
}
reverse(s.begin(), s.end());
return s == num;
} | true |
6eabbb41d2266c28551997454808bdf01833378c | C++ | marco-chen4u/sort | /main.cpp | UTF-8 | 6,428 | 3.8125 | 4 | [] | no_license | #include <iostream>
#include <iomanip>
#include <algorithm>
using namespace std;
void printArr(int *arr, int len) {
for (int i = 0; i < len; ++i) {
cout << setw(5) << arr[i];
}
cout << endl;
}
// 1.直接插入排序
void insertSort(int *arr, int len) {
for (int i = 1; i < len; ++i) { // 从第2个元素开始插入,原始单个元素视为有序
if (arr[i] < arr[i - 1]) {
int x = arr[i];
int j = i - 1; // 原始序列的最后一个
while (x < arr[j] && j >= 0) {
arr[j + 1] = arr[j];
j--;
}
// 跳出时,x >= arr[j]
arr[j + 1] = x;
}
}
}
// 2.希尔排序
void shellSort(int *arr, int len) {
for (int dk = len / 2; dk > 0; --dk) { // dk增量
for (int i = dk; i < len; ++i) { // 1层for
if (arr[i] < arr[i - dk]) {
int x = arr[i]; // 哨兵
int j = i - dk; // 原有序序列最后一个元素
while (x < arr[j] && j >= 0) {
arr[j + dk] = arr[j];
j -= dk;
}
arr[j + dk] = x;
}
}
}
}
// 3.选择排序
void selectSort(int *arr, int len) {
for (int i = 0; i < len - 1; ++i) {
for (int j = i + 1; j < len; ++j) {
if (arr[i] > arr[j]) swap(arr[i], arr[j]); // 最小值放前思想
}
}
}
// 4.堆排序
// 调整大顶堆
void heapAdjust(int *arr, int root, int len) {
int child = 2 * root + 1;
while (child < len) { // child可以去最后一个元素:len-1
if (child + 1 < len && arr[child] < arr[child + 1]) child++; // child指向大孩子
if (arr[root] < arr[child]) {
swap(arr[root], arr[child]);
root = child;
child = 2 * root + 1;
} else {
break; // 基于下面已经满足大顶堆
}
}
}
// 构建大顶堆
void buildHeap(int *arr, int len) {
for (int i = (len - 1) / 2; i >= 0; --i) { // (length-1)/2 最大的非叶节点
heapAdjust(arr, i, len); // i遍历所有的root
}
}
void heapSort(int *arr, int len) {
buildHeap(arr, len);
cout << "调整之后";
printArr(arr, len);
while (len > 1) {
swap(arr[0], arr[len - 1]); // 首尾元素互换
cout << "len=" << len;
printArr(arr, len);
len--;
heapAdjust(arr, 0, len);
}
}
// 5.冒泡排序
void bubbleSort(int *arr, int len) {
for (int i = 0; i < len - 1; ++i) {
for (int j = 0; j < len - 1 - i; ++j) {
if (arr[j] > arr[j + 1]) swap(arr[j], arr[j + 1]); // 最大值放后思想
}
}
}
// 6.快速排序
// 分成两部分
int partition(int *arr, int low, int high) {
int pivot = arr[low]; // 选第1个值为基准值
while (low < high) {
while (low < high && arr[high] >= pivot) high--;
swap(arr[high], arr[low]); // 大小值更换,注意:更换的不是pivot
while (low < high && arr[low] <= pivot) low++;
swap(arr[high], arr[low]); // 大小值更换
}
return low;
}
void quickSort(int *arr, int low, int high) {
if (low < high) {
int pivotLoc = partition(arr, low, high); // 基准值位置
// printArr(arr, high + 1);
quickSort(arr, low, pivotLoc - 1);
quickSort(arr, pivotLoc + 1, high);
}
}
// 7.归并排序
void merge(int *arr, int low, int mid, int high) {
auto *tmp = new int[high - low + 1]; // 暂存数据
// int tmp[high - low + 1]; // 也OK
// 3个序列迭代器
int i = low; // 序列1开始
int j = mid + 1; // 序列2开始
int k = 0; // 合并新序列开始
while (i <= mid && j <= high) { // 都得小于最后一个元素
tmp[k++] = (arr[i] <= arr[j]) ? arr[i++] : arr[j++];
}
while (i <= mid) tmp[k++] = arr[i++];
while (j <= high) tmp[k++] = arr[j++];
i = low; // arr序列开始的位置
k = 0;
while (i <= high) arr[i++] = tmp[k++];
}
void mergeSort(int *arr, int low, int high) {
int mid;
if (low < high) {
mid = (low + high) / 2;
mergeSort(arr, low, mid); // 这里和merge中的j值有关
mergeSort(arr, mid + 1, high); // 先mergeSort成2个有序序列,再将2个序列合并有完整有序
merge(arr, low, mid, high);
}
}
// 8.基数排序
void radixSort(int *arr, int len, int radix) {
// 先找到待排序元素的上下界
int max = arr[0];
int min = arr[0];
for (int i = 1; i < len; ++i) {
if (max < arr[i]) max = arr[i];
if (min > arr[i]) min = arr[i];
}
// cout << max << "\t" << min << endl;
int bucket_num = max / radix - min / radix + 1; // 桶的数量,一定要分开除
int bucket_arr[bucket_num][len]; // 存储元素
int bucket_len[bucket_num]; // 记录每个桶的元素个数
for (int i = 0; i < bucket_num; ++i) bucket_len[i] = 0; // 赋初值
// 元素进入桶
cout << "元素进桶" << endl;
for (int i = 0; i < len; ++i) {
int bucket_id = arr[i] / radix - min / radix; // 桶id转移到数列下标,一定要分开除
bucket_arr[bucket_id][bucket_len[bucket_id]] = arr[i];
bucket_len[bucket_id]++;
}
// 打印各桶元素
for (int i = 0; i < bucket_num; ++i) {
cout << radix * (min / radix + i) << "," << radix * (min / radix + i + 1) - 1 << ": ";
printArr(bucket_arr[i], bucket_len[i]);
}
cout << "桶内排序" << endl;
for (int i = 0; i < bucket_num; ++i) {
if (bucket_len[i] > 1) quickSort(bucket_arr[i], 0, bucket_len[i] - 1);
}
// 打印排序后各桶元素
for (int i = 0; i < bucket_num; ++i) {
cout << radix * (min / radix + i) << "," << radix * (min / radix + i + 1) - 1 << ": ";
printArr(bucket_arr[i], bucket_len[i]);
}
// 排序后元素拷贝
int k = 0;
for (int i = 0; i < bucket_num; ++i) {
for (int j = 0; j < bucket_len[i]; ++j) {
arr[k] = bucket_arr[i][j];
k++;
}
}
}
int main() {
// 随机生成数据
int len = 20;
auto *arr = new int[len];
srand((unsigned int) time(nullptr));
for (int i = 0; i < len; ++i) arr[i] = (int) random() % 100;
printArr(arr, len);
radixSort(arr, len, 10); // 可以调整radix值
printArr(arr, len);
}
| true |
9271353501287bcd05f6cda4e51c11ea4175674b | C++ | namane88/3d | /src/math/mat4.h | UTF-8 | 679 | 3.0625 | 3 | [] | no_license | #ifndef MAT4_H
#define MAT4_H
#include <iostream>
#include <assert.h>
#include <cstring>
#include <math.h>
namespace math
{
class Mat4
{
private:
float values[16];
public:
Mat4();
Mat4(float value);
float *ref();
float& operator[](const int index) {
assert( index >= 0 && index <= 16);
return values[index];
}
friend Mat4 operator*(Mat4 &lhs, Mat4 &rhs);
void setIdentity(float value);
void clear();
void print() {
for(int i = 1; i <= 16; i++) {
std::cout << values[i-1] << "\t";
if ( 0 == (i % 4) ) std::cout << std::endl;
}
std::cout << std::endl;
}
float determinant();
};
}
#endif
| true |
6ee46f6c5aea354152071504c92faf1ddf2222ef | C++ | luzhlon/cpp | /relayer/Tcp.h | GB18030 | 1,647 | 2.578125 | 3 | [] | no_license | #ifndef __TCP_H_
#define __TCP_H_
#include "stdlib.h"
#include "string.h"
#define __WINDOWS__ 1
#ifdef __WINDOWS__
#ifndef _WINSOCKAPI_
#define _WINSOCKAPI_
#include "WinSock2.h"
#endif
#endif
class TcpConnect
{
public:
static void InitSocketLib();
public:
TcpConnect(SOCKET sock = NULL);
~TcpConnect();
void InitSocket(SOCKET sock = NULL);
bool setAddress(const char *addr);
bool setAddress(unsigned long ip);
const char *getIP(char *ipAddr);
unsigned long getIP();
inline int get_last(){ return m_ret; }
inline void setPort(unsigned int port){ m_sockAddr.sin_port = htons((u_short)port); }
inline unsigned int getPort(){ return ntohs(m_sockAddr.sin_port); }
inline int send(const char *buf, int len, int flags = 0)
{
return ::send(m_socket, buf, len, flags);
}
inline int recv(char *buf, int len, int flags = 0)
{
return ::recv(m_socket, buf, len, flags);
}
int Send(const char *buf, int len, int flags = 0); //֤lenֽ
int Recv(char *buf, int len, int flags = 0);//֤lenֽ
public:
SOCKET m_socket;
sockaddr_in m_sockAddr;
hostent *m_host;
int m_ret;
};
class TcpClient : public TcpConnect
{
public:
TcpClient();
~TcpClient();
inline bool connect();
bool connect(const char *addr, unsigned int port);
};
class TcpServer : public TcpConnect
{
public:
TcpServer();
~TcpServer();
bool bind(unsigned int port = 0);
bool listen(int backlog = 5);
TcpConnect* accept();
TcpConnect* waitConnect(unsigned int port, int backlog = 5);
bool m_binded;
bool m_listened;
};
#endif
| true |
7fb7b31a4af2fc59a49116bf5cb32f961fbeecd1 | C++ | Daedalus1400/Crypto_Nightmare | /src/main.cpp | UTF-8 | 686 | 2.765625 | 3 | [] | no_license | /*
* File: main.cpp
* Author: Daedalus
*
* Created on May 5, 2015
*/
#include <cstdlib>
#include <iostream>
#include <vector>
#include <thread>
#include "ThreadedEnigma.h"
#include "Timer.h"
#include "FileHandler.h"
using namespace std;
void PrintfromVector(vector<byte>);
int main() {
Timer * time = new Timer();
char password[] = "Arbitrary password for no reason";
vector<byte> * buffer = new vector<byte>;
GetFile("testimage", buffer);
ThreadedEnigma * cypher = new ThreadedEnigma();
cypher->Process(buffer, password, true, 8);
WriteFile("outimage", buffer);
//time->Delayms(5000);
return 0;
}
void PrintfromVector(vector<byte> text) {
for (char c : text) {
cout << c;
}
} | true |
187bda373954375e38c9cf57f3345693b325ff23 | C++ | lasagnaphil/altmath | /tests/vec_simd_test.cpp | UTF-8 | 3,749 | 3.046875 | 3 | [
"MIT"
] | permissive | //
// Created by lasagnaphil on 19. 8. 22..
//
#include "simd/vec2dx4.h"
#include "simd/vec3dx4.h"
#include "doctest.h"
TEST_CASE("vec2dx4 works") {
SUBCASE("Is POD") {
CHECK(std::is_pod<vec2dx4>());
}
SUBCASE("Arithmetic") {
vec2d a[4], b[4];
for (int i = 0; i < 4; i++) {
a[i].x = 4*i;
a[i].y = 4*i + 1;
b[i].x = 4*i + 2;
b[i].y = 4*i + 3;
}
vec2dx4 a4 = vec2dx4::load(a);
vec2dx4 b4 = vec2dx4::load(b);
CHECK(a4 == a4);
CHECK(a4 != b4);
vec2dx4 c4;
vec2d c[4];
c4 = a4 + b4;
for (int i = 0; i < 4; i++) {
c[i] = a[i] + b[i];
}
CHECK(c4 == vec2dx4::load(c));
c4 = a4 - b4;
for (int i = 0; i < 4; i++) {
c[i] = a[i] - b[i];
}
CHECK(c4 == vec2dx4::load(c));
c4 = a4 * b4;
for (int i = 0; i < 4; i++) {
c[i] = a[i] * b[i];
}
CHECK(c4 == vec2dx4::load(c));
c4 = a4 * 2.0;
for (int i = 0; i < 4; i++) {
c[i] = a[i] * 2.0;
}
CHECK(c4 == vec2dx4::load(c));
a4 += b4;
for (int i = 0; i < 4; i++) {
a[i] += b[i];
}
CHECK(a4 == vec2dx4::load(a));
a4 -= b4;
for (int i = 0; i < 4; i++) {
a[i] -= b[i];
}
CHECK(a4 == vec2dx4::load(a));
a4 *= b4;
for (int i = 0; i < 4; i++) {
a[i] *= b[i];
}
CHECK(a4 == vec2dx4::load(a));
vec4d anormsq = aml::normsq(a4);
CHECK(anormsq.x == aml::normsq(a[0]));
CHECK(anormsq.y == aml::normsq(a[1]));
CHECK(anormsq.z == aml::normsq(a[2]));
CHECK(anormsq.w == aml::normsq(a[3]));
}
}
TEST_CASE("vec3dx4 works") {
SUBCASE("Is POD") {
CHECK(std::is_pod<vec3dx4>());
}
SUBCASE("Arithmetic") {
vec3d a[4], b[4];
for (int i = 0; i < 4; i++) {
a[i].x = 6*i;
a[i].y = 6*i + 1;
a[i].z = 6*i + 2;
b[i].x = 6*i + 3;
b[i].y = 6*i + 4;
b[i].z = 6*i + 5;
}
vec3dx4 a4 = vec3dx4::load(a);
vec3dx4 b4 = vec3dx4::load(b);
CHECK(a4 == a4);
CHECK(a4 != b4);
vec3dx4 c4;
vec3d c[4];
c4 = a4 + b4;
for (int i = 0; i < 4; i++) {
c[i] = a[i] + b[i];
}
CHECK(c4 == vec3dx4::load(c));
c4 = a4 - b4;
for (int i = 0; i < 4; i++) {
c[i] = a[i] - b[i];
}
CHECK(c4 == vec3dx4::load(c));
c4 = a4 * b4;
for (int i = 0; i < 4; i++) {
c[i] = a[i] * b[i];
}
CHECK(c4 == vec3dx4::load(c));
c4 = a4 * 2.0;
for (int i = 0; i < 4; i++) {
c[i] = a[i] * 2.0;
}
CHECK(c4 == vec3dx4::load(c));
a4 += b4;
for (int i = 0; i < 4; i++) {
a[i] += b[i];
}
CHECK(a4 == vec3dx4::load(a));
a4 -= b4;
for (int i = 0; i < 4; i++) {
a[i] -= b[i];
}
CHECK(a4 == vec3dx4::load(a));
a4 *= b4;
for (int i = 0; i < 4; i++) {
a[i] *= b[i];
}
CHECK(a4 == vec3dx4::load(a));
c4 = aml::cross(a4, b4);
for (int i = 0; i < 4; i++) {
c[i] = aml::cross(a[i], b[i]);
}
CHECK(a4 == vec3dx4::load(a));
vec4d anormsq = aml::normsq(a4);
CHECK(anormsq.x == aml::normsq(a[0]));
CHECK(anormsq.y == aml::normsq(a[1]));
CHECK(anormsq.z == aml::normsq(a[2]));
CHECK(anormsq.w == aml::normsq(a[3]));
}
}
#undef ALTMATH_USE_SIMD
| true |
c4d727b7c3af68017c2b6869085c1111b7658c00 | C++ | Fedor-Sharygin/GAM550TechDemo | /Objects/Components/ParticleEmitter.h | UTF-8 | 1,303 | 2.703125 | 3 | [] | no_license | #pragma once
#ifndef _PARTICLE_H_
#define _PARTICLE_H_
#include "..//Component.h"
struct Particle
{
glm::vec3 position;
glm::vec3 velocity;
glm::vec4 color;
float lifeTime;
Particle()
:
position(glm::vec3(0.0f)), velocity(glm::vec3(0.0f)),
color(glm::vec4(0.0f)), lifeTime(-1.0f) /// negative, so that they are not alive
/// when they are first created
{};
};
class Shader;
class AssetManager;
class GraphicsManager;
class ParticleEmitter : public Component
{
public:
ParticleEmitter(unsigned int nAmount, unsigned int nSpawnRate, std::string nParticleTextureName);
~ParticleEmitter();
virtual void Update(float dt) override;
virtual void FrameStart() override;
virtual void FrameEnd() override;
virtual void Initialize() override;
virtual void End() override;
virtual void HandleEvent(Event* nEvent) override;
void Draw(Shader* pShader);
void PassLoader(AssetManager* nLoader);
public:
private:
unsigned int FirstUnusedParticle();
void RespawnParticle(Particle& cParticle);
private:
std::vector<Particle> particles;
unsigned int spawnRate;
unsigned int particleAmount;
AssetManager* loader;
unsigned int lastUsedParticle;
unsigned int particleVAO, particleVBO;
std::string particleTextureName;
unsigned int particleTexture;
};
#endif
| true |
11b0eda70b98cbd0aaf4bec6a39ee2e5de1ab6bb | C++ | hudovisk/Allegro | /Allegro/include/Vector.h | IBM852 | 644 | 3.09375 | 3 | [] | no_license | /*
* Vector.h
*
* Created on: 04/08/2013
* Author: Hudo Cim Asseno
* Author: Felipe Ukan Pereira
*/
#ifndef VECTOR_H_
#define VECTOR_H_
#include <cmath>
class Vector
{
public:
Vector(float xx, float yy) : x(xx), y(yy) { }
Vector() : x(0), y(0) { }
float getX() { return x; }
float getY() { return y; }
float getMagnitude() { return sqrt(x*x + y*y);}
float dotProdut(Vector v) { return x*v.getX() + y*v.getY(); }
Vector getInverse() { return Vector(-x,-y);}
Vector getNormalized()
{
float mag = getMagnitude();
return Vector(x/mag,y/mag);
}
private:
float x;
float y;
};
#endif /* VECTOR_H_ */
| true |
79d1d21d987e816b3e98562457e94220eba26214 | C++ | kapoorkhushal/CPP-Programs-Basic | /q10.cpp | UTF-8 | 828 | 3.796875 | 4 | [] | no_license | #include<iostream>
using namespace std;
class student
{
char* name;
int rollno;
int age;
float marks;
public:
student(){
name = NULL;
rollno = 0;
age = 0;
marks = 0;
}
void input();
void display();
};
void student :: input(){
name = new char[25];
cout<<"Enter Name : ";
fgets(name,25,stdin);
cout<<"Enter Roll No : ";
cin>>rollno;
cout<<"Enter Age : ";
cin>>age;
cout<<"Enter Marks : ";
cin>>marks;
getchar();
}
void student :: display(){
cout<<"Name : "<<name;
cout<<"Roll No : "<<rollno<<endl;
cout<<"Age : "<<age<<endl;
cout<<"Marks : "<<marks<<endl;
}
int main(void)
{
student s[3];
for(int i=0;i<3;i++)
{
cout<<"\nEnter Details for STUDENT-"<<i+1<<" ::\n";
s[i].input();
}cout<<endl;
for(int i=0;i<3;i++)
{
cout<<"\nDetails for STUDENT-"<<i+1<<" ::\n";
s[i].display();
}
}
| true |
1773b5b241483239e0de574dc7504e33a45edc6b | C++ | cup2of2tea/contests | /codeforces/355 Codeforces Round #206 (Div. 2)/355B.cpp | UTF-8 | 745 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int tot_cost(int cseul,int cmono,vector<int> &v)
{
int res=0;
for(int c=0;c<v.size();c++)
{
res+=min(cseul*v[c],cmono);
}
return res;
}
int main()
{
int s1=0;
int s2=0;
int N,M;
int c1,c2,c3,c4;
cin>>c1>>c2>>c3>>c4>>N>>M;
vector<int> bus(N),trolley(M);
for(int c=0;c<N;c++)
{
cin>>bus[c];
s1+=bus[c];
}
for(int c=0;c<M;c++)
{
cin>>trolley[c];
s2+=trolley[c];
}
int b=tot_cost(c1,c2,bus);
int t=tot_cost(c1,c2,trolley);
cerr<<b+t<<" "<<b+c3<<" "<<t+c3<<" "<<c4<<endl;
cout<<min(b+t,min(b+c3,min(t+c3,min(2*c3,c4))));
}
| true |
7ccfbfd2df55f02576c6665e0635e4d89d0a392a | C++ | attatrol/made_2019_2_algorithms | /5_6/main.cpp | UTF-8 | 8,137 | 3.578125 | 4 | [] | no_license | /**
* F. RMQ наоборот
*
* ввод rmq.in
* вывод rmq.out
*
* Рассмотрим массив a[1..n].
* Пусть Q(i, j) — ответ на запрос о нахождении минимума среди чисел a[i], ..., a[j].
* Вам даны несколько запросов и ответы на них.
* Восстановите исходный массив.
*
* Входные данные
* Первая строка входного файла содержит число n — размер массива, и m — число запросов (1 ≤ n, m ≤ 100 000).
* Следующие m строк содержат по три целых числа i, j и q, означающих, что Q(i, j) = q (1 ≤ i ≤ j ≤ n, - 231 ≤ q ≤ 231 - 1).
*
* Выходные данные
* Если искомого массива не существует, выведите строку «inconsistent».
* В противном случае в первую строку выходного файла выведите «consistent».
* Во вторую строку выходного файла выведите элементы массива.
* Элементами массива должны быть целые числа в интервале от - 231 до 231 - 1 включительно.
* Если решений несколько, выведите любое.
*/
/**
* C. RMQ2
*
* ввод стандартный ввод
* вывод стандартный вывод
*
* Входные данные
* В первой строке находится число n — размер массива. (1 ≤ n ≤ 10^5).
* Во второй строке находится n чисел ai — элементы массива.
* Далее содержится описание операций, их количество не превышает 2·10^5.
* В каждой строке находится одна из следующих операций:
* set i j x — установить все a[k], i ≤ k ≤ j в x.
* add i j x — увеличить все a[k], i ≤ k ≤ j на x.
* min i j — вывести значение минимального элемента в массиве на отрезке с i по j, гарантируется, что (1 ≤ i ≤ j ≤ n).
* Все числа во входном файле и результаты выполнения всех операций не превышают по модулю 10^18.
*
* Выходные данные
* Выведите последовательно результат выполнения всех операций min. Следуйте формату выходного файла из примера.
*
* Пример:
*
* Входные данные
* 5
* 1 2 3 4 5
* min 2 5
* min 1 5
* min 1 4
* min 2 4
* set 1 3 10
* add 2 4 4
* min 2 5
* min 1 5
* min 1 4
* min 2 4
*
* Выходные данные
* 2
* 1
* 1
* 2
* 5
* 5
* 8
* 8
*/
#define DEBUG
#include <algorithm>
#include <assert.h>
#include <cmath>
#include <fstream>
#ifdef DEBUG
#include <iostream>
#endif
#include <limits>
using value_t = int;
static const value_t MIN_NEUTRAL_ELEMENT = std::numeric_limits<value_t>::max();
struct TreeNode
{
value_t value;
value_t delayedValue;
bool set;
};
inline std::size_t getPow2Ceil(std::size_t n)
{
std::size_t result = 1;
while(result < n)
{
result <<= 1;
}
return result;
}
std::pair<TreeNode*, std::size_t> buildSegmentTree(const std::size_t dataSize)
{
std::size_t dataSizePow2 = getPow2Ceil(dataSize);
const std::size_t treeSize = dataSizePow2 * 2 - 1;
TreeNode* result = new TreeNode[treeSize];
for (std::size_t i = 0; i < dataSizePow2; ++i)
{
result[dataSizePow2 + i - 1].value = MIN_NEUTRAL_ELEMENT;
result[dataSizePow2 + i - 1].delayedValue = 0;
result[dataSizePow2 + i - 1].set = false;
}
return std::make_pair(result, treeSize);
}
value_t get(TreeNode* tree, std::size_t index, std::size_t l, std::size_t r)
{
assert(l <= r);
if (tree[index].set)
{
return tree[index].delayedValue;
}
else
{
return tree[index].delayedValue + tree[index].value;
}
}
void push(TreeNode* tree, std::size_t index, std::size_t l, std::size_t r)
{
assert(l <= r);
if (l == r)
{
if (tree[index].set)
{
tree[index].value = tree[index].delayedValue;
tree[index].set = false;
}
else
{
tree[index].value += tree[index].delayedValue;
}
tree[index].delayedValue = 0;
}
else
{
if (tree[index].set)
{
tree[2 * index + 1].delayedValue = tree[2 * index + 2].delayedValue = tree[index].delayedValue;
tree[2 * index + 1].set = tree[2 * index + 2].set = true;
}
else
{
tree[2 * index + 1].delayedValue += tree[index].delayedValue;
tree[2 * index + 2].delayedValue += tree[index].delayedValue;
}
std::size_t m = (l + r) / 2;
tree[index].delayedValue = 0;
tree[index].set = false;
tree[index].value = std::min(get(tree, 2 * index + 1, l, m), get(tree, 2 * index + 2, m + 1, r));
}
}
void update(TreeNode* tree, std::size_t index, std::size_t l, std::size_t r, std::size_t a, std::size_t b, value_t value, bool set)
{
assert(l <= r);
assert(a <= b);
if (tree[index].delayedValue || tree[index].set)
{
push(tree, index, l, r);
}
if (l > b || r < a)
{
return;
}
if (l >= a && r <= b)
{
tree[index].delayedValue = value;
tree[index].set = set;
return;
}
std::size_t m = (l + r) / 2;
update(tree, 2 * index + 1, l, m, a, b, value, set);
update(tree, 2 * index + 2, m + 1, r, a, b, value, set);
tree[index].value = std::min(get(tree, 2 * index + 1, l, m), get(tree, 2 * index + 2, m + 1, r));
}
value_t rmq(TreeNode* tree, const std::size_t size, std::size_t index, std::size_t l, std::size_t r, std::size_t a, std::size_t b)
{
assert(l <= r);
assert(a <= b);
assert(index < size);
if (tree[index].delayedValue || tree[index].set)
{
push(tree, index, l, r);
}
if (l > b || r < a) return MIN_NEUTRAL_ELEMENT;
if (l >= a && r <= b) return get(tree, index, l, r);
std::size_t m = (l + r) / 2;
return std::min(rmq(tree, size, 2 * index + 1, l, m, a, b), rmq(tree, size, 2 * index + 2, m + 1, r, a, b));
}
struct Query
{
std::size_t a;
std::size_t b;
value_t value;
};
int main()
{
#ifdef DEBUG
std::ifstream cin("input.txt");
using std::cout;
#else
std::ifstream cin("rmq.in");
std::ofstream cout("rmq.out");
#endif
std::size_t dataSize, opCount;
cin >> dataSize >> opCount;
auto[tree, treeSize] = buildSegmentTree(dataSize);
std::size_t rRoot = (treeSize + 1) / 2;
Query* queries = new Query[opCount];
for (std::size_t i = 0; i < opCount; ++i)
{
cin >> queries[i].a >> queries[i].b >> queries[i].value;
}
std::sort(queries, queries + opCount, [](const Query& q1, const Query& q2)
{
return q1.value < q2.value;
});
for (std::size_t i = 0; i < opCount; ++i)
{
update(tree, 0, 1, rRoot, queries[i].a, queries[i].b, queries[i].value, true);
}
bool consistent = true;
for (std::size_t i = 0; i < opCount; ++i)
{
if (queries[i].value != rmq(tree, treeSize, 0, 1, rRoot, queries[i].a, queries[i].b))
{
cout << "inconsistent";
consistent = false;
break;
}
}
if (consistent)
{
cout << "consistent\n";
for (std::size_t i = 1; i <= dataSize; ++i)
{
cout << rmq(tree, treeSize, 0, 1, rRoot, i, i) << ' ';
}
}
delete[] queries;
delete[] tree;
return 0;
}
| true |
d46fd003ad165cf7bf1927dc4bac6518d224db11 | C++ | TLMSONANA/CUGSECourses | /剑指offer/数组中只出现一次的数字.cpp | UTF-8 | 679 | 3.015625 | 3 | [] | no_license | class Solution {
public:
void FindNumsAppearOnce(vector<int> data,int* num1,int *num2) {
int n=0;
for(int i=0;i<data.size();i++){
n=n^data[i];
}
int index=findFirst1(n);
*num1=*num2=0;
for(int i=0;i<data.size();i++){
if(((data[i])>>index)&1){*num1=*num1^data[i];}
else{*num2=*num2^data[i];}
}
}
int findFirst1(int num){
int index=1;
while(index<8*sizeof(int)){
if(isBit1(num,index)){return index;}
index++;
}
return index;
}
bool isBit1(int num,int index){
num=num>>index;
return num&1;
}
}; | true |
aaa7c0a9baa97c446b49ff423a04f3f0f753df4c | C++ | Teolink/Cpp_L-Calculus_Compiler | /Compiler.cpp | UTF-8 | 3,746 | 3.234375 | 3 | [] | no_license | // Name: Theodoros Gatsos
// Record Number: 1115200200013
// Semester: 5th
// University of Athens
// Department of Informatics and Telecommunications
// Subject: Principles of Programming Languages
// February 2005
// Project: Implementation of a lambda calculus compiler
// File: Compiler.cpp
#include "Compiler.h"
#include "V_Table.h"
#include "S_Table.h"
#include <iostream>
#include <string>
#include <iterator>
using namespace std;
//------------------------ LEXICAL ANALYSIS FUNCTIONS --------------------------
static const string alphabetic = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const string symbol = "().\\";
static const string whitespace = " \n\t\f\v";
// Constructor
Compiler::Compiler(unsigned int max_s, bool verbose) : _maxSteps(max_s), _lexAnalyzed(false),
_verbose(verbose), _synAnalyzed(false), _expr(), _vTable(), _sTable(), _lambda(0) {}
// Destructor
Compiler::~Compiler() {
if(_lambda)
delete _lambda;
}
// Returns '_lexAnalyzed'
bool Compiler::is_lexed(void) { return _lexAnalyzed; }
// Returns '_synAnalyzed'
bool Compiler::is_syntaxed(void) { return _synAnalyzed; }
// This function gives an input to the compiler. If the compiler already worked with an input
// then this function resets the compiler's state before assigning the new input
void Compiler::input(const string &inp) {
_lexAnalyzed = false;
_synAnalyzed = false;
_expr = inp;
_sTable.clear();
_vTable.clear();
if(_lambda) {
delete _lambda;
_lambda = 0;
}
cout << "Compiler was given the input: " << _expr << endl;
return;
}
// This function provides lexical analysis to the input lambda expression 'expr'.
// The 'stab' matrix stores the lexical tokens of the input expression in the order that they were written.
// The 'vtab' matrix stores the names of the variables found in the input expression in alphabetic order.
void Compiler::lexical_analysis(void)
{
if(_lexAnalyzed) {
cerr << "Input expression was already lexically analyzed" << endl;
return;
}
const string checkstr = alphabetic + symbol + whitespace;
// Check the lambda term for illegal symbols
size_t res = _expr.find_first_not_of(checkstr);
if(res != string::npos) {
cerr << "Lexical analysis: Symbol \'" << _expr[res] << "\' is not allowed" << endl;
_lexAnalyzed = false;
return;
}
else { // Find the lexical tokens of the input expression 'expr' given.
Symbol token;
const size_t inp_size = _expr.size();
size_t p = 0;
while(p < inp_size) {
p = _expr.find_first_not_of(whitespace, p);// Ignore whitespaces
if(p == string::npos)
break; // End of input reached
else {
switch(_expr[p]) {
case '(':
token.type = LEFT_PAR;
token.name = "(";
++p;
break;
case ')':
token.type = RIGHT_PAR;
token.name = ")";
++p;
break;
case '\\':
token.type = LAMBDA;
token.name = "\\";
++p;
break;
case '.':
token.type = DOT;
token.name = ".";
++p;
break;
default:
// Lexical token corresponds to a variable
token.type = VARIABLE;
size_t q = _expr.find_first_not_of(alphabetic, p);
if(q == string::npos)
token.name = _expr.substr(p);
else
token.name = _expr.substr(p, q - p);
_vTable.insert(token.name);
p = q;
break;
}
} // end else
_sTable.insert(token); // This line gets executed in all cases but whitespaces and end of input
}// end while
}
_lexAnalyzed = true;
return;
}
// This function reduces the expression to it's normal form
void Compiler::find_normal(void) {
if(!_synAnalyzed) {
cerr << "Input expression is not syntactically analyzed yet" << endl;
return;
}
_lambda->normalize(_maxSteps, _vTable, _verbose);
return;
} | true |
2c65b1051b3b82c00afe7130ba0500e72744db33 | C++ | KwokShing/POJ | /1088.cpp | UTF-8 | 1,403 | 2.921875 | 3 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <cmath>
using namespace std;
int search(int x, int y, int **matrix, int **dp, const int &row, const int &col) {
if(dp[x][y] > 0)
return dp[x][y];
int val = 1;
if(x-1 >= 0 && matrix[x-1][y] < matrix[x][y])
val = max( search(x-1, y, matrix , dp, row, col)+1, val);
if(y-1 >= 0 && matrix[x][y-1] < matrix[x][y])
val = max( search(x, y-1, matrix , dp, row, col)+1, val);
if(x+1 < row && matrix[x+1][y] < matrix[x][y])
val = max( search(x+1, y, matrix , dp, row, col)+1, val);
if(y+1 < col && matrix[x][y+1] < matrix[x][y])
val = max( search(x, y+1, matrix, dp, row, col)+1, val);
dp[x][y] = val;
return val;
}
int main(int argc, const char * argv[]) {
int r = 0, c = 0;
cin>>r>>c;
int **matrix = new int*[r];
int **dp = new int*[r];
for(int i = 0; i < r; ++i) {
matrix[i] = new int[c];
dp[i] = new int[c];
}
for(int i = 0; i < r; ++i)
for(int j = 0; j < c; ++j) {
int height = 0;
cin>>height;
matrix[i][j] = height;
dp[i][j] = -1;
}
int res = 0;
for(int i = 0; i < r; ++i)
for(int j = 0; j < c; ++j) {
res = max(res, search(i, j, matrix, dp, r, c));
}
cout<<res;
return 0;
} | true |
79cf7c3d7851bae963e4b59a55075fc2151d765e | C++ | scratchingmycranium/programmingLangTranslators | /hw3.cpp | UTF-8 | 3,153 | 2.5625 | 3 | [] | no_license | //Adapted from: Hello.cpp - Example code from "Writing an LLVM Pass"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Function.h"
#include "llvm/Pass.h"
#include "llvm/IR/CallSite.h"
#include "llvm/Support/raw_ostream.h"
#include <iostream>
#include "llvm/IR/Module.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/IRBuilder.h"
using namespace llvm;
#define DEBUG_TYPE "hw3"
STATISTIC(Hw3Counter, "Counts number of functions greeted");
namespace {
// Hw3 - The first implementation, without getAnalysisUsage.
struct Hw3 : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
Hw3() : FunctionPass(ID) {}
bool runOnFunction(Function &F) override {
++Hw3Counter;
errs().write_escaped(F.getName()) << " ";
if(F.isVarArg()){
errs().write_escaped( "arguments= * ");
}else if(!F.arg_empty()){
errs().write_escaped( "arguments=");
errs().write_escaped(std::to_string(F.arg_size())) << " ";
}else{
errs().write_escaped( "arguments=0 ");
}
int callCounter = 0;
for (Function &Fun : F.getParent()->getFunctionList()){
for(BasicBlock &block: Fun){
for(Instruction &ins: block){
if (CallInst* callInst = dyn_cast<CallInst>(&ins)) {
if (callInst->getCalledFunction()->getName() == Fun.getName()){
}else{
}
}
}
for(Instruction &ins: block){
CallSite cs(&ins);
if(!cs.getInstruction()){
continue;
}
Value *called = cs.getCalledValue()->stripPointerCasts();
if(Function* f = dyn_cast<Function>(called)){
if(f->getName() == F.getName() ){
++callCounter;
}
}
}
}
}
errs().write_escaped("callsites=");
errs().write_escaped(std::to_string(callCounter)) << " ";
errs().write_escaped("basicblocks=");
errs().write_escaped(std::to_string((int) F.getBasicBlockList().size())) << " ";
if(!(F.getInstructionCount() <= 0)){
errs().write_escaped("instructions=");
errs().write_escaped(std::to_string(F.getInstructionCount()));
}
errs().write_escaped("")<< "\n";
return false;
}
};
}
char Hw3::ID = 0;
static RegisterPass<Hw3> X("hw3", "Hw3 Pass");
namespace {
// Hw32 - The second implementation with getAnalysisUsage implemented.
struct Hw32 : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
Hw32() : FunctionPass(ID) {}
bool runOnFunction(Function &F) override {
++Hw3Counter;
errs() << "Hw3: ";
errs().write_escaped(F.getName()) << '\n';
return false;
}
// We don't modify the program, so we preserve all analyses.
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
}
};
}
char Hw32::ID = 0;
static RegisterPass<Hw32>
Y("hw32", "Hw3 Pass (with getAnalysisUsage implemented)"); | true |
92762e574366435539908eea89ae7e9ea57f7ebf | C++ | pallas/liboco | /socket_address.h | UTF-8 | 1,092 | 3.140625 | 3 | [
"Zlib"
] | permissive | #ifndef SOCKET_ADDRESS_H
#define SOCKET_ADDRESS_H
#include <cstring>
#include <sys/socket.h>
class socket_address {
public:
virtual sockaddr & cast() = 0;
virtual const sockaddr & cast() const = 0;
virtual socklen_t length() const = 0;
int protocol() const;
int family() const;
bool is_inet() const;
bool is_inet6() const;
bool is_local() const;
};
template <int AF, typename SA>
class basic_socket_address : public socket_address {
public:
basic_socket_address() {
memset(&sa, 0, sizeof sa);
cast().sa_family = AF;
}
sockaddr & cast() {
return reinterpret_cast<sockaddr &>(sa);
}
const sockaddr & cast() const {
return reinterpret_cast<const sockaddr &>(sa);
}
socklen_t length() const { return sizeof sa; }
protected:
SA sa;
static const int af = AF;
};
class any_address : public basic_socket_address<AF_UNSPEC,sockaddr_storage> {
public:
any_address();
any_address(const socket_address &);
any_address(const struct sockaddr *, socklen_t);
any_address & operator=(const socket_address &);
};
#endif//SOCKET_ADDRESS_H
| true |
3dc2f465e589570c69bab321ff1b0f9fa4a2f003 | C++ | Schwaigs/Planning_optimisation | /src/Population.cpp | UTF-8 | 3,975 | 2.90625 | 3 | [] | no_license | #include "Population.h"
using namespace std;
// initialisation d'une population de solutions
Population::Population(int tp, int tc)
{
taille_pop = tp;
individus = new Chromosome*[taille_pop];
for (int i=0; i<taille_pop; i++)
individus[i] = new Chromosome(tc);
ordre = new int[taille_pop];
}
// destruction de l'objet "Population"
Population::~Population()
{
for (int i=0; i<taille_pop; i++)
delete individus[i];
delete individus;
delete ordre;
}
// statistiques sur la population
void Population::statistiques()
{
double moyenne = 0;
double ecart_type = 0;
for (int i=0; i<taille_pop; i++)
{
moyenne += individus[i]->fitness;
ecart_type += individus[i]->fitness*individus[i]->fitness;
}
moyenne = moyenne / taille_pop;
ecart_type = sqrt(ecart_type/taille_pop - moyenne*moyenne);
cout << "fitness : (moyenne, ecart_type) -> ("
<< moyenne << " , " << ecart_type << ")" << endl;
cout << "fitness : [meilleure, mediane, pire] -> ["
<< individus[ordre[0]]->fitness << " , "
<< individus[ordre[(int)(taille_pop/2)]]->fitness << " , "
<< individus[ordre[taille_pop-1]]->fitness << "]" << endl;
}
// Ordonne les individus de la population par ordre croissant de fitness
void Population::ordonner()
{
int inter;
for(int i=0; i<taille_pop; i++)
ordre[i]=i;
for(int i=0; i<taille_pop-1; i++)
for(int j=i+1; j<taille_pop; j++)
if(individus[ordre[i]]->fitness > individus[ordre[j]]->fitness)
{
inter = ordre[i];
ordre[i] = ordre[j];
ordre[j] = inter;
}
}
// R�-ordonne le classement des individus de la population par ordre croissant de fitness
// apr�s un petit changement
void Population::reordonner()
{
int inter;
for(int i=0; i<taille_pop-1; i++)
for(int j=i+1; j<taille_pop; j++)
if(individus[ordre[i]]->fitness > individus[ordre[j]]->fitness)
{
inter = ordre[i];
ordre[i] = ordre[j];
ordre[j] = inter;
}
}
// SELECTION PAR TOURNOI
//op�rateur de s�lection bas� sur la fonction fitness
Chromosome* Population::selection_tournoi()
{
int n = taille_pop/10; //nombre d'individus tirés
Chromosome* chromosomeFitnessMin;
int index_indiv; //index de l'individu tiré
Chromosome* individusTires[n];
//tirage de n individus
for(int i = 0; i<n; i++){
do
{
index_indiv = (rand()%taille_pop-2)+1;
} while (index_indiv==-1 && in_list(index_indiv, individusTires, n));
individusTires[i] = individus[index_indiv];
}
chromosomeFitnessMin = individusTires[0];
for(int i=0; i<n; i++){
if(individusTires[i]->fitness < chromosomeFitnessMin->fitness){
chromosomeFitnessMin = individusTires[i];
}
}
return chromosomeFitnessMin;
}
int Population::in_list(int index, Chromosome** individusTires, int taille){
if(index<0){
return 1;
}
for(int i = 0; i<taille; i++){
if (individus[index] == individusTires[i]){
return 1;
}
}
return 0;
}
void Population::remplacement_tournoi(Chromosome* individu){
int n = taille_pop/10; //nombre d'individus tirés
Chromosome* chromosomeFitnessMax;
int index_indiv; //index de l'individu tiré
int index_max=-1;
Chromosome* individusTires[n];
//tirage de n individus
for(int i = 0; i<n; i++){
do
{
index_indiv = (rand()%taille_pop-2)+1;
} while (index_indiv==-1 && in_list(index_indiv, individusTires, n));
if (index_max==-1)
{
index_max=index_indiv;
}else if(individus[index_max]->fitness<individus[index_indiv]->fitness){
index_max = index_indiv;
}
}
individus[index_max]->copier(individu);
individus[index_max]->fitness = individu->fitness;
individus[index_max]->majTempsTravailInterface();
}
| true |
e6870963590c52093a12005eb5e6634645ba6a6b | C++ | xiaogang00/Leetcode | /C++/Word_Ladder.cpp | UTF-8 | 1,637 | 3.03125 | 3 | [] | no_license | //
// Created by Theo on 2017/9/20.
//
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
int dis=1;
int len=wordList.size();
int *visit=new int[len];
memset(visit,0,len*sizeof(int));
queue<string> q;
for (int i=0; i<len; i++)
{
if (cmpStr(beginWord, wordList[i])==true)
{
if (wordList[i] == endWord) return 2;
q.push(wordList[i]);
visit[i]=1;
}
}
if (q.empty()) return 0;
dis++;
while (!q.empty())
{
int _siz=q.size();
while (_siz)
{
string tmp(q.front());
if (tmp == endWord) return dis;
for (int i=0; i<len; i++)
{
if (!visit[i])
{
if (cmpStr(tmp, wordList[i]))
{
if (wordList[i] == endWord) return dis+1;
q.push(wordList[i]);
visit[i]=1;
}
}
}
q.pop();
_siz--;
}
dis++;
}
return 0;
}
bool cmpStr(string s1, string s2)
{
int len=s1.size();
int diff=0;
for (int i=0; i<len; i++)
{
if (s1[i] != s2[i])
{
diff++;
}
}
if (diff == 1) return true;
else return false;
}
}; | true |
0a37678ad2b89d00b5ea0216a753d75937608fe5 | C++ | edd3173/BOJ | /BOJ15651.cpp | UTF-8 | 545 | 2.671875 | 3 | [] | no_license | #pragma warning(disable:4996)
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <algorithm>
using namespace std;
int N, M;
bool visited[10] = { false, };
int arr[10] = { 0,1,2,3,4,5,6,7,8,9 };
void Solve(int cnt) {
if (cnt == M) {
for (int i = 0; i < M; i++)
printf("%d ", arr[i]);
}
for (int i = 1; i < N; i++) {
if (visited[i]) continue;
visited[i] = true; arr[cnt] = i;
Solve(cnt + 1);
visited[i] = false;
}
}
int main() {
scanf("%d %d", &N, &M);
Solve(0);
} | true |
4fb328d8892835762d76f9b733c36f63758e82cf | C++ | victorursan/Contest_CPP | /Contest_CPP/Controller.cpp | UTF-8 | 3,727 | 3.3125 | 3 | [] | no_license | //
// Controller.cpp
// Contest_CPP
//
// Created by Victor Ursan on 4/2/15.
// Copyright (c) 2015 Victor Ursan. All rights reserved.
//
#include "Controller.h"
Controller::Controller(AbstractRepository<Participant>* repo) {
/* Initializes Controller
*/
this->repository = repo;
}
Controller::~Controller() {
/* Destroy Controller
*/
// delete &repository;
// delete this;
}
vector<Participant> Controller::getParticipants(){
/* Get all the participants
returns: all the participants
*/
return repository->getAll();
}
void Controller::addParticipant(string givenName, string familyName, float score) throw (MyException) {
/* Add a participant
param: givenName - a string with a given name
param: familyName - a string with a family name
param: score - a float with the score
*/
Participant p(givenName, familyName, score);
UndoParticipant undo = UndoParticipant(repository->size(), 1, p);
undo_participants.push_back(undo);
repository->save(p);
}
void Controller::updateParticipant(int id, string givenName, string familyName, float score) throw(MyException) {
/* Update a participant
param: id - the position of the participant
param: givenName - a string with a given name
param: familyName - a string with a family name
param: score - a float with the score
*/
Participant p(givenName, familyName, score);
UndoParticipant undo = UndoParticipant(id, 3, p);
undo_participants.push_back(undo);
repository->update(id, p);
}
void Controller::removeParticipant(int id) throw(MyException) {
/* Remove a participant
param: id - the position from where to remove
*/
Participant p = repository->findById(id);
UndoParticipant undo = UndoParticipant(id, 2, p);
undo_participants.push_back(undo);
repository->remove(id);
}
vector<Participant> Controller::filterByGivenName(string givenName) {
/* Filter participants by given name
param: givenName - the name for which to filter
returns: a filtered vector
*/
vector<Participant> toFilter = repository->getAll();
vector<Participant> filtered;
for (vector<Participant>::iterator p = toFilter.begin(); p != toFilter.end(); ++p) {
if (p->getGivenName() == givenName) {
filtered.push_back(*p);
}
}
return filtered;
}
vector<Participant> Controller::filterByFamilyName(string familyName) {
/* Filter participants by family name
param: familyName - the name for which to filter
returns: a filtered vector
*/
vector<Participant> toFilter = repository->getAll();
vector<Participant> filtered;
for (vector<Participant>::iterator p = toFilter.begin(); p != toFilter.end(); ++p) {
if (p->getFamilyName() == familyName) {
filtered.push_back(*p);
}
}
return filtered;
}
vector<Participant> Controller::filterByScore(float score) {
/* Filter participants by score
param: score - the score for which to filter
returns: a filtered vector
*/
vector<Participant> toFilter = repository->getAll();
vector<Participant> filtered;
for (vector<Participant>::iterator p = toFilter.begin(); p != toFilter.end(); ++p) {
if (p->getScore() == score) {
filtered.push_back(*p);
}
}
return filtered;
}
void Controller::undoLastOperation() {
/* Undo last operation
*/
UndoParticipant undo = undo_participants.back();
int op = undo.getOperation();
switch (op) {
case 1:
repository->remove(undo.getPosition());
break;
case 2:
repository->insertAtPosition(undo.getPosition(), undo.getParticipant());
break;
case 3:
repository->update(undo.getPosition(), undo.getParticipant());
break;
default:
break;
}
undo_participants.pop_back();
} | true |
c50f8d6c2e88d5b1e6ecb035cdd84c2bcdcaffd5 | C++ | pemayfes2020/drone-pc | /testsuite/main/thread_test.cpp | UTF-8 | 1,351 | 3.296875 | 3 | [] | no_license | #include "safe_exit.hpp"
#include <chrono>
#include <iostream>
#include <thread>
// コンストラクタとデストラクタが呼ばれることを確認するだけのクラス
class A
{
public:
A()
{
std::cout << "constructor" << std::endl;
}
~A()
{
std::cout << "destructor" << std::endl;
}
};
void work()
{
// スレッド内でenterする
ThreadRoom::enter();
try {
// 寿命を適切に管理したい変数をtry節中で宣言する
A a;
while (!ThreadRoom::toExit()) {
auto start = std::chrono::system_clock::now();
while (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start).count() < 1000) {
}
std::cout << "hello" << std::endl;
}
} catch (ThreadRoom::thread_abort) {
// toExit() が例外を投げるので、try節中の変数の寿命を断ったのちexitする(残りスレッド数を1減らす)
ThreadRoom::exit();
return;
}
return;
}
int main()
{
ThreadRoom::setExitHandler();
std::thread{work}.detach();
std::thread{work}.detach();
std::thread{work}.join();
// 無限ループが走るので、Ctrl+CでSIGINTを与えると正常にdestructorが3回呼ばれて落ちる
return 0;
}
| true |
260d76870904c47051001ae38f25833151d0ddf6 | C++ | chenchukun/UNP | /muduo/net/eventLoop.cpp | UTF-8 | 2,092 | 2.859375 | 3 | [] | no_license | //
// Created by chenchukun on 18/3/28.
//
#include <muduo/net/EventLoopThread.h>
#include <muduo/net/EventLoopThreadPool.h>
#include <muduo/net/EventLoop.h>
#include <muduo/base/ThreadLocal.h>
#include <muduo/net/TcpServer.h>
#include <muduo/net/InetAddress.h>
#include <iostream>
#include <string>
using namespace muduo::net;
using namespace muduo;
using namespace std;
namespace testEventLoopThread
{
// 线程本地数据
ThreadLocal<string> id;
TcpServer *server;
void initCallback(EventLoop *loop)
{
id.value() = "EventLoopThread";
cout << id.value() << " Init" << endl;
InetAddress addr(6180);
server = new TcpServer(loop, addr, "testEventLoopThread");
server->setMessageCallback([] (const TcpConnectionPtr &conn, Buffer *buff, Timestamp timestamp) {
conn->send(buff);
buff->retrieveAll();
});
server->start();
}
void test()
{
id.value() = "MainThread";
cout << id.value() << " Init" << endl;
// EventLoopThread 创建一个运行事件循环的线程,可以传递一个初始化回调函数,
// 该函数在子线程执行EventLoop.loop()前执行
EventLoopThread eventLoopThread(initCallback, "test");
EventLoop *loop = eventLoopThread.startLoop();
string s;
while (cin >> s) {
cout << s << endl;
}
loop->quit();
delete server;
cout << id.value() << " Exit" << endl;
}
}
namespace testEventLoopThreadPool
{
void initCallback(EventLoop *loop)
{
cout << CurrentThread::name() << " init" << endl;
}
void test()
{
EventLoop loop;
// EventLoopThreadPool创建一个线程池,每个线程执行一个事件循环
EventLoopThreadPool eventLoopThreadPool(&loop, "EventLoopThread");
eventLoopThreadPool.setThreadNum(4);
eventLoopThreadPool.start(initCallback);
loop.loop();
}
}
int main()
{
// testEventLoopThread::test();
testEventLoopThreadPool::test();
return 0;
}
| true |
712be8752ef7be8ef499971b80b07b8250fb5f14 | C++ | bakkiraju/sharpenskills | /Dynamic Programming/LCS.cpp | UTF-8 | 848 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int LCSHelper(string X, string Y, int m, int n, unordered_map<string, int> &cache)
{
if (m == 0 || n == 0) return 0;
string key = to_string(m)+'|'+to_string(n);
if (cache.find(key) != cache.end())
{
return cache[key];
}
else
{
if (X[m - 1] == Y[n - 1])
{
cache[key] = LCSHelper(X, Y, m - 1, n - 1, cache) + 1;
}
else
{
cache[key] = max(LCSHelper(X, Y,m-1, n, cache), LCSHelper(X, Y, m, n-1, cache));
}
}
return cache[key];
}
int LCS(string X, string Y)
{
unordered_map<string, int> cache;
return LCSHelper(X, Y, X.length(), Y.length(), cache);
}
int main()
{
string X = "ABCBDAB", Y = "BDCABA";
cout << LCS(X, Y) << endl;
} | true |
f3f51569532c6905e1f289766e29f50e0685b4dd | C++ | lmalano/informaticaC | /suma y multiplicacion de matrices.cpp | UTF-8 | 2,467 | 3.453125 | 3 | [] | no_license | #include <iostream>
using namespace std;
const int dim=20;
void cargar_matriz (int [dim][dim], int, int);
void mostrar_matriz (int [dim][dim], int, int);
void sumar (int [dim][dim], int [dim][dim], int, int);
void multiplicar (int [dim][dim], int [dim][dim], int , int, int );
void ordenar (int [dim][dim], int, int);
void mostrar_lista (int [dim], int);
int main (){
int filasA, columA, filasB, columB;
cout << "Ingrese numero de filas y luego de columnas de la matriz 1:"<< endl;
int A[dim][dim];
cin >> filasA >> columA;
cargar_matriz (A, filasA, columA);
cout << endl;
cout << "Ingrese numero de filas y luego de columas de la matriz 2:"<< endl;
int B[dim][dim];
cin >> filasB >> columB;
cargar_matriz (B, filasB, columB);
cout << endl;
if ((filasA == filasB) && (columA == columB)){
cout << "Se sumaran las matrices" << endl;
sumar (A, B, filasA, columA);
}
else
cout << "Las matrices no se pueden sumar" << endl;
cout << endl;
if ((columA == filasB)){
cout << "Se multiplicaran las matrices" << endl;
multiplicar (A, B, filasA, columB, columB);
}
else
cout << "Las matrices no se pueden multiplicar" << endl;
cout << endl;
system ("pause");
return 0;
}
void cargar_matriz (int val[dim][dim], int filas, int colum){
int a,b;
cout << "Comienze a ingresar los elementos" << endl;
for (a=0; a<filas; a++)
for (b=0; b<colum; b++)
cin >> val[a][b];
mostrar_matriz(val, filas, colum);
}
void mostrar_matriz (int matriz[dim][dim], int filas, int colum){
int a,b;
cout << "La matriz es:" << endl;
for (a=0; a<filas; a++){
for (b=0; b<colum; b++){
cout << matriz [a][b] << " ";
}
cout << endl;
}
}
void sumar (int A[dim][dim], int B[dim][dim], int filas, int colum){
int a,b, suma[dim][dim];
for (a=0; a<filas; a++){
for (b=0; b<colum; b++){
suma [a][b] = A[a][b] + B[a][b];
}
}
mostrar_matriz (suma, filas, colum);
}
void multiplicar (int A[dim][dim], int B[dim][dim], int filas, int colum, int control){
int a,b,c, C[dim][dim];
for (a=0; a<filas; a++){
for (b=0; b<colum; b++){
C[a][b]=0;
for (c=0; c<control; c++){
C[a][b] = C[a][b] + A[a][c] * B[c][b];
}
}
}
mostrar_matriz (C, filas, colum);
}
| true |
36d5678fb7bf6ef87139a69f376b3bf9c681f289 | C++ | AlexWuDDD/TDDCPP | /src/c5/1/PlaceDescriptionServiceTest.cpp | UTF-8 | 1,602 | 2.875 | 3 | [] | no_license | #include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "Http.h"
#include "PlaceDescriptionService.h"
using namespace testing;
class APlaceDescriptionServiceTest : public Test
{
public:
static std::string ValidLatitude;
static std::string ValidLongtitude;
};
std::string APlaceDescriptionServiceTest::ValidLatitude = "1";
std::string APlaceDescriptionServiceTest::ValidLongtitude = "2";
class HttpStub : public Http
{
public:
HttpStub(){}
~HttpStub(){}
void initialize() override {}
std::string returnResponse;
std::string expectedURL;
std::string get(const std::string& url) const override
{
verify(url);
return returnResponse;
}
void verify(const std::string& url) const
{
ASSERT_THAT(url, Eq(expectedURL));
}
};
TEST_F(APlaceDescriptionServiceTest, ReturnsDescriptionForValidLocation)
{
HttpStub httpStub;
httpStub.returnResponse = R"({
"address":{
"road": "Drury Ln",
"city": "Fountain",
"state": "CO",
"country": "US"
}
})";
std::string urlStart{
"http://open.mapquestapi.com/nominatim/v1/reverse?format=json&"};
httpStub.expectedURL = urlStart +
"lat=" + APlaceDescriptionServiceTest::ValidLatitude + "&" +
"lon=" + APlaceDescriptionServiceTest::ValidLongtitude;
PlaceDescriptionService service{&httpStub};
auto description = service.summaryDescription(ValidLatitude, ValidLongtitude);
ASSERT_THAT(description, Eq("Drury Ln, Fountain, CO, US"));
} | true |
1e203eb5d7a7e2bc7e1278ac92c03b6d62dd42d4 | C++ | apreak/CharSetTool | /ICharSet.h | GB18030 | 703 | 3.25 | 3 | [] | no_license | #pragma once
#include <string>
class ICharSet
{
public:
// ȡַַָ
virtual void Read(const char *pstr) = 0;
// ַַָ
virtual void Write(char *pstr) = 0;
// ĬϸʽָǰC++ʹõĸʽ
// ȡĬϸʽַ
void ReadNative(const std::wstring &wstr);
// Ĭϸʽַ
void WriteNative(std::wstring &wstr);
// խַת
static std::string ws2s(const std::wstring &ws);
static std::wstring s2ws(const std::string &s);
protected:
std::wstring wsNative;
};
// һʹ÷ʽ
// 1Read -> WriteNative
// 2ReadNative -> Write
| true |
a6d9711f9c6e0c2c67a4a36b091aa2745790baea | C++ | sujeet05/CLRS-Algorithms | /Graphs/StronglyConnectedComponent.cpp | UTF-8 | 10,912 | 2.859375 | 3 | [] | no_license | #include<iostream>
#include<list>
#include<vector>
#include<queue>
#include<algorithm>
#define PARENT 99999
using namespace std;
enum color
{
W=0,
G,
B
};
class vertix
{
private:
int m_name;
vertix* m_parent;
color m_clr;
int m_stime;
int m_etime;
public:
vertix(int _name,vertix* _parent=NULL ,color _clr=W,int _stime=0,int _etime=0):m_name(_name),m_parent(_parent),m_clr(_clr),m_stime(_stime),m_etime(_etime){}
vertix(const vertix& _v):m_name(_v.m_name),m_parent(NULL),m_clr(W){}
int m_getvertixName() {return m_name;}
vertix* m_getvertixParent() {return m_parent;}
color m_getvertixcolor() {return m_clr;}
void set_vertixParent(vertix* _v) {m_parent = _v;}
void set_vertixcolor(color clr) {m_clr =clr;}
void setstarttime(int x) {m_stime=x;}
void setendtime(int x) {m_etime=x;}
int getstarttime() {return m_stime;}
int getendtime() {return m_etime;}
};
struct
{
bool operator()(vertix *a, vertix *b)
{
return a->getendtime() < b->getendtime();
}
} customLess;
class Graph
{
public:
Graph(vector<vertix*>& _v,list<vertix> *_e=NULL,int time=0);
void m_AddEdge(vertix &x,vertix &y);
void m_Init();
void m_InitDFS();
void m_InitTopo();
void m_Initscc();
void m_printEdges();
void m_printTransposeEdge();
void BFS(vertix& src);
void BuildDFS();
void DFS(vertix& src);
void printPath(vertix &src,vertix &dest);
void Topologicalsort();
void SetTransposedEdges();
void SetSCCEdges();
vertix* findMappedTransposedVertix(vertix &_v);
void DFSTransposedGraph(vertix& src);
void BuildDFSTransposeGraph();
void printOrderSCCVertices();
void printSCCEdges();
private:
vector<vertix*> m_vertices;
vector<vertix*> m_sccVertices;
list<vertix*> * m_edges;
list<vertix*> m_topoorder;
list<vertix*> *m_transposededges;
list<vertix*> *m_sccdedges;
int time;
};
void Graph::printOrderSCCVertices()
{
for(int i=0;i<m_sccVertices.size();++i)
cout << m_sccVertices[i]->m_getvertixName() << "...."<< m_sccVertices[i]->m_getvertixcolor() << "..."<< m_sccVertices[i]->m_getvertixParent() << endl;
}
vertix* Graph::findMappedTransposedVertix(vertix &_v)
{
for(int i=0;i< m_sccVertices.size();++i)
{
if(_v.m_getvertixName()==(*m_sccVertices[i]).m_getvertixName())
return m_sccVertices[i];
}
return NULL;
}
Graph::Graph(vector<vertix*>& _v,list<vertix> *_e,int time):m_vertices(_v)
{
m_edges = new list<vertix*>[m_vertices.size()];
m_transposededges = new list<vertix*>[m_vertices.size()];
m_sccdedges = new list<vertix*>[m_vertices.size()];
m_Initscc();
}
void Graph::SetTransposedEdges()
{
for(int i=0;i<m_vertices.size();i++)
for(list<vertix*>::iterator j = m_edges[i].begin(); j != m_edges[i].end(); j++)
m_transposededges[(*j)->m_getvertixName()-1].push_back(m_vertices[i]);
}
void Graph::SetSCCEdges()
{
for(int i=0;i<m_vertices.size();i++)
for(list<vertix*>::iterator j = m_edges[i].begin(); j != m_edges[i].end(); j++)
m_sccdedges[(*j)->m_getvertixName()-1].push_back(findMappedTransposedVertix(*m_vertices[i]));
}
void Graph::m_printEdges()
{
for(int i=0;i<m_vertices.size();i++)
for(list<vertix*>::iterator j = m_edges[i].begin(); j != m_edges[i].end(); j++)
cout << (*m_vertices[i]).m_getvertixName() << "..."<< (*j)->m_getvertixName() << "..color.." << (*j)->m_getvertixcolor() << endl;
}
void Graph::printSCCEdges()
{
for(int i=0;i<m_sccVertices.size();i++)
for(list<vertix*>::iterator j = m_sccdedges[i].begin(); j != m_sccdedges[i].end(); j++)
cout << (*m_sccVertices[i]).m_getvertixName() << "..."<< (*j)->m_getvertixName() << "..color.." << (*j)->m_getvertixcolor() << endl;
}
void Graph::m_printTransposeEdge()
{
for(int i=0;i<m_vertices.size();i++)
for(list<vertix*>::iterator j = m_transposededges[i].begin(); j != m_transposededges[i].end(); j++)
cout << (*m_vertices[i]).m_getvertixName() << "..."<< (*j)->m_getvertixName() << "..color.." << (*j)->m_getvertixcolor() << endl;
}
void Graph::m_AddEdge(vertix &x,vertix &y)
{
m_edges[x.m_getvertixName()-1].push_back(&y);
}
void Graph::m_InitTopo()
{
m_AddEdge(*m_vertices[0],*m_vertices[1]);
m_AddEdge(*m_vertices[0],*m_vertices[7]);
m_AddEdge(*m_vertices[1],*m_vertices[2]);
m_AddEdge(*m_vertices[1],*m_vertices[7]);
m_AddEdge(*m_vertices[2],*m_vertices[5]);
m_AddEdge(*m_vertices[3],*m_vertices[2]);
m_AddEdge(*m_vertices[3],*m_vertices[4]);
m_AddEdge(*m_vertices[4],*m_vertices[4]);
m_AddEdge(*m_vertices[6],*m_vertices[7]);
}
void Graph::m_Initscc()
{
m_AddEdge(*m_vertices[0],*m_vertices[1]);
m_AddEdge(*m_vertices[1],*m_vertices[2]);
m_AddEdge(*m_vertices[1],*m_vertices[4]);
m_AddEdge(*m_vertices[1],*m_vertices[5]);
m_AddEdge(*m_vertices[2],*m_vertices[3]);
m_AddEdge(*m_vertices[2],*m_vertices[6]);
m_AddEdge(*m_vertices[3],*m_vertices[2]);
m_AddEdge(*m_vertices[3],*m_vertices[7]);
m_AddEdge(*m_vertices[4],*m_vertices[0]);
m_AddEdge(*m_vertices[4],*m_vertices[5]);
m_AddEdge(*m_vertices[5],*m_vertices[6]);
m_AddEdge(*m_vertices[6],*m_vertices[5]);
m_AddEdge(*m_vertices[6],*m_vertices[7]);
m_AddEdge(*m_vertices[7],*m_vertices[7]);
}
void Graph::m_InitDFS()
{
m_AddEdge(*m_vertices[0],*m_vertices[1]);
m_AddEdge(*m_vertices[0],*m_vertices[4]);
m_AddEdge(*m_vertices[1],*m_vertices[2]);
m_AddEdge(*m_vertices[1],*m_vertices[4]);
m_AddEdge(*m_vertices[2],*m_vertices[3]);
m_AddEdge(*m_vertices[3],*m_vertices[1]);
m_AddEdge(*m_vertices[4],*m_vertices[3]);
m_AddEdge(*m_vertices[5],*m_vertices[0]);
m_AddEdge(*m_vertices[5],*m_vertices[4]);
m_AddEdge(*m_vertices[6],*m_vertices[5]);
m_AddEdge(*m_vertices[6],*m_vertices[7]);
m_AddEdge(*m_vertices[7],*m_vertices[6]);
m_AddEdge(*m_vertices[7],*m_vertices[5]);
}
void Graph::m_Init()
{
m_AddEdge(*m_vertices[0],*m_vertices[1]);
m_AddEdge(*m_vertices[0],*m_vertices[3]);
m_AddEdge(*m_vertices[1],*m_vertices[4]);
m_AddEdge(*m_vertices[2],*m_vertices[4]);
m_AddEdge(*m_vertices[2],*m_vertices[5]);
m_AddEdge(*m_vertices[3],*m_vertices[1]);
m_AddEdge(*m_vertices[4],*m_vertices[2]);
m_AddEdge(*m_vertices[5],*m_vertices[5]);
}
void Graph::DFS(vertix& src)
{
time = time+1;
src.setstarttime(time);
src.set_vertixcolor(G);
for(list<vertix*>::iterator j = m_edges[src.m_getvertixName()-1].begin(); j != m_edges[src.m_getvertixName()-1].end(); j++)
{
if((*j)->m_getvertixcolor() ==W)
{
(*j)->set_vertixParent(&src);
DFS(**j);
}
}
src.set_vertixcolor(B);
time = time+1;
src.setendtime(time);
vertix *v = new vertix(src);
m_sccVertices.push_back(v);
m_topoorder.push_front(&src);
}
void Graph::DFSTransposedGraph(vertix& src)
{
cout << src.m_getvertixName() << "...";
src.set_vertixcolor(G);
for(list<vertix*>::iterator j = m_sccdedges[src.m_getvertixName()-1].begin(); j != m_sccdedges[src.m_getvertixName()-1].end(); j++)
{
if((*j)->m_getvertixcolor() ==W)
{
(*j)->set_vertixParent(&src);
DFSTransposedGraph(**j);
}
}
src.set_vertixcolor(B);
}
void Graph::Topologicalsort()
{
BuildDFS();
for(list<vertix*>::iterator j = m_topoorder.begin(); j != m_topoorder.end(); j++)
cout << (*j)->m_getvertixName() << "....";
}
void Graph::BuildDFSTransposeGraph()
{
for(int i=0;i < m_sccVertices.size() ;++i)
{
(*m_sccVertices[i]).set_vertixcolor(W);
(*m_sccVertices[i]).set_vertixParent(NULL);
}
// sorti
// cout << "Before sort of vertices.." << endl;
// printOrderSCCVertices();
// cout << endl;
// std::sort(m_sccVertices.begin(), m_sccVertices.end(), customLess);
// printOrderSCCVertices();
for(int i= m_sccVertices.size()-1;i >=0 ;--i)
if((*m_sccVertices[i]).m_getvertixcolor() ==W)
{
cout << endl;
DFSTransposedGraph(*(m_sccVertices[i]));
}
}
void Graph::BuildDFS()
{
time =0;
for(int i=0;i < m_vertices.size() ;++i)
{
(*m_vertices[i]).set_vertixcolor(W);
(*m_vertices[i]).set_vertixParent(NULL);
}
for(int i=0;i < m_vertices.size() ;++i)
if((*m_vertices[i]).m_getvertixcolor() ==W)
DFS(*(m_vertices[i]));
SetSCCEdges();
BuildDFSTransposeGraph();
}
void Graph::BFS(vertix& src)
{
for(int i=0;i < m_vertices.size() ;++i)
{
(*m_vertices[i]).set_vertixcolor(W);
(*m_vertices[i]).set_vertixParent(NULL);
}
src.set_vertixParent(NULL);
src.set_vertixcolor(G);
queue<vertix*> q;
q.push(&src);
cout << endl;
while(!q.empty())
{
vertix *v = q.front();
q.pop();
for(list<vertix*>::iterator j = m_edges[v->m_getvertixName()-1].begin(); j != m_edges[v->m_getvertixName()-1].end(); j++)
{
if((*j)->m_getvertixcolor() ==W)
{
(*j)->set_vertixcolor(G);
(*j)->set_vertixParent(&(*v));
q.push(&(**j));
}
}
v->set_vertixcolor(B);
}
}
void Graph::printPath(vertix &src,vertix &dest)
{
if(src.m_getvertixName()==dest.m_getvertixName())
cout << src.m_getvertixName();
else if (dest.m_getvertixParent() == NULL)
cout << "No path from src to dest exist" << endl;
else
{ printPath(src,*(dest.m_getvertixParent()));
cout << dest.m_getvertixName();
}
}
int main()
{
cout << "BFS DEMONSTRATION......................." << endl;
#if 0
vertix v1(1),v2(2),v3(3),v4(4),v5(5),v6(6);
vector<vertix* > v;
v.push_back(&v1);
v.push_back(&v2);
v.push_back(&v3);
v.push_back(&v4);
v.push_back(&v5);
v.push_back(&v6);
Graph G(v);
G.BFS(*v[0]);
G.m_printEdges();
cout << endl;
G.printPath(*v[0],*v[5]);
cout << endl;
G.printPath(*v[0],*v[4]);
cout << endl;
#endif
cout << "DFS DEMONSTRATION......................." << endl;
#if 0
vertix D1(1),D2(2),D3(3),D4(4),D5(5),D6(6),D7(7),D8(8);
vector<vertix* > d;
d.push_back(&D1);
d.push_back(&D2);
d.push_back(&D3);
d.push_back(&D4);
d.push_back(&D5);
d.push_back(&D6);
d.push_back(&D7);
d.push_back(&D8);
Graph G1(d);
G1.BuildDFS();
G1.printPath(*d[0],*d[3]);
cout << endl;
G1.printPath(*d[0],*d[4]);
cout << endl;
G1.printPath(*d[6],*d[5]);
cout << endl;
#endif
cout << "Topological DEMONSTRATION......................." << endl;
#if 0
vertix T1(1),T2(2),T3(3),T4(4),T5(5),T6(6),T7(7),T8(8),T9(9);
vector<vertix*> t;
t.push_back(&T1);
t.push_back(&T2);
t.push_back(&T3);
t.push_back(&T4);
t.push_back(&T5);
t.push_back(&T6);
t.push_back(&T7);
t.push_back(&T8);
t.push_back(&T9);
Graph G1(t);
G1.Topologicalsort();
#endif
cout << "Strongly Connected Components...." << endl;
vertix scc1(1),scc2(2),scc3(3),scc4(4),scc5(5),scc6(6),scc7(7),scc8(8);
vector<vertix* > d;
d.push_back(&scc1);
d.push_back(&scc2);
d.push_back(&scc3);
d.push_back(&scc4);
d.push_back(&scc5);
d.push_back(&scc6);
d.push_back(&scc7);
d.push_back(&scc8);
Graph G1(d);
G1.BuildDFS();
// G1.printOrderSCCVertices();
#if 0
G1.printSCCEdges();
G1.m_printEdges();
cout << endl;
G1.SetTransposedEdges();
G1.m_printTransposeEdge();
G1.printOrderSCCVertices();
cout << endl;
G1.SetSCCEdges();
G1.printSCCEdges();
#endif
return 0;
}
| true |
6401dece1e68c3514b13a81d25945a4e3c7ea828 | C++ | Akaflieg/startkladde | /src/util/environment.cpp | UTF-8 | 755 | 2.625 | 3 | [] | no_license | /*
* environment.cpp
*
* Created on: 14.07.2010
* Author: Martin Herrmann
*/
#include "environment.h"
#include <cstdlib>
#include "src/i18n/notr.h"
/**
* Gets the contents of an environment variable
*
* @param name the name of the environment variable
* @return the contents of the environment variable
*/
QString getEnvironmentVariable (const QString &name)
{
char *r=getenv (name.toUtf8 ().constData ());
if (r)
return QString (r);
else
return QString ();
}
QStringList getSystemPath (const QString &environmentVariable)
{
#if defined (Q_OS_WIN32) || defined (Q_OS_WIN64)
return getEnvironmentVariable (environmentVariable).split (notr (";"));
#else
return getEnvironmentVariable (environmentVariable).split (notr (":"));
#endif
}
| true |
421c5163e0b50070659420647bc1319ac0edbbb9 | C++ | waveform/leetcode | /algo/cpp/reverse_integer.cc | UTF-8 | 1,162 | 2.984375 | 3 | [] | no_license | class Solution {
public:
// handle as string
/*
int reverse(int x) {
string in = to_string(x);
string minimal = to_string(INT_MIN).substr(1), maximal = to_string(INT_MAX);
bool negative = false;
if (in[0]=='-') {
negative = true;
in = in.substr(1);
}
//reverse(begin(in), end(in));
//reverse(in.begin(), in.end());
int l = 0, r = in.size() - 1;
while(l<r) swap(in[l++], in[r--]);
if (negative) {
if (in.size()>=minimal.size() && in > minimal) return 0;
return -stoi(in);
} else {
if (in.size()>=maximal.size() && in > maximal) return 0;
return stoi(in);
}
return 0;
}
*/
// handle as number
int reverse(int x) {
long long xx = x, tt = 0;
bool negative = (xx < 0);
xx = llabs(xx);
while (xx) {
tt*=10;
tt += xx%10;
xx /= 10;
}
if (negative) {
tt*=-1;
if (tt < INT_MIN) return 0;
} else if (tt > INT_MAX) return 0;
return tt;
}
};
| true |
b193d149630643e3d7653d3e10a956f43b759225 | C++ | MilaBits/Direct2D-Game-Engine-Framework | /SimpleGame/Utils.cpp | UTF-8 | 2,024 | 3.015625 | 3 | [] | no_license | #include "Utils.h"
#include <cstdio>
#include <corecrt_malloc.h>
#include <cmath>
#include <iostream>
#define DATA_OFFSET_OFFSET 0x000A
#define WIDTH_OFFSET 0x0012
#define HEIGHT_OFFSET 0x0016
#define BITS_PER_PIXEL_OFFSET 0x001C
#define HEADER_SIZE 14
#define INFO_HEADER_SIZE 40
#define NO_COMPRESION 0
#define MAX_NUMBER_OF_COLORS 0
#define ALL_COLORS_REQUIRED 0
int Utils::Clamp(int min, int val, int max)
{
if (val < min) return min;
if (val > max) return max;
return val;
}
bool Utils::GetGridTileValue(vector<vector<int>> grid, int xPos, int yPos, int* value)
{
if (xPos < 0 || xPos >= grid[0].size() ||
yPos < 0 || yPos >= grid.size())
{ // out of bounds, return -1
*value = -1;
return false;
}
*value = grid[yPos][xPos];
return true;
}
void Utils::ReadImage(const char* fileName, unsigned int** pixels, unsigned int* width, unsigned int* height, unsigned int* bytesPerPixel)
{
// Get file
FILE* imageFile = fopen(fileName, "rb");
// Get Pixel Data Offset
unsigned int dataOffset;
fseek(imageFile, DATA_OFFSET_OFFSET, SEEK_SET);
fread(&dataOffset, 4, 1, imageFile);
// Get image width and height
fseek(imageFile, WIDTH_OFFSET, SEEK_SET);
fread(width, 4, 1, imageFile);
fseek(imageFile, HEIGHT_OFFSET, SEEK_SET);
fread(height, 4, 1, imageFile);
// Get bits per pixel
short bitsPerPixel;
fseek(imageFile, BITS_PER_PIXEL_OFFSET, SEEK_SET);
fread(&bitsPerPixel, 2, 1, imageFile);
*bytesPerPixel = ((unsigned int)bitsPerPixel) / 8;
// Read pixel data
int totalSize = *width * *height * (int)*bytesPerPixel;
*pixels = (unsigned int*)malloc(totalSize);
for (int parsedBytes = 0; parsedBytes < totalSize; parsedBytes += (int)bytesPerPixel)
{
unsigned int pixelOffset = dataOffset + parsedBytes;
fseek(imageFile, dataOffset + parsedBytes, SEEK_SET);
fread(*pixels + parsedBytes, 1, (int)bytesPerPixel, imageFile);
}
// Clean up
fclose(imageFile);
} | true |
d1d073248981b6fee2276ce2c87e2f57b6ad1833 | C++ | samanseifi/Tahoe | /toolbox/src/C1functions/ErrorFunc.cpp | UTF-8 | 4,924 | 2.953125 | 3 | [
"BSD-3-Clause"
] | permissive | /* $Id: ErrorFunc.cpp,v 1.8 2011/12/01 20:25:15 bcyansfn Exp $ */
#include "ErrorFunc.h"
#include <cmath>
#include <iostream>
#include "ExceptionT.h"
#include "dArrayT.h"
#include "Gamma.h"
using namespace Tahoe;
const int ITMAX = 100;
const double EPS = 3.0e-7;
const double FPMIN = 1.0e-30;
/*
* constructors
*/
ErrorFunc::ErrorFunc()
{
}
/*
* destructors
*/
ErrorFunc::~ErrorFunc()
{
}
/*
* methods
*/
double gammp(double a, double p);
void gcf(double *gammcf, double a, double x, double *gln);
void gser(double *gamser, double a, double x, double *gln);
/*
* I/O
*/
void ErrorFunc::Print(ostream& out) const
{
/* parameters */
out << " No Scaling constant. . . . . . . . . . . . . . . ." << '\n';
}
void ErrorFunc::PrintName(ostream& out) const
{
out << " Error Function\n";
}
/*
* Returning values
*/
double ErrorFunc::Function(double x) const
{
return (x < 0.0 ? -gammp(0.5,x*x) : gammp(0.5,x*x));
}
double ErrorFunc::DFunction(double x) const
{
cout << "\n Derivative of the Error Function not provided!\n";
throw ExceptionT::kBadInputValue;
return 0.0*x; // to avoid generating warning messages
}
double ErrorFunc::DDFunction(double x) const
{
cout << "\n Second derivative of the Error Function not provided!\n";
throw ExceptionT::kBadInputValue;
return 0.0*x; // to avoid generating warning messages
}
/*
* Returning values in groups - derived classes should define
* their own non-virtual function called within this functon
* which maps in to out w/o requiring a virtual function call
* everytime. Default behavior is just to map the virtual functions
* above.
*/
dArrayT& ErrorFunc::MapFunction(const dArrayT& in, dArrayT& out) const
{
/* dimension checks */
if (in.Length() != out.Length()) throw ExceptionT::kGeneralFail;
const double* pl = in.Pointer();
double* pU = out.Pointer();
for (int i = 0; i < in.Length(); i++)
{
double r = *pl++;
*pU++ = (r < 0.0 ? -gammp(0.5,r*r) : gammp(0.5,r*r));
}
return out;
}
dArrayT& ErrorFunc::MapDFunction(const dArrayT& in, dArrayT& out) const
{
/* dimension checks */
if (in.Length() != out.Length()) throw ExceptionT::kGeneralFail;
const double* pl = in.Pointer();
double* pdU = out.Pointer();
cout << "\n Derivative of the Bessel Function of the 3rd Kind not tabulated!\n";
for (int i = 0; i < in.Length(); i++)
{
// double r = *pl++;
*pl++;
*pdU++ = 0.0;
}
return out;
}
dArrayT& ErrorFunc::MapDDFunction(const dArrayT& in, dArrayT& out) const
{
/* dimension checks */
if (in.Length() != out.Length()) throw ExceptionT::kGeneralFail;
const double* pl = in.Pointer();
double* pddU = out.Pointer();
cout << "\n Second derivative of the Bessel Function of the 3rd Kind not tabulated!\n";
for (int i = 0; i < in.Length(); i++)
{
// double r = *pl++;
*pl++;
*pddU++ = 0.0;
}
return out;
}
// Taken from "Numerical Recipes in C", pg. 218-219. This returns the incomplete
// gamma function, P(a,x), evaluated by its series representation.
// Also returns log(Gamma(a)) as gln.
void ErrorFunc::gser(double *gamser, double a, double x, double *gln) const
{
Gamma gammnln;
double sum, del, ap;
*gln = log(gammnln.Function(a));
if (x <= 0.0)
{
if (x < 0.0)
{
cout << "\n*** x less than 0 in method gser.\n";
throw ExceptionT::kBadInputValue;
}
*gamser = 0.0;
return;
}
else
{
ap = a;
del = sum = 1.0/a;
for (int n=1; n<=ITMAX; n++)
{
++ap;
del *= x/ap;
sum += del;
if (fabs(del) < fabs(sum)*EPS)
{
*gamser = sum*exp(-x+a*log(x)-(*gln));
return;
}
}
cout << "\n*** a too large, ITMAX too small in method gser.\n";
throw ExceptionT::kBadInputValue;
}
}
// Taken from "Numerical Recipes in C", pg. 219. This returns the incomplete
// gamma function, Q(a,x), evaluated by its continued fraction representation.
// Also returns log(Gamma(a)) as gln.
void ErrorFunc::gcf(double *gammcf, double a, double x, double *gln) const
{
Gamma gammnln;
int i;
double an, b, c, d, del, h;
*gln = log(gammnln.Function(a));
b = x+1.0-a;
c = 1.0/FPMIN;
d = 1.0/b;
h = d;
for (i=1; i<=ITMAX; i++)
{
an = -i*(i-a);
b += 2.0;
d = an*d+b;
if (fabs(d) < FPMIN)
d = FPMIN;
c = b+an/c;
if (fabs(c) < FPMIN)
c = FPMIN;
d = 1.0/d;
del = d*c;
h *= del;
if (fabs(del-1.0) < EPS)
break;
}
if (i > ITMAX)
{
cout << "\n*** a too large, ITMAX too small in method gcf.\n";
throw ExceptionT::kBadInputValue;
}
*gammcf = exp(-x+a*log(x)-(*gln))*h;
}
// Taken from "Numerical Recipes in C", pg. 218. This returns the incomplete
// gamma function, P(a,x).
double ErrorFunc::gammp(double a, double x) const
{
double gamser, gammcf, gln;
if (x < 0.0 || a <= 0.0)
{
cout << "\n*** Invalid arguments in method gammp.\n";
throw ExceptionT::kBadInputValue;
}
if (x < (a+1.0))
{
gser(&gamser,a,x,&gln);
return gamser;
}
else
{
gcf(&gammcf,a,x,&gln);
return 1.0-gammcf;
}
}
| true |
b96b1fb4019ee88faf2d94491dc71d1d9b0b5430 | C++ | DanielRourke/DataStructure | /DataStructure/Assignment1-mapBased/SmartPlayer.h | UTF-8 | 924 | 2.921875 | 3 | [] | no_license | #pragma once
#include "Player.h"
class SmartPlayer :
public Player
{
public:
SmartPlayer() : Player() {};
SmartPlayer(int i, string name = "Smart Player") : Player(i, name) {};
~SmartPlayer() {};
Move getMove(Board & board)
{
priority_queue<Move, vector<Move>, less<vector<Move>::value_type>> bestMove;
list<Move> rMoves = board.getRemainingMoves();
for (Move move : rMoves)
{
move.printMove();
}
for (Move move : rMoves)
{
Board tempBoard(board);
tempBoard.getNeighbours(move);
move.sortTargets();
move.pickTargets(id);
tempBoard.addMove(move, id);
if (tempBoard.isboardFull())
{
if (id == 0)
{
move.utility = tempBoard.getHuristicScore() * 1.0;
}
else if (id == 1)
{
move.utility = tempBoard.getHuristicScore() * -1.0;
}
}
move.utility += move.targetTotal() * 0.01;
bestMove.push(move);
}
return bestMove.top();
}
}; | true |
7ef06bbc57f5aecf8998b792a84f986cd77b642c | C++ | DeepikaNarayanaswamy/cg | /timer.cpp | UTF-8 | 1,282 | 2.515625 | 3 | [] | no_license | #include<GL/glut.h>
#include<iostream>
using namespace std;
int x[4]= {100,200,100,200};
int y[4]= {100,200,200,100};
float trans[3][3]= {{0.5,0,0},{0,1,0},{0,0,1}};
int x1=100,x2=100,y1=100,y2=200,count=0;
void myinit()
{
glClearColor(1.0,1.0,1.0,1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glPointSize(1);
gluOrtho2D(-512.0,512.0,-512.0,512.0);
}
void translate(int w)
{
int i,j,k;
int p[3][1],p1[3][1];
//sleep(1);
if (count > 2 )
{
trans[0][0]=1.5; trans[1][1]=1;
}
else if (count > 4)
{
trans[0][0]=0.5;
count=0;
}
for (i=0;i<4;i++)
{
p[0][0]=x[i];
p[1][0]=y[i];
p[2][0]=1;
for (j=0;j<3;j++)
{
p1[j][0]=0;
for (k=0;k<3;k++)
{
p1[j][0]+=trans[j][k]*p[k][0];
}
}
x[i]=p1[0][0];
y[i]=p1[1][0];
}
count++;
}
void mydisplay()
{
int i;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,0.0,0.0);
glBegin(GL_POLYGON);
for (i=0;i<4;i++)
glVertex2d(x[i],y[i]);
glEnd();
sleep(1);
//count++;
translate(1);
glutPostRedisplay();
glFlush();
}
int main(int argc, char**argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(512,512);
glutCreateWindow("TRANSFORM");
glutDisplayFunc(mydisplay);
glutTimerFunc(1000,translate,1);
myinit();
glutMainLoop();
return 0;
}
| true |
6e8546978a8619f70b265f29193e12a09460f9a2 | C++ | arjkashyap/competitive-coding | /code arena/rgb.cpp | UTF-8 | 1,410 | 2.875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
void Display(int *a, int n){
for( int i = 0; i < n; i++ ) printf("%d ", a[i]);
printf("\n");
}
void InputRGB(int *a, int interval, int time){
for(int i = interval; i < time; i+= interval){
int index = 0;
while(index < interval){
a[i] = 1;
i++;
index++;
}
}
}
int main(){
int t, r, g, b;
scanf("%d %d %d %d", &t, &r, &g, &b);
int red[t] = {0}, green[t] = {0}, blue[t] = {0};
InputRGB(red, r, t);
InputRGB(green, g, t);
InputRGB(blue, b, t);
int R = 0, G = 0, B = 0, Y = 0, C = 0, M = 0, W = 0, Black = 0;
for( int i = 0; i < t; i++ ){
if( red[i] == 0 && blue[i] == 0 && green[i] == 0 )
Black += 1;
else if( red[i] == 1 && green[i] == 0 && blue[i] == 0)
R++;
else if(red[i] == 0 && green[i] == 1 && blue[i] == 0)
G++;
else if(red[i] == 0 && green[i] == 0 && blue[i] == 1)
B++;
else if(red[i] == 1 && green[i] == 1 && blue[i] == 0)
Y++;
else if(red[i] == 0 && green[i] == 1 && blue[i] == 1)
C++;
else if(red[i] == 1 && green[i] == 0 && blue[i] == 1)
M++;
else if( red[i] == 1 && green[i] == 1&& blue[i] == 1 )
W++;
}
printf("%d %d %d %d %d %d %d %d\n", R, G, B, Y, C, M, W, Black);
}
| true |
9d2aed111b6760a5b0f5360f7295585c75066e3d | C++ | etremel/pddm | /src/messaging/AggregationMessage.h | UTF-8 | 7,804 | 2.71875 | 3 | [] | no_license | /*
* AggregationMessage.h
*
* Created on: May 18, 2016
* Author: edward
*/
#pragma once
#include <cstddef>
#include <memory>
#include <iterator>
#include <ostream>
#include <unordered_map>
#include <vector>
#include <mutils-serialization/SerializationSupport.hpp>
#include "../FixedPoint_t.h"
#include "../util/Hash.h"
#include "Message.h"
#include "MessageType.h"
#include "MessageBody.h"
#include "MessageBodyType.h"
namespace pddm {
namespace messaging {
/** Decorates std::vector<FixedPoint_t> with the MessageBody type so it can be the payload of a Message. */
class AggregationMessageValue : public MessageBody {
private:
std::vector<FixedPoint_t> data;
public:
static const constexpr MessageBodyType type = MessageBodyType::AGGREGATION_VALUE;
template<typename... A>
AggregationMessageValue(A&&... args) : data(std::forward<A>(args)...) {}
AggregationMessageValue(const AggregationMessageValue&) = default;
AggregationMessageValue(AggregationMessageValue&&) = default;
virtual ~AggregationMessageValue() = default;
operator std::vector<FixedPoint_t>() const { return data; }
operator std::vector<FixedPoint_t>&() { return data; }
//Boilerplate copy-and-pasting of the entire interface of std::vector follows
decltype(data)::size_type size() const noexcept { return data.size(); }
template<typename... A>
void resize(A&&... args) { return data.resize(std::forward<A>(args)...); }
template<typename... A>
void emplace_back(A&&... args) { return data.emplace_back(std::forward<A>(args)...); }
decltype(data)::iterator begin() { return data.begin(); }
decltype(data)::const_iterator begin() const { return data.begin(); }
decltype(data)::iterator end() { return data.end(); }
decltype(data)::const_iterator end() const { return data.end(); }
decltype(data)::const_iterator cbegin() const { return data.cbegin(); }
decltype(data)::const_iterator cend() const { return data.cend(); }
bool empty() const noexcept { return data.empty(); }
void clear() noexcept { data.clear(); }
decltype(data)::reference at(decltype(data)::size_type i) { return data.at(i); }
decltype(data)::const_reference at(decltype(data)::size_type i) const { return data.at(i); }
decltype(data)::reference operator[](decltype(data)::size_type i) { return data[i]; }
decltype(data)::const_reference operator[](decltype(data)::size_type i) const { return data[i]; }
template<typename A>
AggregationMessageValue& operator=(A&& other) {
data.operator=(std::forward<A>(other));
return *this;
}
//An argument of type AggregationMessageValue won't forward to std::vector::operator=
AggregationMessageValue& operator=(const AggregationMessageValue& other) {
data = other.data;
return *this;
}
//This is the only method that differs from std::vector<FixedPoint_t>
inline bool operator==(const MessageBody& _rhs) const {
if (auto* rhs = dynamic_cast<const AggregationMessageValue*>(&_rhs))
return this->data == rhs->data;
else return false;
}
//Forward the serialization methods to the already-implemented ones for std::vector
std::size_t bytes_size() const {
return mutils::bytes_size(type) + mutils::bytes_size(data);
}
std::size_t to_bytes(char* buffer) const {
std::size_t bytes_written = mutils::to_bytes(type, buffer);
return bytes_written + mutils::to_bytes(data, buffer + bytes_written);
}
void post_object(const std::function<void (char const * const,std::size_t)>& f) const {
mutils::post_object(f, type);
mutils::post_object(f, data);
}
static std::unique_ptr<AggregationMessageValue> from_bytes(mutils::DeserializationManager<>* m, char const* buffer) {
/*"Skip past the MessageBodyType, then take the deserialized vector
* and wrap it in a new AggregationMessageValue"*/
return std::make_unique<AggregationMessageValue>(
*mutils::from_bytes<std::vector<FixedPoint_t>>(m, buffer + sizeof(type)));
}
};
std::ostream& operator<<(std::ostream& out, const AggregationMessageValue& v);
/**
* The messages sent in the Aggregate phase of all versions of the protocol.
* They carry the query result (or its intermediate value) and the count of
* data points that contributed to the result. Query results are always vectors
* of FixedPoint_t.
*/
class AggregationMessage: public Message {
private:
int num_contributors;
public:
static const constexpr MessageType type = MessageType::AGGREGATION;
using body_type = AggregationMessageValue;
int query_num;
AggregationMessage() : Message(0, nullptr), num_contributors(0), query_num(0) {}
AggregationMessage(const int sender_id, const int query_num, std::shared_ptr<AggregationMessageValue> value) :
Message(sender_id, value), num_contributors(1), query_num(query_num) {}
virtual ~AggregationMessage() = default;
std::shared_ptr<body_type> get_body() { return std::static_pointer_cast<body_type>(body); };
const std::shared_ptr<body_type> get_body() const { return std::static_pointer_cast<body_type>(body); };
void add_value(const FixedPoint_t& value, int num_contributors);
void add_values(const std::vector<FixedPoint_t>& values, const int num_contributors);
int get_num_contributors() const { return num_contributors; }
std::size_t bytes_size() const;
std::size_t to_bytes(char* buffer) const;
void post_object(const std::function<void (char const * const,std::size_t)>&) const;
static std::unique_ptr<AggregationMessage> from_bytes(mutils::DeserializationManager<> *p, const char* buffer);
friend bool operator==(const AggregationMessage& lhs, const AggregationMessage& rhs);
friend struct std::hash<AggregationMessage>;
private:
//All-member constructor used only be deserialization
AggregationMessage(const int sender_id, const int query_num,
std::shared_ptr<AggregationMessageValue> value, const int num_contributors) :
Message(sender_id, value), num_contributors(num_contributors), query_num(query_num) {}
};
bool operator==(const AggregationMessage& lhs, const AggregationMessage& rhs);
bool operator!=(const AggregationMessage& lhs, const AggregationMessage& rhs);
std::ostream& operator<<(std::ostream& out, const AggregationMessage& m);
} /* namespace messaging */
} /* namespace pddm */
namespace std {
template<>
struct hash<pddm::messaging::AggregationMessageValue> {
size_t operator()(const pddm::messaging::AggregationMessageValue& input) const {
std::size_t seed = input.size();
//Convert the FixedPoints to their base integral type, since we just want the bits
for (pddm::FixedPoint_t::base_type i : input) {
seed ^= i + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
};
template<>
struct hash<pddm::messaging::AggregationMessage> {
size_t operator()(const pddm::messaging::AggregationMessage& input) const {
using pddm::util::hash_combine;
size_t result = 1;
hash_combine(result, input.num_contributors);
hash_combine(result, input.query_num);
hash_combine(result, *std::static_pointer_cast<pddm::messaging::AggregationMessageValue>(input.body));
return result;
}
};
} // namespace std
| true |
86657dd674190d0f485c7f0f105f5376569f3aaf | C++ | sjzlyl406/Practice | /test81.cpp | UTF-8 | 1,342 | 3.34375 | 3 | [
"LicenseRef-scancode-boost-original"
] | permissive | /*************************************************************************
> File Name: test81.cpp
> Author: leon
> Mail: sjzlyl406@163.com
> Created Time: 2015年07月16日 星期四 20时43分10秒
************************************************************************/
/*******************************************************************
* Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
* For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1,
* 2, 3, 4]. Return its length: 4.
* Your algorithm should run in O(n) complexity.
* ******************************************************************/
#include<iostream>
#include<vector>
#include<unordered_set>
int foo(const std::vector<int> &vec)
{
std::unordered_set<int> arraySet;
int ret = 0;
for(size_t i = 0; i < vec.size(); ++i) {
arraySet.insert(vec[i]);
}
for(size_t i = 0; i < vec.size(); ++i) {
int curLen = 1;
int tmp = vec[i];
while(arraySet.find(--tmp) != arraySet.end()) ++curLen;
tmp = vec[i];
while(arraySet.find(++tmp) != arraySet.end()) curLen++;
if(curLen > ret) ret = curLen;
}
return ret;
}
int main(void)
{
int num;
std::vector<int> vec;
while(std::cin >> num) {
vec.push_back(num);
}
std::cout<< "Length:" << foo(vec) << std::endl;
return 0;
}
| true |
7db644a5f477ddfb11e50f88e122aa939fe9e2ab | C++ | tick7tock7/Object-oriented-C-- | /ContactList/Contact.h | WINDOWS-1251 | 656 | 3.109375 | 3 | [] | no_license | /*
* Contact.h
*/
#ifndef CONTACT_H
#define CONTACT_H
#include <iostream> // << >>
using namespace std;
class Contact
{
friend istream& operator >> (istream& a, Contact& e);
friend ostream& operator << (ostream& a, const Contact& e);
public:
//
Contact();
//
const char* getName() const; //
private:
char name[20]; // (20 )
char phoneNumber[20]; // (20 )
char address[20]; // (20 )
};
#endif | true |
b223682d00bdbeb7165da90667ef16f66fcd67ab | C++ | denthos/heliocentric | /Heliocentric/Client/orbital_camera.cpp | UTF-8 | 2,466 | 2.78125 | 3 | [] | no_license | #include "orbital_camera.h"
#include <glm\gtc\matrix_transform.hpp>
#define RESET_KEY "ResetKey"
inline int toLower(int c) {
return c >= 97 && c <= 122 ? c - 32 : c;
}
OrbitalCamera::OrbitalCamera(KeyboardHandler & keyboardHandler, MouseHandler & mouseHandler, const std::vector<GameObject *> & selection) : selection(selection) {
loadSettings(keyboardHandler);
mouseHandler.registerMouseCursorHandler(std::bind(&OrbitalCamera::handleCursorInput, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
mouseHandler.registerMouseWheelHandler(std::bind(&OrbitalCamera::handleWheelInput, this, std::placeholders::_1));
}
void OrbitalCamera::update() {
if (!active) return;
if (selection.size() == 1) {
glm::vec3 oldTarget = this->target;
this->target = selection[0]->get_position();
glm::vec3 translate = this->target - oldTarget;
this->position += translate;
}
}
void OrbitalCamera::loadSettings(KeyboardHandler & keyboardHandler, Lib::INIParser & config) {
resetKey = toLower((int)config.get<std::string>(RESET_KEY)[0]);
keyboardHandler.registerKeyDownHandler(resetKey, std::bind(&OrbitalCamera::handleReset, this, std::placeholders::_1));
// load other settings
this->speed = config.get<float>(CAMERA_SPEED_KEY);
this->sensitivity = config.get<float>(CAMERA_SENSITIVITY_KEY);
}
void OrbitalCamera::handleCursorInput(const MouseButtonMap & mouseButtons, ScreenPosition currPosition, ScreenPosition lastPosition) {
if (!active) return;
if (mouseButtons.at(MouseButton(GLFW_MOUSE_BUTTON_RIGHT, GLFW_MOD_NONE)).down) {
glm::vec3 camFocus = position - target;
glm::vec3 right = glm::cross(up, glm::normalize(camFocus));
float angle = (lastPosition.second - currPosition.second) / -100.0f;
position = glm::vec3(glm::vec4(camFocus, 1.0f) * glm::rotate(glm::mat4(1.0f), angle, right)) + target;
camFocus = position - target;
angle = (lastPosition.first - currPosition.first) / -100.0f;
position = glm::vec3(glm::vec4(camFocus, 1.0f) * glm::rotate(glm::mat4(1.0f), angle, up)) + target;
}
}
void OrbitalCamera::handleWheelInput(ScreenPosition input) {
if (!active) return;
glm::vec3 translate = (target - position) * this->speed * input.second * 0.01f;
this->position += translate;
}
void OrbitalCamera::handleReset(int key) {
if (!active) return;
if (key == resetKey) {
this->target = glm::vec3(0.0f);
this->position = glm::vec3(0.0f, 0.0f, 250.0f);
this->up = glm::vec3(0.0f, 1.0f, 0.0f);
}
} | true |
6bf108096224e8b1a57389bf19faa69e26fcb84e | C++ | nazirdilshad/CodingProblems | /codeforces/1353/C.cpp | UTF-8 | 456 | 2.65625 | 3 | [] | no_license | #include <iostream>
using namespace std;
void solve()
{
long long n;
cin >> n;
long long sum = 1, i = 1, cnt = 0;
if (n == 1)
{
cout << 0 << endl;
return;
}
else
{
while (sum != n * n)
{
cnt += (i * i) * 8;
sum += (8 * i);
i++;
}
}
cout << cnt << endl;
}
int main()
{
int t;
cin >> t;
while (t--)
{
solve();
}
} | true |
b1fe5f23a79c5dc320400f327b5dd250e50830a8 | C++ | shuanglengyunji/Mp3Player | /Interface/Mp3Player/mainwindow.cpp | UTF-8 | 2,009 | 2.75 | 3 | [] | no_license | #include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint); //窗口总在最前+取消关闭按钮
setWindowFlags(windowFlags() | Qt::CustomizeWindowHint); //允许自定义标题栏
setWindowFlags(windowFlags() & ~Qt::WindowMinimizeButtonHint //取消最大、最小、关闭按钮
& ~Qt::WindowMaximizeButtonHint
& ~Qt::WindowCloseButtonHint
);
////////////////////////////////////////////////////////////////////////////////////
//运行程序时自动开始播放音乐
/*1.获取音乐目录absDir*/
runPath = QCoreApplication::applicationDirPath(); //获取当前exe所在路径
absDir = runPath;
//检测命令行参数
QStringList arguments = QCoreApplication::arguments();
qDebug() << "The whole Arguments: " << arguments << endl;
//生成文件目录
if(arguments.count() < 2) //这个参数至少也是1,程序会自动传入一个参数,内容是程序所在目录地址
{
absDir = absDir + "/musics/1.mp3"; //没有传入参数,使用默认参数
}
else
{
absDir = absDir + "/musics/" + arguments.at(1); //使用传入音乐名称作为参数
}
qDebug() << "Path:" << absDir << endl; //显示文件目录
ui->Text->setText(absDir);
/*2.创建QMediaPlayer对象指针,通过指针设置文件路径、音量、播放*/
musicPlayer.setMedia(QUrl::fromLocalFile(absDir));
musicPlayer.setVolume(80);
musicPlayer.play();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
qDebug() << musicPlayer.state();
int tmp_state = musicPlayer.state();
if(tmp_state != 0)
musicPlayer.stop();
//关闭程序
this->close();
}
| true |
cf840e0e075bba0d25d22f56b5a96b07081f0734 | C++ | wenyi214/Qusetion-bank | /Trie .cpp | GB18030 | 3,098 | 4.03125 | 4 | [] | no_license | ֻDZǰַͬǰͬγһµķ֧
ʼmapͷڵ
ǰ
ַ
Ҫõңmap棬keyΪַvalueΪ㡣keyַvalueͬһַַ
ַʱͬǰõͬĽ㡣
ҪһisEndǷߵַβ
㣺
ȱ浱ǰĽ㣬mapжӦַsecondΪգ˵ûиַ½ڵ㣬ӣߵһ㡣
isEndΪtrue
void insert(string word) {
//浱ǰ
Trie *head = this;
for (auto ch : word){
//Ϊգ˵ûйַ
if (head->m[ch] == nullptr){
//һַһµmapheadָһ㣬mapֻһַ
//Կظġ
head->m[ch] = new Trie();
}
//ߵһ
head = head->m[ch];
}
head->isEnd = true;
}
ң
浱ǰ㣬mapҶӦַvalueǷΪգΪ˵ûиַ
ߵҪҵַжǷʱisEndǷΪβ
bool search(string word) {
//ǰ
Trie *head = this;
for (auto ch : word){
//Ϊ˵ûиַ
if (head->m[ch] == nullptr){
return false;
}
//
head = head->m[ch];
}
//жǷ
return head->isEnd;
}
ǰ
bool startsWith(string prefix) {
//浱ǰ
Trie *head = this;
for (auto ch : prefix){
//Ϊգ˵ûиַfalse
if (head->m[ch] == nullptr){
return false;
}
//ߵϴһ
head = head->m[ch];
}
//˵иǰ
return true;
}
ȫ룺
class Trie {
private:
unordered_map<char, Trie*> m;//ַÿһַÿһַһTrieǰͬԹͬ
bool isEnd = false;//ַǷ
public:
Trie() {
}
void insert(string word) {
//浱ǰ
Trie *head = this;
for (auto ch : word){
//Ϊգ˵ûйַ
if (head->m[ch] == nullptr){
//һַһµmapheadָһ㣬mapֻһַ
//Կظġ
head->m[ch] = new Trie();
}
//ߵһ
head = head->m[ch];
}
head->isEnd = true;
}
bool search(string word) {
//ǰ
Trie *head = this;
for (auto ch : word){
//Ϊ˵ûиַ
if (head->m[ch] == nullptr){
return false;
}
//
head = head->m[ch];
}
//жǷ
return head->isEnd;
}
bool startsWith(string prefix) {
//浱ǰ
Trie *head = this;
for (auto ch : prefix){
//Ϊգ˵ûиַfalse
if (head->m[ch] == nullptr){
return false;
}
//ߵϴһ
head = head->m[ch];
}
//˵иǰ
return true;
}
}; | true |
a3186de12545ee752811a635c028c851aae38065 | C++ | NarenMadham/Problem-Solving-Using-Data-Structures-and-Algorithms | /ARRAYS/Kadane's_algorithm.cpp | UTF-8 | 652 | 2.578125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
long long int max(long long int a, long long int b){
if( a > b ){
return a;
}else{
return b;
}
}
int main()
{
int t;
cin>>t;
while(t--){
int n;
cin>>n;
long long int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
long long int dp[n];
dp[0] = arr[0];
for(int i=1;i<n;i++){
dp[i] = max(dp[i-1] + arr[i], arr[i]);
}
long long int s = INT_MIN;
for(int i=0;i<n;i++){
if(s < dp[i]){
s = dp[i];
}
}
cout<<s<<endl;
}
return 0;
} | true |
6c1c10284b30ca47379ff48111ae050603c0e1d7 | C++ | stevecarren/framework-arduinolinkit7697 | /libraries/LBLE/examples/ScanPeripherals/ScanPeripherals.ino | UTF-8 | 2,187 | 2.65625 | 3 | [] | no_license | /*
This example scans nearby BLE peripherals and prints the peripherals found.
created Mar 2017 by MediaTek Labs
*/
#include <LBLE.h>
#include <LBLECentral.h>
void setup() {
//Initialize serial
Serial.begin(9600);
// Initialize BLE subsystem
Serial.println("BLE begin");
LBLE.begin();
while (!LBLE.ready()) {
delay(10);
}
Serial.println("BLE ready, start scan (wait 10 seconds)");
LBLECentral.scan();
for(int i = 0; i < 10; ++i)
{
delay(1000);
Serial.print(".");
}
// list advertisements found.
Serial.print("Total ");
Serial.print(LBLECentral.getPeripheralCount());
Serial.println(" devices found:");
Serial.println("idx\taddress\t\t\tflag\tRSSI");
for (int i = 0; i < LBLECentral.getPeripheralCount(); ++i) {
printDeviceInfo(i);
}
LBLECentral.stopScan();
Serial.println("------scan stopped-------");
}
void loop() {
// do nothing
delay(3000);
}
void printDeviceInfo(int i) {
Serial.print(i);
Serial.print("\t");
Serial.print(LBLECentral.getAddress(i));
Serial.print("\t");
Serial.print(LBLECentral.getAdvertisementFlag(i), HEX);
Serial.print("\t");
Serial.print(LBLECentral.getRSSI(i));
Serial.print("\t");
const String name = LBLECentral.getName(i);
Serial.print(name);
if(name.length() == 0)
{
Serial.print("(Unknown)");
}
Serial.print(" by ");
const String manu = LBLECentral.getManufacturer(i);
Serial.print(manu);
Serial.print(", service: ");
if (!LBLECentral.getServiceUuid(i).isEmpty()) {
Serial.print(LBLECentral.getServiceUuid(i));
} else {
Serial.print("(no service info)");
}
if (LBLECentral.isIBeacon(i)) {
LBLEUuid uuid;
uint16_t major = 0, minor = 0;
int8_t txPower = 0;
LBLECentral.getIBeaconInfo(i, uuid, major, minor, txPower);
Serial.print(" ");
Serial.print("iBeacon->");
Serial.print(" UUID: ");
Serial.print(uuid);
Serial.print("\tMajor:");
Serial.print(major);
Serial.print("\tMinor:");
Serial.print(minor);
Serial.print("\ttxPower:");
Serial.print(txPower);
}
Serial.println();
}
| true |
24de10101fc3876fc35380d48257f7e6b1176739 | C++ | xiazhiyiyun/C-Primer | /Unit15/Exercise15.6/Bulk_quote.h | UTF-8 | 551 | 3 | 3 | [] | no_license | #ifndef _BULK_QUOTE
#define _BULK_QUOTE
#include <string>
#include <iostream>
#include "Quote.h"
class Bulk_quote:public Quote
{
public:
Bulk_quote():min_qty(0),discount(0.0)
{}
Bulk_quote(const std::string & _isbn,double _price,std::size_t _qty,double _discount):
Quote(_isbn,_price),min_qty(_qty),discount(_discount) {}
public:
virtual double net_price(std::size_t n) const
{
if(n > min_qty)
{
return n * (1 - discount) *price;
}else
{
return n * price;
}
}
private:
std::size_t min_qty;
double discount;
};
#endif | true |
bd8ee4aa928bcfee055f237cb235880d55c57508 | C++ | guinao/LeetCode | /Convert Sorted List to Binary Search Tree.cpp | UTF-8 | 758 | 3.578125 | 4 | [] | no_license | #include <cstdio>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
private:
TreeNode* covert(ListNode* begin, ListNode* end=NULL){
if(begin == end)
return NULL;
ListNode *slow = begin, *fast = begin;
while(fast != end){
fast = fast->next;
if(fast != end)
fast = fast->next;
else
break;
slow = slow->next;
}
TreeNode *tn = new TreeNode(slow->val);
tn->left = covert(begin, slow);
tn->right = covert(slow->next, end);
return tn;
}
public:
TreeNode* sortedListToBST(ListNode* head) {
return covert(head);
}
}; | true |
5741a2ef9c45fd2fc7eefdf37c59b4cc9e87f211 | C++ | NewBornSun/Energia | /NewTempSensor/NewTempSensor.ino | UTF-8 | 434 | 2.53125 | 3 | [] | no_license | void setup()
{
// put your setup code here, to run once:
Serial.begin(115200);
}
void loop()
{
// put your main code here, to run repeatedly:
int temperature_counts = analogRead(A19);
float val = temperature_counts*1.821/2304;
float temperature_Celsius = (10.888-sqrt(118.548544+0.01388*(1777.3-val*1000.0)))/(2*-0.00347)+30.0;
//Serial.print(temperature_counts);
Serial.println(temperature_Celsius);
delay(500);
}
| true |
8a1adf3dfd5d3839d7834dffc2eb6e5e0db955ad | C++ | DVRodri8/Competitive-programs | /OnlineJudgeUVa/C++/100-9999/893 - Y3K Problem/main.cpp | UTF-8 | 881 | 3 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main(){
int remaining, day, month, year, passed;
while(cin >> remaining >> day >> month >> year && month != 0 && day != 0){
while(remaining > 0){
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
passed = 32 - day;
break;
case 2:
if(year%400 == 0 || (year % 4 == 0 && year % 100 != 0)) passed = 30 - day;
else passed = 29 - day;
break;
default: passed = 31 - day;
}
if(passed <= remaining){
day = 1;
month += 1;
remaining -= passed;
}else{
day += remaining;
remaining = 0;
}
if(month == 13){
month = 1;
year+=1;
}
}
printf("%d %d %d\n", day, month, year);
}
return 0;
}
| true |
7e98043a4d99059c64953aa9b263fe6875bf3010 | C++ | hahahu91/oop | /lab6/StudentTest/tests.cpp | WINDOWS-1251 | 1,793 | 3.59375 | 4 | [] | no_license | #include "pch.h"
#include "lab6/CStudent.h"
TEST_CASE("CStudent can return yourself name, surname, patronymic and age")
{
CStudent student("Ivanov", "Ivan", "Ivanovich", 25);
CHECK(student.GetName() == "Ivanov");
CHECK(student.GetSurname() == "Ivan");
CHECK(student.GetPatronymic() == "Ivanovich");
CHECK(student.GetAge() == 25);
}
SCENARIO("CStudent allows you to change the name and age of the student") {
GIVEN("Student")
{
CStudent student("Ivanov", "Ivan", "Ivanovich", 25);
WHEN("change name")
{
student.Rename("Smirnov", "Artem", "Nikolaevich");
THEN("the name change")
{
CHECK(student.GetName() == "Smirnov");
CHECK(student.GetSurname() == "Artem");
CHECK(student.GetPatronymic() == "Nikolaevich");
}
}
WHEN("try to change the name to incorrect data")
{
CHECK_THROWS_WITH(student.Rename("Smirnov", " ", "Nikolaevich"), "name and surname cannot be empty\n");
THEN("the name no change")
{
CHECK(student.GetName() == "Ivanov");
CHECK(student.GetSurname() == "Ivan");
CHECK(student.GetPatronymic() == "Ivanovich");
}
}
WHEN("change age")
{
student.SetAge(28);
THEN("the age change")
{
CHECK(student.GetAge() == 28);
}
}
WHEN("try to change the age to incorrect data")
{
CHECK_THROWS_WITH(student.SetAge(12), "age must be between 14 and 60 years old\n");
THEN("the age no change")
{
CHECK(student.GetAge() == 25);
}
CHECK_THROWS_WITH(student.SetAge(24), "new age can not be less\n");
THEN("the age no change")
{
CHECK(student.GetAge() == 25);
}
}
}
}
//
TEST_CASE("Student should not be created with invalid input")
{
CStudent student("Smirnov", "Nikolay", " ", 25);
CHECK(student.GetPatronymic() == "");
} | true |
6c66b9a167ac1f25eca8bcdc991187254128a3fb | C++ | benjaminhuanghuang/ben-leetcode | /1011_Capacity_To_Ship_Packages_Within_D_Days/solution.cpp | UTF-8 | 995 | 3.3125 | 3 | [] | no_license | /*
1011. Capacity To Ship Packages Within D Days [Medium]
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/
*/
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
/*
https://blog.csdn.net/fuxuemingzhu/article/details/88769103
https://www.youtube.com/watch?v=t2eQB9-EqPg
Solution: Binary Search, find minimal valid ship weight capacity
[ #875. Koko Eating Bananas ]
*/
class Solution
{
public:
int shipWithinDays(vector<int> &weights, int D)
{
int l = *max_element(weights.begin(), weights.end());
int r = accumulate(weights.begin(), weights.end(), 0);
while (l < r)
{
int mid = l + (r - l) / 2;
int days = 1;
int capacity = 0;
for (auto const &w : weights)
{
if (capacity + w > mid)
{
days += 1;
capacity = 0;
}
capacity += w;
}
if (days > D)
l = mid + 1;
else
r = mid;
}
return l;
}
}; | true |
457306f28178cd618dc86fe795b80bddb8300105 | C++ | feynard/mesh | /list.hpp | UTF-8 | 5,081 | 3.734375 | 4 | [] | no_license | #ifndef LIST_HPP
#define LIST_HPP
// Generic, oredered, doubly linked list
using namespace std;
template <class D>
class List {
private:
// Inner data container
struct Node {
D var;
Node* next;
Node* prev;
Node(const D & x): var(x), next(0), prev(0) {}
};
Node* root_; // Head of a list
Node* tail_; // Pointer to the tail of a list
Node* current_; // Inner iterator
unsigned int n_; // Number of elements
public:
//
// Constructor and destructor
//
List();
// O(n)
~List();
//
// Methods
//
// Iterator
void set_iterator();
bool iterator();
void iterate();
D & get_iterator();
// Add element to the tail, O(1)
void push(const D & x);
// Add element to the beginning, O(1)
void push_head(const D & x);
// Delete the last (tail) element and return its copy, O(1)
D pop();
// Delete the first element and return its copy, O(1)
D pop_head();
// Removes i-th element
void remove_by_index(unsigned int i);
// ???
// Check if the list contains an element, O(N)
bool contains(const D& x);
// Return the i-j-slice of the list (including both ends), O(n)
List<D> slice(int i, int j);
// Length, O(1)
int length();
// Tail, O(1)
D & tail();
// Head, O(1)
D & root();
//
// Operator overloading
//
// Indexing operator, O(N)
D & operator [] (unsigned int i);
friend istream & operator >> (istream& in, List<D> & list)
{
D element;
in >> element;
list.push(element);
return in;
}
friend ostream & operator << (ostream& out, List<D> & list)
{
out << list.pop();
return out;
}
};
//
// Implementation
//
template <class D>
List<D>::List()
{
root_ = 0, tail_ = 0, n_ = 0;
}
template <class D>
List<D>::~List()
{
Node *p = root_, *prev;
while (p) {
prev = p, p = p -> next;
delete prev;
}
}
template <class D>
void List<D>::set_iterator()
{
current_ = root_;
}
template <class D>
bool List<D>::iterator()
{
return current_ != 0 ? true : false;
}
template <class D>
void List<D>::iterate()
{
current_ = current_ -> next;
}
template <class D>
D & List<D>::get_iterator()
{
return current_ -> var;
}
template <class D>
void List<D>::push(const D & x)
{
if (root_ == 0) {
root_ = new Node(x);
tail_ = root_;
} else {
tail_ -> next = new Node(x);
tail_ -> next -> prev = tail_;
tail_ = tail_ -> next;
}
n_++;
}
template <class D>
void List<D>::push_head(const D & x)
{
if (root_ == 0) {
root_ = new Node(x);
tail_ = root_;
} else {
Node *p = new Node(x);
p -> next = root_;
root_ -> prev = p;
root_ = p;
}
n_++;
}
template <class D>
D List<D>::pop()
{
if (root_ == 0)
return 0;
D tmp = tail_ -> var;
tail_ = tail_ -> prev;
delete tail_ -> next;
tail_ -> next = 0;
n_--;
return tmp;
}
template <class D>
D List<D>::pop_head()
{
if (root_ == 0)
return 0;
D tmp = root_ -> var;
if (root_ -> next == 0) {
delete root_;
root_ = 0, tail_ = 0;
} else {
Node *p = root_;
root_ = root_ -> next;
root_ -> prev = 0;
delete p;
}
n_--;
return tmp;
}
template <class D>
void List<D>::remove_by_index(unsigned int i)
{
if (i >= n_)
return;
n_--;
Node *p = root_;
for (unsigned int j = 0; j < i; j++)
p = p -> next;
if (p == root_ && p != tail_) {
root_ = root_ -> next;
delete root_ -> prev;
root_ -> prev = 0;
return;
} else if (p == tail_ && p != root_) {
tail_ = p -> prev;
p -> prev -> next = 0;
delete p;
return;
} else if (p == tail_ && p == root_) {
delete root_;
root_ = 0;
tail_ = 0;
return;
}
p -> prev -> next = p -> next;
p -> next -> prev = p -> prev;
delete p;
}
template <class D>
bool List<D>::contains(const D& x)
{
Node *p = root_;
while (p) {
if (p -> var == x)
return true;
p = p -> next;
}
return false;
}
template <class D>
List<D> List<D>::slice(int i, int j)
{
List<D> new_list;
Node *p = root_;
// Variable p points to the i-th element
for (int k = 0; k < i; k++)
p = p -> next;
// Push all the necessary elements to the new list
for (int k = 0; k <= j - i; k++, p = p -> next)
new_list.push(p -> var);
return new_list;
}
template <class D>
int List<D>::length()
{
return n_;
}
template <class D>
D & List<D>::tail()
{
return tail_ -> var;
}
template <class D>
D & List<D>::root()
{
return root_ -> var;
}
template <class D>
D & List<D>::operator [] (unsigned int i)
{
Node *p = root_;
for (unsigned int j = 0; j < i; j++)
p = p -> next;
return p -> var;
}
#endif
| true |