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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
90466d6a93f99570baa32e871fa24d69e06f66cf | C++ | yaelShechter/ATM | /src/account.cpp | UTF-8 | 224 | 2.75 | 3 | [] | no_license | #include "account.hpp"
Account::Account(int balance):
_balance(balance)
{}
int Account::balance() const
{
return _balance;
}
void Account::set_balance(int new_balance)
{
_balance = new_balance;
} | true |
eedbbc8c5fcb881dc9e0eeabea233097e47f9157 | C++ | JHYOOOOON/Collection | /baekjoon/2456.cpp | UTF-8 | 1,076 | 3 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#define X first
#define Y second
using namespace std;
bool compare(pair<pair<int, int>, pair<int, int>> a, pair<pair<int, int>, pair<int, int>> b){
if(a.X.X != b.X.X) return a.X.X > b.X.X;
else if(a.X.Y != b.X.Y) return a.X.Y > b.X.Y;
else if(a.Y.X != b.Y.X) return a.Y.X > b.Y.X;
else{ return a.Y.Y > b.Y.Y; }
}
int main(){
int t, tmp;
pair<pair<int, int>, pair<int, int>> score[4] = {{{0,0}, {0,0}}};
score[1].Y.Y = 1;
score[2].Y.Y = 2;
score[3].Y.Y = 3;
cin >> t;
while(t--){
for(int i=1; i<=3; i++){
cin >> tmp;
score[i].X.X += tmp;
if(tmp == 3){ score[i].X.Y++; }
else if(tmp == 2){ score[i].Y.X++; }
}
}
sort(score+1, score+4, compare);
if((score[1].X.X == score[2].X.X) &&
(score[1].X.Y == score[2].X.Y) &&
(score[1].Y.X == score[2].Y.X)){
cout << 0 << ' ' << score[1].X.X << "\n";
} else{ cout << score[1].Y.Y << ' ' << score[1].X.X << "\n"; }
return 0;
}
| true |
9f049916a72120b12be46fe5dcfb3ea85dd84fce | C++ | vutuancong/C--Combination. | /Chap 4-Linklist-Stack-Queue/stl_DuyetString.cpp | UTF-8 | 969 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <list>
#include <string>
#include <fstream>
using namespace std;
typedef struct node
{
string word;
int soLan;
};
list<node> X;
list<node>::iterator i;
int kiemTra(string a,int &n)
{
int count = 0;
for(i = X.begin();i!=X.end();i++)
{
node temp = *i;
if(temp.word == a) return count;
count++;
}
return n+1;
}
void Fix_node(int n)
{
int count = 0;
for(i =X.begin(),count = 0;i!=X.end();i++,count++)
{
if(count == n)
{
node temp = *i;
X.erase(i);
temp.soLan++;
X.push_back(temp);
break;
}
}
}
void Display()
{
for(i = X.begin();i!=X.end();i++)
{
node temp = *i;
cout<<temp.word<<" "<<temp.soLan<<endl;
}
}
int main()
{
fstream f;
string a;
int flag = 0,n = 0;
f.open("vanban.txt",ios::in);
while(!f.eof())
{
f>>a;
flag = kiemTra(a,n);
if(flag > n)
{
node temp;
temp.soLan = 1;
temp.word = a;
X.push_back(temp);
n = flag;
}
else Fix_node(flag);
}
Display();
}
| true |
13df27077d2c5768b153ac0e217a5dc5b149f3be | C++ | mtrempoltsev/msu_cpp_autumn_2017 | /homework/Filin/08/task8_1.cpp | UTF-8 | 8,161 | 3.640625 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <stdio.h>
#include <memory>
#include <vector>
//базовый класс ошибок
class Error {
protected:
std::string message_;
public:
const std::string getMessage() const {
return message_;
}
};
//класс ошибок, возникающих в базовых операциях/функциях класса Vector
class VectorError : public Error
{
public:
VectorError(std::string&& message) {
message_ = message;
}
};
//класс ошибок, возникающих в базовых операциях/функциях при использовании итераторов
class IteratorError : public Error
{
public:
IteratorError(std::string&& message) {
message_ = message;
}
};
//класс ошибок возникающих при неправильных значениях векторов
class ValueError: public Error {
public:
ValueError(std::string&& message) {
message_ = message;
}
};
template<class T> void test();
template <class T, bool reverse>
class Iterator: public std::iterator<std::forward_iterator_tag, T>
{
T* ptr_;
void next_() {
if (reverse) {
ptr_--;
} else {
ptr_++;
}
}
public:
using const_reference = const Iterator<T, reverse>&;
using reference_type = T&;
explicit Iterator(T* ptr) : ptr_(ptr) {}
bool operator==(const_reference other) const
{
return ptr_ == other.ptr_;
}
bool operator!=(const_reference other) const
{
return !(*this == other);
}
reference_type operator*() const
{
return *ptr_;
}
Iterator& operator++()
{
next_();
return *this;
}
Iterator& operator++(T)
{
next_();
return *this;
}
};
//шаблонная реализация класса Vector
template<class T, class Alloc = std::allocator<T>>
class Vector
{
using size_type = size_t;
using value_type = T;
using value_type_ptr = T*;
using lvalue_type = value_type&&;
using reference = value_type&;
using const_reference = const value_type&;
static const int default_size = 128;
using iterator = Iterator<value_type, false>;
using const_iterator = Iterator<const_reference, false>;
using reverse_iterator = Iterator<value_type, true>;
using const_reverse_iterator = Iterator<const_reference, true>;
public:
explicit Vector()
{
size_ = default_size;
capacity_ = default_size;
data_ = allocator_.allocate(default_size);
}
explicit Vector(size_type count)
{
size_ = count;
capacity_ = count;
data_ = allocator_.allocate(count);
throw std::bad_alloc();
}
explicit Vector(size_type count, value_type defaultValue)
{
size_ = count;
capacity_ = count;
data_ = allocator_.allocate(count);
for (size_type i = 0; i < size_; i++) {
data_[i] = defaultValue;
}
}
void push_back(const_reference value) {
if (size_ == capacity_) {
reserve(capacity_ * 2);
}
data_[size_] = value;
size_++;
}
void push_back(lvalue_type value) {
if (size_ == capacity_){
reserve(capacity_ * 2);
}
data_[size_] = std::move(value);
size_++;
}
reference pop_back() {
size_--;
return data_[size_];
}
void reserve(size_type count)
{
value_type_ptr tmp;
tmp = allocator_.allocate(size_);
for (size_type i = 0; i < size_; i++) {
tmp[i] = data_[i];
}
data_ = allocator_.allocate(count);
size_type bound = std::min(size_, count);
for (size_type i = 0; i < bound; i++) {
data_[i] = tmp[i];
}
capacity_ = count;
size_ = bound;
allocator_.deallocate(tmp, size_);
}
size_type capacity() const noexcept
{
return capacity_;
}
void resize(size_type newSize)
{
reserve(newSize);
size_ = newSize;
}
void resize(size_type newSize, value_type defaultValue)
{
reserve(newSize);
for (size_type i = size_; i < newSize; i++) {
data_[i] = defaultValue;
}
size_ = newSize;
}
constexpr size_type size() const noexcept
{
return size_;
}
reference operator[](size_type pos)
{
return data_[pos];
}
constexpr const_reference operator[](size_type pos) const
{
return data_[pos];
}
void clear() noexcept {
allocator_.deallocate(data_, capacity_);
size_ = 0;
capacity_ = 0;
}
bool empty() noexcept {
return size_ == 0;
}
iterator begin() noexcept
{
return iterator(data_);
}
const_iterator begin() const noexcept
{
return const_iterator(data_);
}
iterator end() noexcept
{
return iterator(data_ + size_);
}
const_iterator end() const noexcept
{
return const_iterator(data_ + size_);
}
reverse_iterator rbegin() noexcept
{
return reverse_iterator(data_ + size_ - 1);
}
const_reverse_iterator rbegin() const noexcept
{
return const_reverse_iterator(data_ + size_ - 1);
}
reverse_iterator rend() noexcept
{
return reverse_iterator(data_ - 1);
}
const_reverse_iterator rend() const noexcept
{
return const_reverse_iterator(data_ - 1);
}
private:
T* data_;
size_t size_;
size_t capacity_;
Alloc allocator_;
};
int main(int argc, char* argv[]) {
try {
test<int>();
}
catch (const ValueError& error) {
std::cerr << error.getMessage() << std::endl;
}
catch (const IteratorError& error) {
std::cerr << error.getMessage() << std::endl;
}
catch (...) {
std::cerr << "Unexpected Exception" << std::endl;
}
std::cout << "Finish testing..." << std::endl;
return 0;
}
void check(bool value) {
if (!value) {
throw ValueError("Value error while testing");
}
}
template<class T>
void test()
{
try {
Vector<T> vec = Vector<T>(3, 100);
vec[1] = 20;
check(vec[0] == 100);
check(vec[1] == 20);
check(vec[2] == 100);
T a = 5;
vec.push_back(a);
check(vec.size() == 4);
check(vec[3] == 5);
T b = vec.pop_back();
check(b == 5);
vec.resize(5, -10);
check(vec[3] == -10);
check(vec.size() == 5);
vec.reserve(100);
check(vec.capacity() == 100);
check(vec.size() == 5);
vec.reserve(3);
check(vec.size() == 3);
}
catch(const ValueError& error) {
std::cerr << error.getMessage() << std::endl;
}
catch(...) {
throw VectorError("Vector error while testing");
}
try {
std::vector<T> stdvec(3, 4);
Vector<T> myvec(3, 4);
myvec.push_back(4);
stdvec.push_back(4);
check(myvec.size() == stdvec.size());
auto iter = myvec.begin();
auto stditer = stdvec.begin();
while ((iter != myvec.end()) && (stditer != stdvec.end())) {
check(*iter == *stditer);
iter++;
stditer++;
}
auto iter2 = myvec.rbegin();
auto stditer2 = stdvec.rbegin();
while ((iter2 != myvec.rend()) && (stditer2 != stdvec.rend())) {
check(*iter2 == *stditer2);
iter2++;
stditer2++;
}
}
catch(const ValueError& error) {
std::cerr << error.getMessage() << std::endl;
}
catch(...) {
throw IteratorError("Iterator error while testing");
}
}
| true |
e15a68c19dfb15029edd18a0fed9b11158cd3c92 | C++ | FabioVL/IME | /LabProg1/Revisao_C/ordena.cpp | UTF-8 | 443 | 2.828125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
// Método bubblesort(?)
int *a,n,b;
cout << "Entre com n: " << endl;
cin >> n;
a = (int *) malloc(n* (sizeof(int)));
for(int i=0;i<n;i++) scanf("%d",&a[i]);
for (int i=0;i<n;i++)
for (int j=0;j<n-1;j++)
{
if (a[j+1] < a[j])
{
b = a[j];
a[j] = a[j+1];
a[j+1] = b;
}
}
for (int i=0;i<n;i++) cout << a[i] << " ";
free(a);
cout << endl;
} | true |
52f0a3e43a4151c3e4053bcbc22a990126ace4de | C++ | xingfeT/c-practice | /day-001-100/day-024/problem-3/main.cpp | UTF-8 | 985 | 4.375 | 4 | [] | no_license | /*
* Write a C program that asks the user to input two numbers. After your program
* accepts these numbers using one or more scanf() function calls, have your program
* check the numbers. If the first number entered is greater than the second number,
* print the message:
* - "The first number is greater than the second"
*
* else print the message:
* - "The first number is not greater than the second"
*/
#include <stdio.h>
struct Numbers
{
float X;
float Y;
};
inline bool
IsGreaterThan(float, float);
int
main(void)
{
Numbers N = {};
printf("Enter in a first number:\n");
scanf("%f", &N.X);
printf("Enter in a second number:\n");
scanf("%f", &N.Y);
if (IsGreaterThan(N.X, N.Y))
{
printf("The first number is greater than the second!\n");
}
else
{
printf("The first number is not greater than the second!\n");
}
return 0;
}
inline bool
IsGreaterThan(float firstNumber, float secondNumber)
{
return (firstNumber > secondNumber) ? true : false;
}
| true |
596349485986ff178e45348adaa8f8ff66f506d5 | C++ | fudalejt/SFML-game | /SFML game/SFML/VertexHitbox.cpp | UTF-8 | 1,976 | 2.8125 | 3 | [] | no_license | #include "VertexHitbox.h"
#include "MathUtilities.h"
#include <iostream>
VertexHitbox::VertexHitbox(sf::VertexArray& vertexAr):
vertexAr(vertexAr),
linPar(std::vector<LinFuncParam>(vertexAr.getVertexCount()))
{
}
VertexHitbox::~VertexHitbox()
{
}
bool VertexHitbox::isContaining(const sf::Vector2f& point)
{
sf::Vector2f relPoint = point;
relPoint = relPoint - getPosition();
relPoint = math::rotateVector(relPoint, getRotation());
relPoint += getOrigin();
for (unsigned int i = 1; i < vertexAr.getVertexCount() - 1; i++)
{
LinFuncParam &fx = linPar[i];
if (fx.a == std::numeric_limits<float>::max()) //if f(x) function is a vertical positive funct &&...
{
if (relPoint.x > vertexAr[i].position.x)
return false;
else
continue;
}
else if (fx.a == std::numeric_limits<float>::min()) //if f(x) function is a vertical negative funct &&...
{
if (relPoint.x < vertexAr[i].position.x)
return false;
else
continue;
}
else {
if (fx.o == 1) {
if ((fx.a * relPoint.x + fx.b) > relPoint.y) {
return false;
}
}
else if (fx.o == -1) {
if ((fx.a * relPoint.x + fx.b) < relPoint.y)
return false;
}
else {
throw "class [COLLIDE_POLYGON], method [CONTAIN()]: ERROR, fx.o ";
}
}
}
return true;
}
void VertexHitbox::refresh()
{
for (unsigned int i = 1; i < linPar.size() - 1; i++) {
LinFuncParam &fx = linPar[i];
if ((vertexAr[i + 1].position.x - vertexAr[i].position.x) != 0) {
fx.setA((vertexAr[i + 1].position.y - vertexAr[i].position.y) / (vertexAr[i + 1].position.x - vertexAr[i].position.x));
fx.setB((vertexAr[i].position.y) - fx.a * (vertexAr[i].position.x));
fx.setO((vertexAr[i + 1].position.x - vertexAr[i].position.x > 0) ? 1 : -1);
}
else {
if ((vertexAr[i + 1].position.y - vertexAr[i].position.y) > 0)
fx.setA(std::numeric_limits<float>::max()); //max float value
else
fx.setA(std::numeric_limits<float>::min()); //min float value
}
}
}
| true |
0147751f98be11ef13c5dfb5e3e2713780c7fa6e | C++ | Infamous0192/competitive-programming | /classical/HANGOVER.cpp | UTF-8 | 270 | 2.578125 | 3 | [] | no_license | #include <stdio.h>
int main() {
float c;
scanf("%f", &c);
while (c) {
float len = 0.00;
int n = 0;
while (len < c) {
n++;
len += 1.00 / (1.00 + n);
}
printf("%d card(s)\n", n);
scanf("%f", &c);
}
return 0;
} | true |
bee23c7889f280449ca5cc1cbfbfa8578b474573 | C++ | hlohse/sound-glove | /software/common/Serializer.h | UTF-8 | 476 | 2.59375 | 3 | [] | no_license | #ifndef SERIALIZER_H_
#define SERIALIZER_H_
#include "SharedPointer.h"
#include "Serialization.h"
class Serializer {
public:
Serializer(const Serialization& serialization);
void serialize(const uint8_t value, const int bits = 8);
void serialize(uint8_t* buffer, const int length);
int size() const;
private:
SharedPointer<uint8_t> data_;
uint8_t* current_data_;
int bit_offset_;
uint8_t* data_end_;
void checkError();
};
#endif /* SERIALIZER_H_ */
| true |
93c5041c7b21a69101707b51448a3b1e15d0d647 | C++ | Igor-amateur/mvp-for-license-service-project | /Windows_C++dll_client/DLLControlLicense/file_parser.h | UTF-8 | 536 | 2.5625 | 3 | [] | no_license | #ifndef FILE_PARSER_H_INCLUDED
#define FILE_PARSER_H_INCLUDED
#include <iostream>
#include<string>
struct TargetPoint
{
bool is_parsed_ = false;
int port_;
std::string ip_addres_;
double time_dur_;
TargetPoint() = default;
explicit TargetPoint(int port, std::string ip_addres, double time_dur);
void SetPort(int port);
void SetIPaddres(std::string ip_addres);
void SetTimeDuration(double time_dur);
};
TargetPoint& fileParser(TargetPoint& targetPoint, const std::string& fileName);
#endif // FILE_PARSER_H_INCLUDED
| true |
6bddcb81e05e0bf2fe454d7ea5473f081bb9e198 | C++ | trnthsn/VongLapPractice | /bai27.cpp | UTF-8 | 221 | 2.734375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
string number[] = {"khong", "mot", "hai", "ba", "bon", "nam",
"sau", "bay", "tam", "chin"};
int n;
cin >> n;
if (n >= 0 && n <= 9)
cout << number[n];
}
| true |
d3d832bddcb971e5bb7a9359f4b1632b76c97909 | C++ | lkesteloot/weekend-ray-tracer | /src/ray/Texture.h | UTF-8 | 261 | 2.859375 | 3 | [
"Apache-2.0"
] | permissive | #ifndef TEXTURE_H
#define TEXTURE_H
#include "Vec3.h"
// Interface for a procedural texture.
class Texture {
public:
// Use u,v for 2D textures, p for 3D textures.
virtual Vec3 value(float u, float v, const Vec3 &p) const = 0;
};
#endif // TEXTURE_H
| true |
195adc2ef8ea1fcff0adcde98c024b646da903e5 | C++ | Sopel97/chess_pos_db | /src/chess/ReverseMoveGenerator.h | UTF-8 | 44,995 | 2.8125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Bitboard.h"
#include "CastlingTraits.h"
#include "Chess.h"
#include "Position.h"
#include "data_structure/FixedVector.h"
#include "enum/EnumArray.h"
namespace movegen
{
struct PieceSetMask
{
bool pawn;
bool knight;
bool lightSquareBishop;
bool darkSquareBishop;
bool rook;
bool queen;
[[nodiscard]] constexpr static PieceSetMask allUncaptures()
{
return { true, true, true, true, true, true };
}
[[nodiscard]] constexpr static PieceSetMask allUnpromotions()
{
return { false, true, true, true, true, true };
}
};
struct PieceSet
{
std::uint8_t pawnCount;
std::uint8_t knightCount;
std::uint8_t lightSquareBishopCount;
std::uint8_t darkSquareBishopCount;
std::uint8_t rookCount;
std::uint8_t queenCount;
[[nodiscard]] constexpr static PieceSet standardPieceSet()
{
return PieceSet(8, 2, 1, 1, 2, 1);
}
constexpr PieceSet() :
pawnCount{},
knightCount{},
lightSquareBishopCount{},
darkSquareBishopCount{},
rookCount{},
queenCount{}
{
}
constexpr PieceSet(int pawnCount, int knightCount, int lsbCount, int dsbCount, int rookCount, int queenCount) :
pawnCount(pawnCount),
knightCount(knightCount),
lightSquareBishopCount(lsbCount),
darkSquareBishopCount(dsbCount),
rookCount(rookCount),
queenCount(queenCount)
{
}
PieceSet(const Board& board, Color color) :
pawnCount(board.pieceCount(Piece(PieceType::Pawn, color))),
knightCount(board.pieceCount(Piece(PieceType::Knight, color))),
lightSquareBishopCount((board.piecesBB(Piece(PieceType::Bishop, color)) & bb::lightSquares).count()),
darkSquareBishopCount((board.piecesBB(Piece(PieceType::Bishop, color)) & bb::darkSquares).count()),
rookCount(board.pieceCount(Piece(PieceType::Rook, color))),
queenCount(board.pieceCount(Piece(PieceType::Queen, color)))
{
}
[[nodiscard]] constexpr bool canTurnInto(const PieceSet& future) const
{
// Pawns can turn into pieces but the pawn count is bounded from above.
const int availablePawnPromotions = pawnCount - future.pawnCount;
if (availablePawnPromotions < 0)
{
// pawns cannot be added
return false;
}
const int additionalQueens = std::max(0, future.queenCount - queenCount);
const int additionalRooks = std::max(0, future.rookCount - rookCount);
const int additionalLsbs = std::max(0, future.lightSquareBishopCount - lightSquareBishopCount);
const int additionalDsbs = std::max(0, future.darkSquareBishopCount - darkSquareBishopCount);
const int additionalKnights = std::max(0, future.knightCount - knightCount);
return
additionalQueens
+ additionalRooks
+ additionalLsbs
+ additionalDsbs
+ additionalKnights
<= availablePawnPromotions;
}
// this must be able to turn into current
[[nodiscard]] constexpr PieceSetMask uncapturesWithRemaining(const PieceSet& current) const
{
// this is start pieces
// current is what's remaining
const int additionalQueens = std::max(0, current.queenCount - queenCount);
const int additionalRooks = std::max(0, current.rookCount - rookCount);
const int additionalLsbs = std::max(0, current.lightSquareBishopCount - lightSquareBishopCount);
const int additionalDsbs = std::max(0, current.darkSquareBishopCount - darkSquareBishopCount);
const int additionalKnights = std::max(0, current.knightCount - knightCount);
const int additionalPieces = additionalQueens
+ additionalRooks
+ additionalLsbs
+ additionalDsbs
+ additionalKnights;
const bool hasUnusedPawnPromotions = (pawnCount - current.pawnCount - additionalPieces) > 0;
return {
hasUnusedPawnPromotions,
hasUnusedPawnPromotions || (current.knightCount < knightCount),
hasUnusedPawnPromotions || (current.lightSquareBishopCount < lightSquareBishopCount),
hasUnusedPawnPromotions || (current.darkSquareBishopCount < darkSquareBishopCount),
hasUnusedPawnPromotions || (current.rookCount < rookCount),
hasUnusedPawnPromotions || (current.queenCount < queenCount)
};
}
[[nodiscard]] FixedVector<Piece, 6> uncaptures(const PieceSet& current, Color capturedPieceColor, Color squareColor) const
{
const auto mask = uncapturesWithRemaining(current);
FixedVector<Piece, 6> pieces;
pieces.emplace_back(Piece::none());
if (mask.pawn) pieces.emplace_back(Piece(PieceType::Pawn, capturedPieceColor));
if (mask.knight) pieces.emplace_back(Piece(PieceType::Knight, capturedPieceColor));
if (
(mask.lightSquareBishop && squareColor == Color::White)
|| (mask.darkSquareBishop && squareColor == Color::Black)
)
pieces.emplace_back(Piece(PieceType::Bishop, capturedPieceColor));
if (mask.rook) pieces.emplace_back(Piece(PieceType::Rook, capturedPieceColor));
if (mask.queen) pieces.emplace_back(Piece(PieceType::Queen, capturedPieceColor));
return pieces;
}
// this must be able to turn into current
[[nodiscard]] constexpr PieceSetMask unpromotionsWithRemaining(const PieceSet& current) const
{
// this is start pieces
// current is what's remaining
// To be able to unpromote a piece we have to have either
// 1. an unused pawn promotion - so we have a pawn that was just captured (or a promoted piece captured)
// 2. more pieces of the type than at the start - because that piece must have came from a promotion
// for example with rbqqknbr/8/ppppppp1 the only possible unpromotion is queen unpromotion because otherwise
// we would end up with two queens and 8 pawns.
const int additionalQueens = std::max(0, current.queenCount - queenCount);
const int additionalRooks = std::max(0, current.rookCount - rookCount);
const int additionalLsbs = std::max(0, current.lightSquareBishopCount - lightSquareBishopCount);
const int additionalDsbs = std::max(0, current.darkSquareBishopCount - darkSquareBishopCount);
const int additionalKnights = std::max(0, current.knightCount - knightCount);
const int additionalPieces = additionalQueens
+ additionalRooks
+ additionalLsbs
+ additionalDsbs
+ additionalKnights;
const bool hasUnusedPawnPromotions = (pawnCount - current.pawnCount - additionalPieces) > 0;
return {
false,
hasUnusedPawnPromotions || (current.knightCount > knightCount),
hasUnusedPawnPromotions || (current.lightSquareBishopCount > lightSquareBishopCount),
hasUnusedPawnPromotions || (current.darkSquareBishopCount > darkSquareBishopCount),
hasUnusedPawnPromotions || (current.rookCount > rookCount),
hasUnusedPawnPromotions || (current.queenCount > queenCount)
};
}
[[nodiscard]] EnumArray<PieceType, bool> unpromotions(const PieceSet& current, Color squareColor) const
{
const auto mask = unpromotionsWithRemaining(current);
EnumArray<PieceType, bool> validUnpromotions;
for (auto& p : validUnpromotions) p = false;
if (mask.knight) validUnpromotions[PieceType::Knight] = true;
if (
(mask.lightSquareBishop && squareColor == Color::White)
|| (mask.darkSquareBishop && squareColor == Color::Black)
)
validUnpromotions[PieceType::Bishop] = true;
if (mask.rook) validUnpromotions[PieceType::Rook] = true;
if (mask.queen) validUnpromotions[PieceType::Queen] = true;
return validUnpromotions;
}
};
namespace detail
{
struct CandidateEpSquares
{
Bitboard ifNoUncapture;
Bitboard ifPawnUncapture;
Bitboard ifOtherUncapture;
[[nodiscard]] Bitboard forUncapture(Piece piece) const
{
if (piece.type() == PieceType::None)
{
return ifNoUncapture;
}
if (piece.type() == PieceType::Pawn)
{
return ifPawnUncapture;
}
return ifOtherUncapture;
}
};
[[nodiscard]] CandidateEpSquares candidateEpSquaresForReverseMove(
const Board& board,
Color sideToDoEp,
const Move& rm
)
{
const Piece movedPiece = board.pieceAt(rm.to);
Bitboard ourPawns = board.piecesBB(Piece(PieceType::Pawn, sideToDoEp));
Bitboard theirPawns = board.piecesBB(Piece(PieceType::Pawn, !sideToDoEp));
Bitboard pieces = board.piecesBB();
const Bitboard fromto = Bitboard::square(rm.from) ^ rm.to;
pieces ^= fromto;
if (movedPiece.type() == PieceType::Pawn)
{
// We have to update our pawns locations
ourPawns ^= fromto;
if (rm.type == MoveType::EnPassant)
{
// If it's an en-passant then this must be the only possible
// epSquare if we want to reverse the move.
// That's because there can be only one epSquare for a given
// position.
const Bitboard epSquare = Bitboard::square(rm.to);
return { epSquare, epSquare, epSquare };
}
}
CandidateEpSquares candidateEpSquares{ Bitboard::none(), Bitboard::none(), Bitboard::none() };
if (sideToDoEp == Color::White)
{
// Case 1. no uncapture
candidateEpSquares.ifNoUncapture = (
theirPawns & bb::rank5
& ~(pieces.shiftedVertically(-1) | pieces.shiftedVertically(-2))
).shiftedVertically(1);
// Case 2. other uncapture
// In this case the uncapture may place a piece on the double push path
// making impossible to have done double push earlier and
// so the en-passant to was not possible instead of that capture.
pieces ^= rm.to;
const Bitboard unobstructed = ~(pieces.shiftedVertically(-1) | pieces.shiftedVertically(-2));
candidateEpSquares.ifOtherUncapture = (
theirPawns & bb::rank5
& unobstructed
).shiftedVertically(1);
// Case 3. a pawn uncapture
// In this case we may have added a candidate to capture.
// We may have also inhibited some ep.
// Consider B. p.
// .. -> .B
// pP pP
// This is a generalization of Case 2. The `pieces` is already
// updated there.
candidateEpSquares.ifPawnUncapture = (
(theirPawns | rm.to) & bb::rank5
& unobstructed
).shiftedVertically(1);
}
else
{
// Case 1.
candidateEpSquares.ifNoUncapture = (
theirPawns & bb::rank4
& ~(pieces.shiftedVertically(1) | pieces.shiftedVertically(2))
).shiftedVertically(-1);
// Case 2.
pieces ^= rm.to;
const Bitboard unobstructed = ~(pieces.shiftedVertically(1) | pieces.shiftedVertically(2));
candidateEpSquares.ifOtherUncapture = (
theirPawns & bb::rank4
& unobstructed
).shiftedVertically(-1);
// Case 3.
candidateEpSquares.ifPawnUncapture = (
(theirPawns | rm.to) & bb::rank4
& unobstructed
).shiftedVertically(-1);
}
// We only consider candidate ep squares that are attacked by our pawns.
// Otherwise nothing could execute the en-passant so the flag
// cannot be set.
const Bitboard ourPawnAttacks = bb::pawnAttacks(ourPawns, sideToDoEp);
candidateEpSquares.ifNoUncapture &= ourPawnAttacks;
candidateEpSquares.ifPawnUncapture &= ourPawnAttacks;
candidateEpSquares.ifOtherUncapture &= ourPawnAttacks;
return candidateEpSquares;
}
struct CastlingRightsByUncapture
{
CastlingRights ifNotRookUncapture;
CastlingRights ifRookUncapture;
};
[[nodiscard]] CastlingRightsByUncapture updateCastlingRightsForReverseMove(
CastlingRights minCastlingRights,
const Board& board,
Color sideToUnmove,
const Move& rm
)
{
const Piece ourRook = Piece(PieceType::Rook, sideToUnmove);
const Piece ourKing = Piece(PieceType::King, sideToUnmove);
if (rm.type == MoveType::Castle)
{
// We only have to consider adding the castling right used
// and possibly for the other castle type. No need
// to add anything for the opponent, and since we
// cannot capture when castling both returned rights are the same.
const CastleType castleType = CastlingTraits::moveCastlingType(rm);
const CastlingRights requiredCastlingRight = CastlingTraits::castlingRights[sideToUnmove][castleType];
CastlingRights castlingRights = minCastlingRights | requiredCastlingRight;
const Square otherRookSq = CastlingTraits::rookStart[sideToUnmove][!castleType];
if (board.pieceAt(otherRookSq) == ourRook)
{
castlingRights |= CastlingTraits::castlingRights[sideToUnmove][!castleType];;
}
return { castlingRights, castlingRights };
}
// This is only reached if not a castling move.
CastlingRights castlingRightsIfNotRookCapture = minCastlingRights;
const Piece movedPiece = board.pieceAt(rm.to);
if (movedPiece.type() == PieceType::King)
{
// If we move our king back to its starting position
// then we need to add castling rights for each rook still
// on its starting square.
if (rm.from == CastlingTraits::kingStart[sideToUnmove])
{
const Square shortRookSq = CastlingTraits::rookStart[sideToUnmove][CastleType::Short];
const Square longRookSq = CastlingTraits::rookStart[sideToUnmove][CastleType::Long];
if (board.pieceAt(shortRookSq) == ourRook)
{
castlingRightsIfNotRookCapture |= CastlingTraits::castlingRights[sideToUnmove][CastleType::Short];
}
if (board.pieceAt(longRookSq) == ourRook)
{
castlingRightsIfNotRookCapture |= CastlingTraits::castlingRights[sideToUnmove][CastleType::Long];
}
}
}
else if (movedPiece.type() == PieceType::Rook)
{
// If we move a rook we only have to add its castling rights
// if we move to its starting square and the king is at the
// starting square.
if (board.pieceAt(CastlingTraits::kingStart[sideToUnmove]) == ourKing)
{
const Square shortRookSq = CastlingTraits::rookStart[sideToUnmove][CastleType::Short];
const Square longRookSq = CastlingTraits::rookStart[sideToUnmove][CastleType::Long];
if (rm.from == shortRookSq)
{
castlingRightsIfNotRookCapture |= CastlingTraits::castlingRights[sideToUnmove][CastleType::Short];
}
else if (rm.from == longRookSq)
{
castlingRightsIfNotRookCapture |= CastlingTraits::castlingRights[sideToUnmove][CastleType::Long];
}
}
}
CastlingRights castlingRightsIfRookCapture = castlingRightsIfNotRookCapture;
{
// Now we're interested in possible uncaptures of an opponent's rook.
// We can only add castling rights if the king is at the start place.
const Color opponentSide = !sideToUnmove;
const Piece theirKing = Piece(PieceType::King, opponentSide);
if (board.pieceAt(CastlingTraits::kingStart[opponentSide]) == theirKing)
{
const Piece theirRook = Piece(PieceType::Rook, opponentSide);
const Square shortRookSq = CastlingTraits::rookStart[opponentSide][CastleType::Short];
const Square longRookSq = CastlingTraits::rookStart[opponentSide][CastleType::Long];
if (rm.to == shortRookSq)
{
castlingRightsIfRookCapture |= CastlingTraits::castlingRights[opponentSide][CastleType::Short];
}
else if (rm.to == longRookSq)
{
castlingRightsIfRookCapture |= CastlingTraits::castlingRights[opponentSide][CastleType::Long];
}
}
}
return { castlingRightsIfNotRookCapture, castlingRightsIfRookCapture };
}
[[nodiscard]] FixedVector<CastlingRights, 16> allCastlingRightsBetween(
CastlingRights min,
CastlingRights max
)
{
const unsigned minInt = static_cast<unsigned>(min);
const unsigned maxInt = static_cast<unsigned>(max);
const unsigned mask = minInt ^ maxInt;
FixedVector<CastlingRights, 16> set;
unsigned maskSubset = 0;
do
{
// We generate all subsets of the difference between min and max
// and xor them with min to get all castling rights between min and max.
// masked increment
// https://stackoverflow.com/questions/44767080/incrementing-masked-bitsets
maskSubset = ((maskSubset | ~mask) + 1) & mask;
set.emplace_back(static_cast<CastlingRights>(minInt ^ maskSubset));
} while (maskSubset);
return set;
}
// This creates a function object that finds all
// possible permutations of capturedPiece, oldEpSquare,
// oldCastlingRights and emits all those moves.
// oldCastlingRights options may depend on the uncaptured piece.
// - some reverse moves may add castling rights.
// capturedPiece options are always the same regardless of the other.
// oldEpSquare options for a given reverse move may differ depending
// on the capturedPiece. That is because the capturedPiece
// may have been attacking our king in which case no en-passant
// is possible (unless the pawn becomes a blocker).
// We at least know that at the beginning our king is not attacked.
// So it's enough to check which placements of
// which opponent piece as capturedPiece would
// result in an attack on our king and which
// pieces are important blockers
// (the blockers don't change unless the reverse
// move is not a capture)
// - and then when generating actual oldEpSquares we either:
// 1. if our king was not in check then generate all oldEpSquares.
// 2. if our king was in check then we know the offending piece
// and we can verify whether the en-passant pawn
// would become a blocker.
//
// Additionally we cannot set oldEpSquare if after
// doing the en-passant our king would end up in check.
// This has to be checked always.
// We can specialize for two cases:
// 1. if our king is not on the same rank as the ep pawns
// we can use blockersForKing to determine if the king
// ends up in a discovered check. (But even if the pawn
// was a blocker we may have added a new blocker so we have
// to check further.)
// 2. if our king is on the same rank as ep pawns then it's
// best to just undo the move, do the ep (not literraly,
// just simulate piece placements), and check if our
// king ends up in check.
// This builds a function object for the given position that
// checks whether given a `undoMove`, `epSquare`, and `uncapturedPiece`
// if we undid the `undoMove` and uncaptured `uncapturedPiece` would the
// `epSquare` be a valid en-passant target.
[[nodiscard]] auto makeTimeTravelEpSquareValidityChecker(const Position& pos)
{
return [] (const Move& undoMove, Square epSquare, Piece uncapturedPiece)
{
// TODO: this
return true;
};
}
template <typename FuncT>
struct Permutator
{
const Position& pos;
FixedVector<Piece, 6> lightSquareUncaptures;
FixedVector<Piece, 6> darkSquareUncaptures;
EnumArray<PieceType, bool> isValidLightSquareUnpromotion;
EnumArray<PieceType, bool> isValidDarkSquareUnpromotion;
FuncT&& func;
decltype(makeTimeTravelEpSquareValidityChecker(pos)) isTimeTravelEpSquareValid;
[[nodiscard]] bool canUncapturePawn() const
{
for (Piece p : lightSquareUncaptures)
{
if (p.type() == PieceType::Pawn)
{
return true;
}
}
for (Piece p : darkSquareUncaptures)
{
if (p.type() == PieceType::Pawn)
{
return true;
}
}
return false;
}
void emitPermutations(const Move& move) const
{
const Color sideToUnmove = !pos.sideToMove();
const CastlingRights minCastlingRights = pos.castlingRights();
// Some reverse moves (pawn reverse moves) may add additional
// possible oldEpSquares.
const CandidateEpSquares candidateOldEpSquares =
candidateEpSquaresForReverseMove(pos, sideToUnmove, move);
// When going back in time we may have an option to include more castling rights.
// Note that the castling rights cannot be removed when we go back.
// Also.
// We have to handle two cases. Either this reverse moves uncaptures a rook
// or not. If it uncaptures a rook and it happens that this rook was
// on it's starting position then it may add additional castling rights.
// Otherwise possibleOldCastlingRightsSetIfNotRookUncapture
// == possibleOldCastlingRightsSetIfRookUncapture.
const CastlingRightsByUncapture possibleOldCastlingRights
= updateCastlingRightsForReverseMove(minCastlingRights, pos, sideToUnmove, move);
// At this stage we generate all different castling rights that may be possible.
// Specific castling rights are not dependent on each other so it makes it
// always a power of two sized set of different castling rights.
const auto possibleOldCastlingRightsSetIfNotRookUncapture
= allCastlingRightsBetween(minCastlingRights, possibleOldCastlingRights.ifNotRookUncapture);
const auto possibleOldCastlingRightsSetIfRookUncapture
= allCastlingRightsBetween(minCastlingRights, possibleOldCastlingRights.ifRookUncapture);
const Piece movedPiece = pos.pieceAt(move.to);
const bool isPawnCapture =
movedPiece.type() == PieceType::Pawn
&& move.from.file() != move.to.file();
const bool isPawnPush =
movedPiece.type() == PieceType::Pawn
&& move.from.file() == move.to.file();
// Castlings and pawn pushes are excluded.
// We also have to exclude en-passants.
const bool mayHaveBeenCapture =
move.type != MoveType::EnPassant
&& move.type != MoveType::Castle
&& !isPawnPush;
const auto& uncaptures =
move.to.color() == Color::White
? lightSquareUncaptures
: darkSquareUncaptures;
ReverseMove rm{};
rm.move = move;
if (mayHaveBeenCapture)
{
// Not all squares allow a pawn uncapture.
const bool canBePawnUncapture = !((bb::rank1 | bb::rank8).isSet(move.to));
for (Piece uncapture : uncaptures)
{
if (isPawnCapture && uncapture.type() == PieceType::None)
{
// Pawns must capture
continue;
}
if (!canBePawnUncapture && uncapture.type() == PieceType::Pawn)
{
continue;
}
const auto actualCandidateOldEpSquares = candidateOldEpSquares.forUncapture(uncapture);
const auto& oldCastlingRightsSet =
uncapture.type() == PieceType::Rook
? possibleOldCastlingRightsSetIfRookUncapture
: possibleOldCastlingRightsSetIfNotRookUncapture;
rm.capturedPiece = uncapture;
for (Square candidateOldEpSquare : actualCandidateOldEpSquares)
{
if (!isTimeTravelEpSquareValid(rm.move, candidateOldEpSquare, uncapture))
{
continue;
}
rm.oldEpSquare = candidateOldEpSquare;
for (CastlingRights oldCastlingRights : oldCastlingRightsSet)
{
rm.oldCastlingRights = oldCastlingRights;
func(rm);
}
}
// There's always the possibility that there was no epSquare.
rm.oldEpSquare = Square::none();
for (CastlingRights oldCastlingRights : oldCastlingRightsSet)
{
rm.oldCastlingRights = oldCastlingRights;
func(rm);
}
}
}
else
{
rm.capturedPiece = Piece::none();
// In case of an en-passant there is only one
// possible oldEpSquare, because it was used.
// No need to check anything.
const auto& oldCastlingRightsSet =
possibleOldCastlingRightsSetIfNotRookUncapture;
if (move.type == MoveType::EnPassant)
{
rm.oldEpSquare = candidateOldEpSquares.ifNoUncapture.first();
for (CastlingRights oldCastlingRights : oldCastlingRightsSet)
{
rm.oldCastlingRights = oldCastlingRights;
func(rm);
}
}
else
{
for (Square candidateOldEpSquare : candidateOldEpSquares.ifNoUncapture)
{
if (!isTimeTravelEpSquareValid(rm.move, candidateOldEpSquare, Piece::none()))
{
continue;
}
rm.oldEpSquare = candidateOldEpSquare;
for (CastlingRights oldCastlingRights : oldCastlingRightsSet)
{
rm.oldCastlingRights = oldCastlingRights;
func(rm);
}
}
// If we're reversing a non en-passant move then it's possible
// that there was no epSquare set before the move.
rm.oldEpSquare = Square::none();
for (CastlingRights oldCastlingRights : oldCastlingRightsSet)
{
rm.oldCastlingRights = oldCastlingRights;
func(rm);
}
}
}
}
};
template <typename FuncT>
[[nodiscard]] Permutator<FuncT> makeReverseMovePermutator(
const Position& pos,
const FixedVector<Piece, 6>& lightSquareUncaptures,
const FixedVector<Piece, 6>& darkSquareUncaptures,
EnumArray<PieceType, bool> isValidLightSquareUnpromotion,
EnumArray<PieceType, bool> isValidDarkSquareUnpromotion,
FuncT&& func
)
{
return Permutator<FuncT>{
pos,
lightSquareUncaptures,
darkSquareUncaptures,
isValidLightSquareUnpromotion,
isValidDarkSquareUnpromotion,
std::forward<FuncT>(func),
makeTimeTravelEpSquareValidityChecker(pos)
};
}
template <typename FuncT>
[[nodiscard]] Permutator<FuncT> makeReverseMovePermutator(const Position& pos, const PieceSet& startPieceSet, FuncT&& func)
{
const PieceSet sideToMovePieceSet = PieceSet(pos, pos.sideToMove());
const PieceSet sideToUnmovePieceSet = PieceSet(pos, !pos.sideToMove());
const auto lightSquareUncaptures = startPieceSet.uncaptures(sideToMovePieceSet, pos.sideToMove(), Color::White);
const auto darkSquareUncaptures = startPieceSet.uncaptures(sideToMovePieceSet, pos.sideToMove(), Color::Black);
const auto isLightSquareUnpromotionValid = startPieceSet.unpromotions(sideToUnmovePieceSet, Color::White);
const auto isDarkSquareUnpromotionValid = startPieceSet.unpromotions(sideToUnmovePieceSet, Color::Black);
return makeReverseMovePermutator(
pos,
lightSquareUncaptures,
darkSquareUncaptures,
isLightSquareUnpromotionValid,
isDarkSquareUnpromotionValid,
std::forward<FuncT>(func)
);
}
template <typename FuncT>
[[nodiscard]] Permutator<FuncT> makeReverseMovePermutator(const Position& pos, FuncT&& func)
{
const auto lightSquareUncaptures = PieceSetMask::allUncaptures();
const auto darkSquareUncaptures = PieceSetMask::allUncaptures();
const auto isLightSquareUnpromotionValid = PieceSetMask::allUnpromotions();
const auto isDarkSquareUnpromotionValid = PieceSetMask::allUnpromotions();
return makeReverseMovePermutator(
pos,
lightSquareUncaptures,
darkSquareUncaptures,
isLightSquareUnpromotionValid,
isDarkSquareUnpromotionValid,
std::forward<FuncT>(func)
);
}
}
template <typename FuncT>
void forEachPseudoLegalPawnNormalReverseMove(
const Position& pos,
FuncT&& func
)
{
constexpr Bitboard whiteSingleUnpushPawnsMask =
bb::rank3 | bb::rank4 | bb::rank5 | bb::rank6 | bb::rank7;
constexpr Bitboard blackSingleUnpushPawnsMask =
bb::rank2 | bb::rank3 | bb::rank4 | bb::rank5 | bb::rank6;
constexpr Bitboard whiteDoubleUnpushPawnsMask = bb::rank4;
constexpr Bitboard blackDoubleUnpushPawnsMask = bb::rank5;
const Color sideToUnmove = !pos.sideToMove();
const int forward =
sideToUnmove == Color::White
? 1
: -1;
// pushes
const FlatSquareOffset singlePawnUnpush = FlatSquareOffset(0, -forward);
const FlatSquareOffset doublePawnUnpush = FlatSquareOffset(0, -forward * 2);
if (pos.epSquare() != Square::none())
{
// The move must have been a double pawn push.
const Square from = pos.epSquare() + singlePawnUnpush;
const Square to = pos.epSquare() + -singlePawnUnpush;
const Move move = Move::normal(from, to);
func(move);
return;
}
const Bitboard singleUnpushPawnsMask =
sideToUnmove == Color::White
? whiteSingleUnpushPawnsMask
: blackSingleUnpushPawnsMask;
const Bitboard doubleUnpushPawnsMask =
sideToUnmove == Color::White
? whiteDoubleUnpushPawnsMask
: blackDoubleUnpushPawnsMask;
const Bitboard pieces = pos.piecesBB();
const Bitboard pawns = pos.piecesBB(Piece(PieceType::Pawn, sideToUnmove));
const Bitboard singleUnpushablePawns =
pawns
& ~pieces.shiftedVertically(forward)
& singleUnpushPawnsMask;
const Bitboard doubleUnpushablePawns =
singleUnpushablePawns
& ~pieces.shiftedVertically(forward * 2)
& doubleUnpushPawnsMask;
for (Square to : singleUnpushablePawns)
{
const Square from = to + singlePawnUnpush;
const Move move = Move::normal(from, to);
func(move);
}
for (Square to : doubleUnpushablePawns)
{
const Square from = to + doublePawnUnpush;
const Move move = Move::normal(from, to);
func(move);
}
// captures
const Offset eastCapture = Offset(1, forward);
const Offset westCapture = Offset(-1, forward);
const FlatSquareOffset eastUncapture = (-eastCapture).flat();
const FlatSquareOffset westUncapture = (-westCapture).flat();
const Bitboard pawnsThatMayHaveCaptured =
pawns
& singleUnpushPawnsMask;
const Bitboard pawnsThatMayHaveCapturedEast =
pawnsThatMayHaveCaptured
& ~pieces.shifted(eastCapture);
const Bitboard pawnsThatMayHaveCapturedWest =
pawnsThatMayHaveCaptured
& ~pieces.shifted(westCapture);
for (Square to : pawnsThatMayHaveCapturedEast)
{
const Square from = to + eastUncapture;
const Move move = Move::normal(from, to);
func(move);
}
for (Square to : pawnsThatMayHaveCapturedWest)
{
const Square from = to + westUncapture;
const Move move = Move::normal(from, to);
func(move);
}
}
template <typename FuncT>
void forEachPseudoLegalPawnPromotionReverseMove(
const Position& pos,
const EnumArray<PieceType, bool>& isValidLightSquareUnpromotion,
const EnumArray<PieceType, bool>& isValidDarkSquareUnpromotion,
FuncT&& func
)
{
if (pos.epSquare() != Square::none())
{
return;
}
const Color sideToUnmove = !pos.sideToMove();
const int forward =
sideToUnmove == Color::White
? 1
: -1;
const FlatSquareOffset singlePawnUnpush = FlatSquareOffset(0, -forward);
const Bitboard promotionRank =
sideToUnmove == Color::White
? bb::rank8
: bb::rank1;
const Bitboard piecesOnPromotionRank = pos.piecesBB(sideToUnmove) & promotionRank;
Bitboard promotionTargets = Bitboard::none();
for (Square sq : piecesOnPromotionRank)
{
const Color sqColor = sq.color();
const PieceType pt = pos.pieceAt(sq).type();
if (
(sqColor == Color::White && isValidLightSquareUnpromotion[pt])
|| (sqColor == Color::Black && isValidDarkSquareUnpromotion[pt])
)
{
promotionTargets |= sq;
}
}
const Bitboard pieces = pos.piecesBB();
// pushes
const Bitboard pushUnpromotions =
promotionTargets
& ~pieces.shiftedVertically(forward);
for (Square to : pushUnpromotions)
{
const Piece piece = pos.pieceAt(to);
const Square from = to + singlePawnUnpush;
const Move move = Move::promotion(from, to, piece);
func(move);
}
// captures
const Offset eastCapture = Offset(1, forward);
const Offset westCapture = Offset(-1, forward);
const FlatSquareOffset eastUncapture = (-eastCapture).flat();
const FlatSquareOffset westUncapture = (-westCapture).flat();
const Bitboard eastCapturePromotions =
promotionTargets
& ~pieces.shifted(eastCapture);
const Bitboard westCapturePromotions =
promotionTargets
& ~pieces.shifted(westCapture);
for (Square to : eastCapturePromotions)
{
const Piece piece = pos.pieceAt(to);
const Square from = to + eastUncapture;
const Move move = Move::promotion(from, to, piece);
func(move);
}
for (Square to : westCapturePromotions)
{
const Piece piece = pos.pieceAt(to);
const Square from = to + westUncapture;
const Move move = Move::promotion(from, to, piece);
func(move);
}
}
template <typename FuncT>
void forEachPseudoLegalPawnEnPassantReverseMove(
const Position& pos,
FuncT&& func
)
{
if (pos.epSquare() != Square::none())
{
return;
}
const Color sideToUnmove = !pos.sideToMove();
const int forward =
sideToUnmove == Color::White
? 1
: -1;
const Bitboard epSquareRank =
sideToUnmove == Color::White
? bb::rank6
: bb::rank3;
const Bitboard pieces = pos.piecesBB();
const Bitboard pawns = pos.piecesBB(Piece(PieceType::Pawn, sideToUnmove));
const Bitboard pawnsThatMayHaveCapturedEnPassant =
pawns
& epSquareRank
& ~pieces.shiftedVertically(1) // the square above and below the ep square has to be empty
& ~pieces.shiftedVertically(-1);
if (pawnsThatMayHaveCapturedEnPassant.isEmpty())
{
return;
}
const Offset eastCapture = Offset(1, forward);
const Offset westCapture = Offset(-1, forward);
const FlatSquareOffset eastUncapture = (-eastCapture).flat();
const FlatSquareOffset westUncapture = (-westCapture).flat();
const Bitboard pawnsThatMayHaveCapturedEastEnPassant =
pawnsThatMayHaveCapturedEnPassant
& ~pieces.shifted(eastCapture);
const Bitboard pawnsThatMayHaveCapturedWestEnPassant =
pawnsThatMayHaveCapturedEnPassant
& ~pieces.shifted(westCapture);
for (Square to : pawnsThatMayHaveCapturedEastEnPassant)
{
const Square from = to + eastUncapture;
const Move move = Move::enPassant(from, to);
func(move);
}
for (Square to : pawnsThatMayHaveCapturedWestEnPassant)
{
const Square from = to + westUncapture;
const Move move = Move::enPassant(from, to);
func(move);
}
}
template <PieceType PieceTypeV, typename FuncT>
void forEachPseudoLegalPieceReverseMove(
const Position& pos,
FuncT&& func
)
{
static_assert(PieceTypeV != PieceType::None);
static_assert(PieceTypeV != PieceType::Pawn);
if (pos.epSquare() != Square::none())
{
return;
}
const Color sideToUnmove = !pos.sideToMove();
const Bitboard ourPieces = pos.piecesBB(sideToUnmove);
const Bitboard theirPieces = pos.piecesBB(!sideToUnmove);
const Bitboard occupied = ourPieces | theirPieces;
const Bitboard pieces = pos.piecesBB(Piece(PieceTypeV, sideToUnmove));
for (Square to : pieces)
{
const Bitboard attacks = bb::attacks<PieceTypeV>(to, occupied) & ~ourPieces;
for (Square from : attacks)
{
Move move = Move::normal(from, to);
func(move);
}
}
}
template <typename FuncT>
void forEachPseudoLegalPawnReverseMove(detail::Permutator<FuncT>& permutator)
{
auto fwd = [&permutator](const Move& m) { permutator.emitPermutations(m); };
forEachPseudoLegalPawnNormalReverseMove(
permutator.pos,
fwd
);
forEachPseudoLegalPawnPromotionReverseMove(
permutator.pos,
permutator.isValidLightSquareUnpromotion,
permutator.isValidDarkSquareUnpromotion,
fwd
);
if (permutator.canUncapturePawn())
{
forEachPseudoLegalPawnEnPassantReverseMove(
permutator.pos,
fwd
);
}
forEachPseudoLegalPieceReverseMove<PieceType::Knight>(permutator.pos, fwd);
forEachPseudoLegalPieceReverseMove<PieceType::Bishop>(permutator.pos, fwd);
forEachPseudoLegalPieceReverseMove<PieceType::Rook>(permutator.pos, fwd);
forEachPseudoLegalPieceReverseMove<PieceType::Queen>(permutator.pos, fwd);
forEachPseudoLegalPieceReverseMove<PieceType::King>(permutator.pos, fwd);
// TODO: Generate reverse castling moves.
}
template <typename FuncT>
void forEachPseudoLegalReverseMove(detail::Permutator<FuncT>& permutator)
{
forEachPseudoLegalPawnReverseMove(permutator);
}
// NOTE: currently doesn't generate reverse castling moves and doesn't
// check if old en-passant square was possible.
template <typename FuncT>
void forEachPseudoLegalReverseMove(const Position& pos, const PieceSet& startPieceSet, FuncT&& func)
{
auto permutator = detail::makeReverseMovePermutator(pos, startPieceSet, std::forward<FuncT>(func));
forEachPseudoLegalReverseMove(permutator);
}
// NOTE: currently doesn't generate reverse castling moves and doesn't
// check if old en-passant square was possible.
template <typename FuncT>
void forEachPseudoLegalReverseMove(const Position& pos, FuncT&& func)
{
auto permutator = detail::makeReverseMovePermutator(pos, std::forward<FuncT>(func));
forEachPseudoLegalReverseMove(permutator);
}
}
| true |
7583ac84b7390779b09544dae29c3a4f470a15fc | C++ | N-Magi/ArduinoWriter | /include/eeprom.h | UTF-8 | 390 | 2.53125 | 3 | [
"MIT"
] | permissive | #include <Arduino.h>
#include <Wire.h>
class eeprom
{
private:
/* data */
public:
eeprom(/* args */);
void WriteByte(uint16_t addr,uint8_t data);
bool WritePage(uint16_t addr,uint8_t* data);
uint8_t ReadByte(uint16_t addr);
uint8_t* ReadBytes(uint16_t addr, int size);
~eeprom();
};
eeprom::eeprom(/* args */)
{
}
eeprom::~eeprom()
{
}
| true |
6bb14e5eeb79f86d12e14e681befe33d4f64f62d | C++ | cheon7886/ArduinoBox | /examples/Rokit/Hunoi/Apps/WalkFish/WalkFish.ino | UTF-8 | 1,378 | 2.703125 | 3 | [] | no_license |
#include <Servo.h>
#define LedPin_01 8
#define LedPin_02 9
#define LedPin_03 10
int light = 0;
int wait = 120;
Servo servo1;
Servo servo2;
void setup() {
pinMode(LedPin_01, OUTPUT);
pinMode(LedPin_02, OUTPUT);
pinMode(LedPin_03, OUTPUT);
pinMode(24, INPUT_PULLUP);
servo1.attach(16); // attaches the servo on pin 16 to the servo object
servo2.attach(17); // attaches the servo on pin 17 to the servo object
}
void loop() {
// put your main code here, to run repeatedly:
if(light==1)
{
digitalWrite(LedPin_01, HIGH);
digitalWrite(LedPin_02, LOW);
digitalWrite(LedPin_03, LOW);
}
else if(light==2)
{
digitalWrite(LedPin_01, LOW);
digitalWrite(LedPin_02, HIGH);
digitalWrite(LedPin_03, LOW);
}
else if(light==3)
{
digitalWrite(LedPin_01, LOW);
digitalWrite(LedPin_02, LOW);
digitalWrite(LedPin_03, HIGH);
}
else
{
light=0;
digitalWrite(LedPin_01, LOW);
digitalWrite(LedPin_02, LOW);
digitalWrite(LedPin_03, LOW);
}
light=light+1;
if (digitalRead(24) == HIGH)
{
servo1.write(110);
servo2.write(115);
delay(wait);
servo1.write(70);
servo2.write(115);
delay(wait);
servo1.write(70);
servo2.write(65);
delay(wait);
servo1.write(110);
servo2.write(65);
delay(wait);
}
}
| true |
df6b3d6e5144805013a61d9f9005cbd260a5c02c | C++ | WillGetDream/ParticleLinked | /mainWithoutwindow.cpp | UTF-8 | 2,829 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <assert.h>
#include <time.h>
static void DRAW(float x, float y) {
}
class Particle
{
public:
Particle* getNext() const { return state_.next; }
void setNext(Particle* next) { state_.next = next; }
Particle()
: framesLeft_(0)
{}
bool draw();
void init(double x, double y,
double xVel, double yVel, int lifetime)
{
x = x; y = y;
vx = xVel; vy = yVel;
framesLeft_ = lifetime;
}
bool inUse() const { return framesLeft_ > 0; }
private:
int framesLeft_;
double x, y;
double vx, vy;
union
{
// State when it's in use.
struct
{
double x, y;
double xVel, yVel;
} live;
// State when it's available.
Particle* next;
} state_;
};
bool Particle::draw()
{
if (!inUse()) return false;
framesLeft_--;
x += vx;
y += vy;
DRAW(x, y);
printf("\n[p %f %f]", x, y);
return framesLeft_ == 0;
}
class ParticlePool
{
public:
void create(double x, double y,
double xVel, double yVel,
int lifetime);
ParticlePool();
void draw();
private:
static const int POOL_SIZE = 100;
Particle particles_[POOL_SIZE];
Particle* firstAvailable_;
};
ParticlePool::ParticlePool()
{
// The first one is available.
firstAvailable_ = &particles_[0];
// Each particle points to the next.
for (int i = 0; i < POOL_SIZE - 1; i++)
{
particles_[i].setNext(&particles_[i + 1]);
}
// The last one terminates the list.
particles_[POOL_SIZE - 1].setNext(NULL);
}
void ParticlePool::create(double x, double y,
double xVel, double yVel,
int lifetime)
{
// Make sure the pool isn't full.
assert(firstAvailable_ != NULL);
// Remove it from the available list.
Particle* newParticle = firstAvailable_;
firstAvailable_ = newParticle->getNext();
newParticle->init(x, y, xVel, yVel, lifetime);
}
void ParticlePool::draw()
{
for (int i = 0; i < POOL_SIZE; i++)
{
if (particles_[i].draw())
{
// Add this particle to the front of the list.
particles_[i].setNext(firstAvailable_);
firstAvailable_ = &particles_[i];
}
}
}
int main() {
srand(static_cast<unsigned int>(time(0)));
int FRAMES=10;
ParticlePool *ps=new ParticlePool();
ps->create(0,0,rand()%9+1,rand()%9+1,10);
for (int i = 0; i < FRAMES; i++) {
printf("\n\n[FRAME %d]", i);
ps->draw();
ps->create(0, 0, rand()%9+1, rand()%9+1, 5);
ps->create(0, 0, rand()%9+1, rand()%9+1, 5);
}
return 0;
}
| true |
f10844a6373877eb5e74de91fc4cfd83930f286c | C++ | carsongmiller/orbit | /orbit/util.h | UTF-8 | 1,045 | 2.890625 | 3 | [] | no_license | #ifndef UTIL_H
#define UTIL_H
class Star;
class Galaxy;
//converts a radian value to degrees
double rad_to_deg(double r);
//converts a degree value to radians
double deg_to_rad(double d);
//returns a double between low and high
//if neg = true, returned value has 50% chance to be negative
double randBound(double low, double high, bool neg);
//normalizes a vector of arbitrary length
std::vector<double> normalize(std::vector<double> v);
//performs matrix multiplication A x B, stores in C
void matrixMult4x1(double A[4][4], double B[4], double C[4]);
//performs matrix multiplication A x B, stores in C
void matrixMult4x4(double A[4][4], double B[4][4], double C[4][4]);
//inverts a 4x4 matrix m, stores in inverse
//returns true if inversion is possible, false otherwise
bool invertMatrix4x4(double m[4][4], double inverse[4][4]);
//returns true if s is within the render boundary, false otherwise
bool shouldRender(Star s);
//returns true if g is within the render boundary, false otherwise
bool shouldRender(Galaxy g);
#endif | true |
e44da5a260b63135d8bc0589ecf806adf1c8aae3 | C++ | Kuree/hermes | /src/process.hh | UTF-8 | 3,295 | 3.09375 | 3 | [] | no_license | #ifndef HERMES_PROCESS_HH
#define HERMES_PROCESS_HH
#include <condition_variable>
#include <cstdio>
#include <functional>
#include <future>
#include <memory>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <utility>
#include <vector>
// forward declare
namespace subprocess {
class Popen;
}
namespace hermes {
class Process {
public:
explicit Process(const std::vector<std::string> &commands);
Process(const std::vector<std::string> &commands, const std::string &cwd);
void wait();
~Process();
private:
std::unique_ptr<subprocess::Popen> process_;
};
class Dispatcher {
public:
void dispatch(const std::function<void()> &task);
static Dispatcher *get_default_dispatcher() {
static Dispatcher instance;
return &instance;
}
void finish();
~Dispatcher() { finish(); }
private:
std::mutex threads_lock_;
std::queue<std::thread> threads_;
void clean_up();
};
// code from https://github.com/progschj/ThreadPool
class ThreadPool {
public:
explicit ThreadPool(size_t);
template <class F, class... Args>
auto enqueue(F &&f, Args &&...args) -> std::future<typename std::result_of<F(Args...)>::type>;
~ThreadPool();
private:
// need to keep track of threads so we can join them
std::vector<std::thread> workers;
// the task queue
std::queue<std::function<void()> > tasks;
// synchronization
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
// the constructor just launches some amount of workers
inline ThreadPool::ThreadPool(size_t threads) : stop(false) {
for (size_t i = 0; i < threads; ++i)
workers.emplace_back([this] {
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock,
[this] { return this->stop || !this->tasks.empty(); });
if (this->stop && this->tasks.empty()) return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
});
}
// add new work item to the pool
template <class F, class... Args>
auto ThreadPool::enqueue(F &&f, Args &&...args)
-> std::future<typename std::result_of<F(Args...)>::type> {
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared<std::packaged_task<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...));
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
// don't allow enqueueing after stopping the pool
if (stop) throw std::runtime_error("enqueue on stopped ThreadPool");
tasks.emplace([task]() { (*task)(); });
}
condition.notify_one();
return res;
}
// the destructor joins all threads
inline ThreadPool::~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (std::thread &worker : workers) worker.join();
}
} // namespace hermes
#endif // HERMES_PROCESS_HH
| true |
6f7410d901941c5f34495db6fcaabab04a4f1730 | C++ | Makaronodentro/imperial | /cracking_the_coding_interview/2_linked_lists/lists.h | UTF-8 | 932 | 3.765625 | 4 | [] | no_license | #ifndef LISTS_H
#define LISTS_H
#include <iostream>
template <typename T>
struct Node{
Node* next;
T x;
};
template <typename T>
class SinglyLinkedList {
private:
Node<T>* root;
public:
SinglyLinkedList(T _x){
root = new Node<T>;
root->next = NULL;
root->x = _x;
last = root;
}
~SinglyLinkedList(){
Node<T>* tbd = root; // To Be Deleted
Node<T>* tmp;
while(tbd){
tmp = tbd->next;
delete tbd;
tbd = tmp->next;
}
delete root;
}
void addFront(T x){
// Allocate memory
Node<T>* tmp = new Node;
// Make the new node point to root
tmp->next = root;
// Set new root
root = tmp;
}
void traverse(){
Node<T>* tmp = root;
while(tmp){
std::cout<<tmp->x<<std::endl;
tmp = tmp->next;
}
}
T getX(){
return root->x;
}
};
#endif
| true |
d65ccfbcca8502363cf75b9a86b2c890c7928498 | C++ | SaberDa/LeetCode | /C++/390-eliminationGame.cpp | UTF-8 | 342 | 2.59375 | 3 | [] | no_license | class Solution {
public:
int lastRemaining(int n) {
int res = 1, distance = 1;
while (distance * 2 <= n) {
res += distance;
distance *= 2;
if (distance * 2 > n) break;
if ((n / distance) % 2) res += distance;
distance *= 2;
}
return res;
}
}; | true |
284df2103fab53c41e888841d37649bcbb8cb573 | C++ | juanpa1220/AlgoritmosDeBusqueda | /busquedas/main.cpp | UTF-8 | 1,490 | 3.8125 | 4 | [] | no_license | #include <iostream>
#include "BusquedaSecuencial.cpp"
#include "BusquedaBinaria.cpp"
#include "BusquedaDeInterpolacion.cpp"
using namespace std;
int main() {
int arr[10];
int num;
// recibe 10 numeros que forman el array
cout << "Ingrese 10 numeros enteros en orden ascendente\n";
for (int i = 0; i < 10; i++) {
cout << "Elemento " << i + 1 << ": ";
int j;
cin >> j;
arr[i] = j;
}
// recibe el numero que se desea buscar
cout << "Ingrese un numero que desee buscar entre los numeros accedidos: ";
cin >> num;
// busqueda secuencial
BusquedaSecuencial b1 = BusquedaSecuencial(arr, num);
if (b1.busquedaSecuencial()) {
cout << "El numero fue encontrado mediante busqueda secuencial\n";
} else {
cout << "El numero no fue encontrado mediante busqueda secuencial\n";
}
// busqueda binaria
BusquedaBinaria b2 = BusquedaBinaria(arr, num);
if (b2.busquedaBinaria()) {
cout << "El numero fue encontrado mediante busqueda binaria\n";
} else {
cout << "El numero no fue encontrado mediante busqueda binaria\n";
}
// busqueda de interpolacion
BusquedaDeInterpolacion b3 = BusquedaDeInterpolacion(arr, num);
if (b2.busquedaBinaria()) {
cout << "El numero fue encontrado mediante busqueda de interpolacion\n";
} else {
cout << "El numero no fue encontrado mediante busqueda de interpolacion\n";
}
return 0;
}
| true |
e7fae9f1c8334973405c7a8f35a26398d75ca504 | C++ | denniskb/merge_fusion | /KinectFission/kifi/util/algorithm.h | UTF-8 | 3,929 | 2.625 | 3 | [] | no_license | #pragma once
namespace kifi {
namespace util {
// TODO: Change interface to ptr, size
template< typename T >
void radix_sort
(
T * first, T * last,
void * scratchPad
);
template< typename T, typename U >
void radix_sort
(
T * keys_first, T * keys_last,
U * values_first,
void * scratchPad
);
template
<
class InputIterator1, class InputIterator2,
class InputIterator3, class InputIterator4,
class OutputIterator1, class OutputIterator2
>
OutputIterator1 set_union
(
InputIterator1 keys_first1, InputIterator1 keys_last1,
InputIterator2 keys_first2, InputIterator2 keys_last2,
InputIterator3 values_first1,
InputIterator4 values_first2,
OutputIterator1 keys_result,
OutputIterator2 values_result
);
}} // namespace
#pragma region Implementation
#include <cstddef>
#include <cstring>
#include <utility>
#include <kifi/util/numeric.h>
namespace kifi {
namespace util {
template< typename T >
void radix_sort
(
T * first, T * last,
void * scratchPad
)
{
using std::swap;
int cnt[ 256 ];
T * tmp = reinterpret_cast< T * >( scratchPad );
for( int shift = 0; shift != 32; shift += 8 )
{
std::memset( cnt, 0, sizeof( cnt ) );
for( T * it = first; it != last; ++it )
++cnt[ ( * it >> shift ) & 0xff ];
partial_sum_exclusive( cnt, cnt + 256, cnt );
for( T * it = first; it != last; ++it )
tmp[ cnt[ ( * it >> shift ) & 0xff ]++ ] = * it;
last = tmp + ( last - first );
swap( first, tmp );
}
}
template< typename T, typename U >
void radix_sort
(
T * keys_first, T * keys_last,
U * values_first,
void * scratchPad
)
{
using std::swap;
int cnt[ 256 ];
T * keys_tmp = reinterpret_cast< T * >( scratchPad );
U * values_tmp = reinterpret_cast< U * >( keys_tmp + (keys_last - keys_first) );
for( int shift = 0; shift != 32; shift += 8 )
{
std::memset( cnt, 0, sizeof( cnt ) );
for( auto it = keys_first; it != keys_last; ++it )
++cnt[ ( * it >> shift ) & 0xff ];
partial_sum_exclusive( cnt, cnt + 256, cnt );
for
(
auto it = std::make_pair( keys_first, values_first );
it.first != keys_last;
++it.first, ++it.second
)
{
std::size_t idst = cnt[ ( * it.first >> shift ) & 0xff ]++;
keys_tmp[ idst ] = * it.first;
values_tmp[ idst ] = * it.second;
}
keys_last = keys_tmp + ( keys_last - keys_first );
swap( keys_first, keys_tmp );
swap( values_first, values_tmp );
}
}
template
<
class InputIterator1, class InputIterator2,
class InputIterator3, class InputIterator4,
class OutputIterator1, class OutputIterator2
>
OutputIterator1 set_union
(
InputIterator1 keys_first1, InputIterator1 keys_last1,
InputIterator2 keys_first2, InputIterator2 keys_last2,
InputIterator3 values_first1,
InputIterator4 values_first2,
OutputIterator1 keys_result,
OutputIterator2 values_result
)
{
while( keys_first1 != keys_last1 && keys_first2 != keys_last2 )
if( * keys_first1 < * keys_first2 )
{
* keys_result++ = * keys_first1;
* values_result++ = * values_first1;
++keys_first1;
++values_first1;
}
else if( * keys_first2 < * keys_first1 )
{
* keys_result++ = * keys_first2;
* values_result++ = * values_first2;
++keys_first2;
++values_first2;
}
else
{
* keys_result++ = * keys_first1;
* values_result++ = * values_first1;
++keys_first1;
++keys_first2;
++values_first1;
++values_first2;
}
// TODO: Replace while loops with std::copy calls
while( keys_first1 != keys_last1 )
{
* keys_result++ = * keys_first1++;
* values_result++ = * values_first1++;
}
while( keys_first2 != keys_last2 )
{
* keys_result++ = * keys_first2++;
* values_result++ = * values_first2++;
}
return keys_result;
}
}} // namespaces
#pragma endregion | true |
082851c39fecf22e621b8fd9d2d3784971514bbe | C++ | AbdulMajeedkhurasani/OpenGL_Learning | /Instancing.cpp | UTF-8 | 4,960 | 2.546875 | 3 | [] | no_license | #include <glad/glad.h>
#include <GLFW/glfw3.h>
#include "Shaders/Shader2.h"
#include <bits/stdc++.h>
using namespace std;
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);
GLFWwindow* initialize();
// settings
const unsigned int SCR_WIDTH = 1366;
const unsigned int SCR_HEIGHT = 768;
int main()
{
GLFWwindow* window = initialize();
// configure global opengl state
float quadVertices[] = {
// positions // colors
-0.05f, 0.05f, 1.0f, 0.0f, 0.0f,
0.05f, -0.05f, 0.0f, 1.0f, 0.0f,
-0.05f, -0.05f, 0.0f, 0.0f, 1.0f,
-0.05f, 0.05f, 1.0f, 0.0f, 0.0f,
0.05f, -0.05f, 0.0f, 1.0f, 0.0f,
0.05f, 0.05f, 0.0f, 1.0f, 1.0f,
};
Shader shader("Shaders/instancing.vs", "Shaders/instancing.fs");
glm::vec2 translations[100];
int index = 0 ;
float offset = 0.1f;
for (int y = -10; y < 10; y += 2)
{
for (int x = -10; x < 10; x += 2)
{
glm::vec2 translation;
translation.x = (float)x / 10.0f + offset;
translation.y = (float)y / 10.0f + offset;
translations[index++] = translation;
}
}
unsigned int instancedVBO;
glGenBuffers(1, &instancedVBO);
glBindBuffer(GL_ARRAY_BUFFER, instancedVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2) * 100, &translations[0], GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
unsigned int VAO, VBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 5* sizeof(float), (void *)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 5* sizeof(float), (void *) (2 * sizeof(float)));
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, instancedVBO);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), (void*)0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glVertexAttribDivisor(2,1); //telling OpenGL that the vertex attribute at attribute location 2 is an instanced array
glBindVertexArray(0);
/*shader.use();
for(int i = 0; i < 100; i++)
{
shader.setVec2(("offsets[" + std::to_string(i) + "]"), translations[i]);
}*/
while (!glfwWindowShouldClose(window))
{
// input
processInput(window);
// render
glClearColor(0.1f,0.1f,0.1f,1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shader.use();
glBindVertexArray(VAO);
glDrawArraysInstanced(GL_TRIANGLES, 0, 6, 100);
glfwSwapBuffers(window);
glfwPollEvents();
}
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glfwTerminate();
return 0;
}
GLFWwindow* initialize(){
// glfw: initialize and configure
// ------------------------------
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
// glfw window creation
// --------------------
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", glfwGetPrimaryMonitor(), NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// tell GLFW to capture our mouse
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
// glad: load all OpenGL function pointers
// ---------------------------------------
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
}
return window;
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}
| true |
1d468ca41744d6482948eceb99f0e84a5f4fc1f7 | C++ | OnyxKnight/Labs | /1021Lab/lab9/money.cpp | UTF-8 | 1,436 | 3.46875 | 3 | [] | no_license | /*************************
*Joseph Barton
*CPSC 1021-004, F16
*Lab 9
*jbarto3
**************************/
#include <iostream>
#include "money.h"
using namespace std;
// default constructor
money_t::money_t()
{
dollars = cents = 0;
}
// Regular constructor
money_t::money_t(double amt)
{
if (amt < 0)
dollars = cents = 0;
else
{
set_dollars(static_cast<int>(amt));
set_cents(static_cast<int>(amt*100) % 100);
}
}
money_t::money_t(int d, int c)
{
if (dollars < 0)
set_dollars(0);
else
set_dollars(d);
if(cents < 0)
set_cents(0);
else
set_cents(c);
}
//Destructor
money_t::~money_t()
{
cout << "Destructor invoked" << endl;
}
int money_t::get_dollars()
{
return dollars;
}
int money_t::get_cents()
{
return cents;
}
void money_t::set_dollars(int amount)
{
dollars = amount;
}
void money_t::set_cents(int amount)
{
cents = amount;
}
//set both values dollars and cents
void money_t::set(int d, int c)
{
money_t::set_dollars(d);
money_t::set_cents(c);
}
//fine total value in cents
int money_t::value_in_cents()
{
int total;
total = get_dollars() * 100;
total += get_cents();
return total;
}
//convert from int to double and find total value
double money_t::compute_value()
{
double value;
value = static_cast<double>(dollars)*100+cents;
value = value / 100;
return value;
}
| true |
b609f6a5cacde04249572eb3d7517c22be1657ce | C++ | FlashPanda/c_cpp | /directory.cpp | UTF-8 | 630 | 3.375 | 3 | [] | no_license | #include <unistd.h>
#include <iostream>
int main () {
char dir_name[] = "/tmp/this/is/a/test";
int result = access (dir_name, 0);
std::cout << "判断的目录:" << dir_name << std::endl;
if (result == 0)
std::cout << "目录存在,result的值为0" << std::endl;
else
std::cout << "目录不存在,result的值为-1" << std::endl;
char dir_name1[] = "/tmp";
result = access (dir_name1, 0);
std::cout << "判断的目录:" << dir_name1 << std::endl;
if (result == 0)
std::cout << "目录存在,result的值为0" << std::endl;
else
std::cout << "目录不存在,result的值为-1" << std::endl;
}
| true |
97fb4cba3c7871c83325560336df2ad3a3bcd031 | C++ | cskilbeck/MakeTheWords | /Source/Base/ScopedObject.h | UTF-8 | 716 | 3.140625 | 3 | [] | no_license | //////////////////////////////////////////////////////////////////////
#pragma once
//////////////////////////////////////////////////////////////////////
template<typename T> struct ScopedObject
{
explicit ScopedObject(T *p = 0)
: mPointer(p)
{
}
~ScopedObject()
{
SafeRelease(mPointer);
}
bool IsNull() const
{
return mPointer == null;
}
T &operator *()
{
return *mPointer;
}
T *operator->()
{
return mPointer;
}
T **operator&()
{
return &mPointer;
}
void Reset(T *p = 0)
{
SafeRelease(mPointer);
mPointer = p;
}
T* Get() const
{
return mPointer;
}
private:
ScopedObject(const ScopedObject&);
ScopedObject& operator=(const ScopedObject&);
T *mPointer;
};
| true |
3b9f4c4f111565b362157985b45d7dbe9d1e2a8b | C++ | SDG98/Capstone-Graphics | /PizzaBox/Animation/AnimEngine.cpp | UTF-8 | 673 | 2.609375 | 3 | [] | no_license | #include "AnimEngine.h"
#include <algorithm>
using namespace PizzaBox;
std::vector<Animator*> AnimEngine::animators;
bool AnimEngine::Initialize(){
return true;
}
void AnimEngine::Destroy(){
animators.clear();
animators.shrink_to_fit();
}
void AnimEngine::Update(float deltaTime_){
for(auto& animator : animators){
animator->Update(deltaTime_);
}
}
void AnimEngine::RegisterAnimator(Animator* animator_){
_ASSERT(animator_ != nullptr);
animators.push_back(animator_);
}
void AnimEngine::UnregisterAnimator(Animator* animator_){
_ASSERT(animator_ != nullptr);
animators.erase(std::remove(animators.begin(), animators.end(), animator_), animators.end());
} | true |
27084b6a981f7edefb581f8fb151b2cb6b3c6bd1 | C++ | warvair/bulletscript | /include/bsEmitterDefinition.h | UTF-8 | 2,470 | 2.90625 | 3 | [] | no_license | /*
BulletScript: a script for firing bullets.
See /doc/license.txt for license details.
*/
#ifndef __BS_EMITTERDEFINITION_H__
#define __BS_EMITTERDEFINITION_H__
#include <vector>
#include "bsPrerequisites.h"
#include "bsObjectDefinition.h"
#include "bsAffector.h"
namespace BS_NMSP
{
class ParseTreeNode;
/** \brief Class to store a definition for instantiating Emitter objects.
*
* EmitterDefinitions are created from scripts, and contain the information needed
* to set up Emitter.
*/
class _BSAPI EmitterDefinition : public ObjectDefinition
{
public:
/** \brief Function compile information
*/
struct Function
{
//! function name
String name;
//! number of arguments
int numArguments;
//! ParseTreeNode object to speed up compilation
ParseTreeNode* node;
};
public:
/** \brief Constructor.
* \param name name of the definition, generally set from script.
*/
explicit EmitterDefinition(const String& name);
/** \brief Set index.
*
* This is an internal method used by code generation.
*
* \param index EmitterDefinition index.
*/
void _setIndex(int index);
/** \brief Get index.
*
* This is an internal method used by code generation.
*
* \return EmitterDefinition index in virtual machine.
*/
int _getIndex() const;
/** \brief Add a function definition.
*
* \param name name of the function.
* \param node a pointer to the ParseTreeNode, for quick access during code generation.
* \return reference to the function definition.
*/
Function& addFunction(const String& name, ParseTreeNode* node);
/** \brief Get a function definition.
*
* \param index index of the function.
* \return reference to the function definition.
*/
Function& getFunction(int index);
/** \brief Get a function definition index.
*
* This is used in conjunction with getFunction to retrieve a function definition by name.
*
* \param name name of the function.
* \return reference to the function definition.
*/
int getFunctionIndex(const String& name) const;
/** \brief Gets the number of function definitions in this EmitterDefinition.
*
* \return number of function definitions.
*/
int getNumFunctions() const;
private:
int mIndex;
// Functions
std::vector<Function> mFunctions;
};
}
#endif
| true |
4c3c83edfec22101c05691632f7f24e23c94b561 | C++ | yuanyiyixi/C-- | /file/ex.cpp | UTF-8 | 534 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
int main()
{
char buf[256];
ifstream examplefile ("example.txt");
if (!examplefile.is_open())
{
cout << "Error opening file" << endl;
exit (1);
}
while(!examplefile.eof())//eof()会多读一次
//while(examplefile.peek() != EOF)//peek()不会多读
{
examplefile.getline (buf, 100);
if (examplefile.good())
cout << buf << endl;
// cout << "read byte:" << examplefile.gcount() << endl;
// cout << "=========" << endl;
}
return 0;
}
| true |
c043c2d990ad61434b6d7c6ac162337c380d428e | C++ | Dragon2050/All-Code | /modular multiplicative inverse update.cpp | UTF-8 | 993 | 3.5625 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int x;
int check_prime(int mod)
{
int check=0;
int root=sqrt(mod)+1;
for(int i=2;i<=root;i++)
{
if(mod%i==0)
{
check=1;
break;
}
}
return check;
}
int bigmod(int number,int power,int mod)
{
if(power==0)
return 1%mod;
x=bigmod(number,power/2,mod);
x=(x*x)%mod;
if(power%2==1)
x=(number*x)%mod;
return x;
}
int main()
{
int number,power,mod,result,check;
cout<<"PRESS THE NUMBER: ";
cin>>number;
cout<<endl<<"PRESS THE POWER: ";
cin>>power;
cout<<endl<<"PRESS THE MOD VALUE: ";
cin>>mod;
check=check_prime(mod);
if(check==1)
{
cout<<endl<<"MODULAR MULTIPLICATIVE INVERSE IS NOT POSSIBLE"<<endl;
}
else
{
result = bigmod(number,power-2,mod);
cout<<endl<<"THE RESULT IS = "<<result<<endl;
}
return 0;
}
| true |
0ec4d62b351a99a6fb4793bee3e9fb8c4d2b2c24 | C++ | ramdotram/BST | /src/CNode.cpp | UTF-8 | 4,187 | 2.71875 | 3 | [] | no_license |
//#include "stdafx.h"
#include <iostream>
#include "BstUtility.h"
#include <cstring>
#include <algorithm> // std::sort
#include <vector>
using namespace std;
#include <atlstr.h>
#include "CNode.h"
namespace krian_bst
{
CNode::CNode(char *pName, char cColor): m_nSize(1), m_unNodeID(1)
{
strcpy_s( m_szName, pName );
m_cColor = cColor;
}
CNode::CNode():
m_cColor('b'), m_nSize(1),
m_pLeftBranch(NULL), m_pRightBranch(NULL), m_unNodeID(1)
{
strcpy_s( m_szName, "");
}
CNode* CNode::GetNewNode()
{
CNode *pNode = new CNode();
//todo memory allocation - exception handling
if( NULL != pNode )
{
cout<< "Enter Node name";
cin >> pNode->m_szName;
cout<< "Enter Node Color";
cin >> pNode->m_cColor;
}
else
{
printf("Memory allocation failure");
}
return pNode;
}
CNode* CNode::GetRandomNewNode()
{
std::string szRandName;
CNode *pNode = new CNode();
if( NULL != pNode )
{
szRandName = randomString( 10 ); //max string is 10 characters now
strcpy_s( pNode->m_szName, szRandName.c_str() );
pNode->m_cColor = randomColor();
}
return pNode;
}
void CNode::SetSize( int size )
{
m_nSize = size;
}
int CNode::GetSize()
{
return m_nSize;
}
char CNode::GetColor()
{
return m_cColor;
}
char* CNode::GetName()
{
return m_szName;
}
void CNode::Display()
{
printf("\n Node Name - %s, Node Color - %c, Node Size - %d", m_szName, m_cColor, m_nSize);
}
bool CNode::operator < (CNode node)
{
int val;
bool retVal = false;
val = strcmp( m_szName, node.GetName() );
if( val < 0 )
{
retVal = true;
}
return retVal;
}
bool CNode::operator > (CNode node)
{
int val;
bool retVal = false;
val = strcmp( m_szName, node.GetName() );
if( val > 0 )
{
retVal = true;
}
return retVal;
}
void CNode::operator = (CNode node)
{
m_cColor = node.GetColor();
strcpy_s( m_szName, node.m_szName);
//no change in size
return;
}
bool CNode::SetNodeID( unsigned int unNodeID )
{
m_unNodeID = unNodeID;
m_AdjacentColorsNodeIDs.push_back( m_unNodeID );
m_AdjacentColorsNodeNames.push_back( m_szName );
return true;
}
unsigned int CNode::GetNodeID( )
{
return m_unNodeID;
}
void CNode::UpdateAdjacentColorNodes( )
{
CNode *ptr;
m_AdjacentColorsNodeIDs.clear();
m_AdjacentColorsNodeIDs.push_back( m_unNodeID );
m_AdjacentColorsNodeNames.clear();
m_AdjacentColorsNodeNames.push_back( m_szName );
if( m_pLeftBranch )
{
if( m_cColor == m_pLeftBranch->GetColor() )
{
m_AdjacentColorsNodeIDs.insert( m_AdjacentColorsNodeIDs.end(), m_pLeftBranch->m_AdjacentColorsNodeIDs.begin(), m_pLeftBranch->m_AdjacentColorsNodeIDs.end() );
std::sort( m_AdjacentColorsNodeIDs.begin(), m_AdjacentColorsNodeIDs.end() );
m_AdjacentColorsNodeNames.insert( m_AdjacentColorsNodeNames.end(), m_pLeftBranch->m_AdjacentColorsNodeNames.begin(), m_pLeftBranch->m_AdjacentColorsNodeNames.end() );
}
}
if( m_pRightBranch )
{
if( m_cColor == m_pRightBranch->GetColor() )
{
m_AdjacentColorsNodeIDs.insert( m_AdjacentColorsNodeIDs.end(), m_pRightBranch->m_AdjacentColorsNodeIDs.begin(), m_pRightBranch->m_AdjacentColorsNodeIDs.end() );
std::sort( m_AdjacentColorsNodeIDs.begin(), m_AdjacentColorsNodeIDs.end() );
m_AdjacentColorsNodeNames.insert( m_AdjacentColorsNodeNames.end(), m_pRightBranch->m_AdjacentColorsNodeNames.begin(), m_pRightBranch->m_AdjacentColorsNodeNames.end() );
}
}
}
}
| true |
4de43d1b47d0bcbc38006bee338754bc505a61c0 | C++ | twobrowin-study/coursera | /Algorithmic Toolbox/week2_algorithmic_warmup/1_fibonacci_number/fibonacci.cpp | UTF-8 | 1,120 | 3.453125 | 3 | [] | no_license | #include <iostream>
#include <cassert>
#include <cstdint>
#include <cstring>
uint64_t fibonacci_naive(uint64_t n) {
if (n <= 1)
return n;
return fibonacci_naive(n - 1) + fibonacci_naive(n - 2);
}
uint64_t fibonacci_fast(uint64_t n) {
if (n <= 1)
return n;
uint64_t prev = 1;
uint64_t curr = 1;
for (uint64_t i = 2; i < n; i++) {
uint64_t tmp = curr;
curr = curr + prev;
prev = tmp;
}
return curr;
}
void test_solution() {
assert(fibonacci_fast(3) == 2);
assert(fibonacci_fast(10) == 55);
for (uint64_t n = 0; n < 25; ++n) {
std::cout << "Testing " << n << " :: " << '\n';
uint64_t fast = fibonacci_fast(n);
uint64_t naive = fibonacci_naive(n);
std::cout << " --> " << fast << " <-> " << naive << '\n';
assert(fast == naive);
}
}
int32_t main(int argc, char* argv[]) {
if (argc == 2 && strcmp(argv[1], "--stress") == 0 ) {
test_solution();
} else {
uint64_t n = 0;
std::cin >> n;
std::cout << fibonacci_fast(n) << '\n';
}
return 0;
}
| true |
d0caeafb3d7a98c0b27fd626dbf9ce85ecb44258 | C++ | DavidParkerDr/PixelGrid | /pixeltest/Shape.h | UTF-8 | 2,355 | 3.4375 | 3 | [] | no_license | #ifndef SHAPE_H
#define SHAPE_H
class Shape {
private:
String mName;
uint32_t mColour;
uint32_t * mCells;
uint16_t mRows;
uint16_t mColumns;
uint16_t mNumCells;
uint16_t mX;
uint16_t mY;
public :
Shape(String pName, uint32_t pColour, uint16_t pRows, uint16_t pColumns) {
this->mName = pName;
this->mColour = pColour;
mRows = pRows;
mColumns = pColumns;
mNumCells = mRows * mColumns;
mCells = new uint32_t[mNumCells];
setPosition(0,0);
}
~Shape() {
delete[] mCells;
}
String getName() {
return this->mName;
}
uint16_t getIndexFromRowAndColumn(uint16_t row, uint16_t column) {
uint16_t index = row * mColumns + column;
return index;
}
void setPosition(uint16_t pX, uint16_t pY) {
mX = pX;
mY = pY;
}
uint16_t getX() {
return mX;
}
uint16_t getY() {
return mY;
}
uint16_t numRows() {
return mRows;
}
uint16_t numColumns() {
return mColumns;
}
uint32_t getColour(uint16_t pRow, uint16_t pColumn) {
uint16_t index = getIndexFromRowAndColumn(pRow, pColumn);
return mCells[index];
}
bool setColour(uint16_t pRow, uint16_t pColumn, uint32_t pColour) {
bool success = false;
if(pRow >= 0 && pRow < mRows) {
if(pColumn >= 0 && pColumn < mColumns) {
uint16_t index = getIndexFromRowAndColumn(pRow, pColumn);
mCells[index] = pColour;
success = true;
}
}
return success;
}
static Shape* makeI(uint32_t pColour){
return new Shape("I", pColour, 2, 2); // light blue
}
static Shape* makeJ(uint32_t pColour){
return new Shape("J", pColour, 2, 2); // dark blue
}
static Shape* makeL(uint32_t pColour){
return new Shape("L", pColour, 2, 2); // orange
}
static Shape* makeO(uint32_t pColour){
Shape* shape = new Shape("O",pColour , 2, 2);
shape->setColour(0,0,pColour);
shape->setColour(0,1,pColour);
shape->setColour(1,0,pColour);
shape->setColour(1,1,pColour);
return shape;
}
static Shape* makeS(uint32_t pColour){
return new Shape("S", pColour, 2, 2); // green
}
static Shape* makeT(uint32_t pColour){
return new Shape("T", pColour, 2, 2); // purple
}
static Shape* makeZ(uint32_t pColour){
Shape* shape = new Shape("Z",pColour , 2, 2);
}
};
#endif
| true |
f66f51a8043f645a87e8e12df9270aaefb2fd05b | C++ | YuseqYaseq/Biblioteka | /AnimationTemplate.h | UTF-8 | 547 | 2.625 | 3 | [] | no_license | //AnimationTemplate.h
#pragma once
#include "Texture.h"
namespace PORTECZKI
{
class CellID
{
public:
int X;
int Y;
};
class AnimationTemplate
{
public:
AnimationTemplate();
~AnimationTemplate();
void Initialize(Texture* pTexture, int iCellWidth, int iCellHeight);
fRect GetFrame(int iCellX, int iCellY);
fRect GetFrame(CellID* ID);
int GetCellWidth(){return m_iCellWidth;}
int GetCellHeight(){return m_iCellHeight;}
private:
int m_iCellWidth;
int m_iCellHeight;
int m_iTexWidth;
int m_iTexHeight;
};
}; | true |
0a5460a85fc399f56f9b8ba979032d64eb299c3c | C++ | F1xx/Shaders-Megaman | /Game/Source/GameObjects/Player.cpp | UTF-8 | 2,633 | 2.5625 | 3 | [] | no_license | #include "GamePCH.h"
#include "Game/Game.h"
#include "Mesh/Mesh.h"
#include "GameObjects/GameObject.h"
#include "GameObjects/Player.h"
#include "GameObjects/PlayerController.h"
#include "Mesh/SpriteSheet.h"
#include "../Scenes/Scene.h"
#include "../Physics/PhysicsWorld.h"
struct RayCastResultCallback : public b2RayCastCallback
{
bool m_Hit;
b2Body* m_pBody;
RayCastResultCallback()
{
m_Hit = false;
m_pBody = 0;
}
float32 ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float32 fraction)
{
m_Hit = true;
m_pBody = fixture->GetBody();
return fraction; //store closest body
}
};
Player::Player(Scene* pScene, std::string name, Transform transform, Mesh* pMesh, Material* pMaterial)
: GameObject(pScene, name, transform, pMesh, pMaterial)
, m_pPlayerController(nullptr)
, m_Speed(PLAYER_SPEED)
, m_TurningSpeed(PLAYER_SPEED)
{
}
Player::~Player()
{
}
void Player::Update(float deltatime)
{
GameObject::Update( deltatime );
vec3 dir( 0, 0, 0 );
if( m_pPlayerController )
{
if( m_pPlayerController->IsHeld_Up() )
{
dir.y = 1;
}
if( m_pPlayerController->IsHeld_Down() )
{
dir.y = -1;
}
if( m_pPlayerController->IsHeld_Left() )
{
dir.x = -1;
}
if( m_pPlayerController->IsHeld_Right() )
{
dir.x = 1;
}
if (m_pPlayerController->IsHeld_In())
{
dir.z = -1;
}
if (m_pPlayerController->IsHeld_Out())
{
dir.z = 1;
}
}
if (m_pBody)
{
/*float mass = m_pBody->GetMass();
b2Vec2 currentVel = m_pBody->GetLinearVelocity();
b2Vec2 TargetVel = b2Vec2(2.0f, 2.0f);
b2Vec2 VelDiff = TargetVel - currentVel;
float timestep = 1 / 60.0f;
*/
//m_pBody->ApplyForceToCenter(mass * VelDiff / timestep);
b2Vec2 force;
force.x = dir.x;
force.y = dir.y;
force *= m_Speed * deltatime;
m_pBody->ApplyLinearImpulseToCenter(force, true);
}
else
m_Position += dir * m_Speed * deltatime;
RayCastResultCallback raycast;
b2Vec2 point1 = b2Vec2(m_Position.x, m_Position.y);
b2Vec2 point2 = b2Vec2(m_Position.x, m_Position.y - 6);
m_pScene->GetPhysicsWorld()->GetWorld()->RayCast(&raycast, point1, point2);
if (raycast.m_Hit)
{
GameObject* obj = (GameObject*)raycast.m_pBody->GetUserData();
ImGui::Text(obj->GetName().c_str());
}
}
void Player::Draw(Camera* cam)
{
GameObject::Draw(cam);
ImGui::SliderFloat("RotationX", &m_Rotation.x, 0.0f, 360.0f);
ImGui::SliderFloat("RotationY", &m_Rotation.y, 0.0f, 360.0f);
ImGui::SliderFloat("RotationZ", &m_Rotation.z, 0.0f, 360.0f);
} | true |
dbb7254df5433a0a252c7c5195d6269dcab0ef75 | C++ | pluto27351/Particles | /ParticleSystem/Classes/CParticle.cpp | BIG5 | 22,709 | 2.78125 | 3 | [] | no_license | #include <cmath>
#include "CParticle.h"
// ھڭOPɶp delta time 첾tq Aনù첾
// ] 2.5 @Ӥlqṳ̀W貾ʨ̤U, ]NO 720 PIXEL
// 720 PIXEL = 0.5*9.8*2.5*2.5 m => 1M = 23.5102 PIXEL
// ]Y bUt, ҥHOn[Wt, NV
#define FALLING_TIME 2.5f
#define MAX_HEIGHT 720.0f
#define PIXEL_PERM (2.0f*MAX_HEIGHT/(9.8f*FALLING_TIME*FALLING_TIME))
#define GRAVITY_Y(t,dt,g) ((g)*(t+0.5f*(dt))) //wggL t AAgL dt ɶUZ
#define LIFE_NOISE(f) ((f)*(1.0f-(rand()%2001/1000.0f)))
//#define INTENSITY(f) ( (f) >= 255 ? 255 : (f) )
inline int INTENSITY(float f) {
if (f >= 255) return(255);
else if (f <= 0) return(0);
else return((int)f);
}
USING_NS_CC;
CParticle::CParticle()
{
_fGravity = 0;
}
bool CParticle::doStep(float dt)
{
float cost, sint;
switch (_iType) {
case STAY_FOR_TWOSECONDS:
if (!_bVisible && _fElapsedTime >= _fDelayTime ) {
_fElapsedTime = _fElapsedTime - _fDelayTime; // s}lp
_bVisible = true;
_Particle->setVisible(_bVisible);
_Particle->setColor(_color);
_Particle->setPosition(_Pos);
}
else if (_fElapsedTime> _fLifeTime) {
_bVisible = false;
_Particle->setVisible(_bVisible);
return true; // lͩRgwg
}
else {
sint = sinf(M_PI*_fElapsedTime / _fLifeTime);
cost = cosf(M_PI_2*_fElapsedTime / _fLifeTime);
_Particle->setScale(1 + sint * 2);
_Particle->setOpacity(_fOpacity * cost);
_Particle->setColor(Color3B(INTENSITY((_color.r + sint * 64)*(1 + sint)),
INTENSITY((_color.g - cost * 32)*(1 + sint)), INTENSITY((_color.b - sint * 64)*(1 + sint))));
float tt = GRAVITY_Y(_fElapsedTime, dt, _fGravity);
_Pos.y += (_Direction.y * _fVelocity + tt) * dt * PIXEL_PERM;
_Particle->setPosition(_Pos);
}
break;
case RANDOMS_FALLING:
if (!_bVisible && _fElapsedTime >= _fDelayTime) {
_fElapsedTime = _fElapsedTime - _fDelayTime; // s}lp
_bVisible = true;
_Particle->setVisible(_bVisible);
_Particle->setColor(_color);
_Particle->setPosition(_Pos);
}
else if (_fElapsedTime > _fLifeTime) {
_bVisible = false;
_Particle->setVisible(_bVisible);
return true; // lͩRgwg
}
else {
sint = sinf(M_PI*_fElapsedTime / _fLifeTime);
cost = cosf(M_PI_2*_fElapsedTime / _fLifeTime);
_Particle->setScale(1 + sint * 1.25f);
_Particle->setOpacity(_fOpacity * cost);
_Particle->setColor(_color);
_Pos.x += _Direction.x * _fVelocity * dt * PIXEL_PERM;
float tt = GRAVITY_Y(_fElapsedTime, dt, _fGravity);
_Pos.y += (_Direction.y * _fVelocity + tt)* dt * PIXEL_PERM;
_Particle->setPosition(_Pos);
}
break;
case FREE_FLY:
if (!_bVisible && _fElapsedTime >= _fDelayTime) {
_fElapsedTime = _fElapsedTime - _fDelayTime; // s}lp
_bVisible = true;
_Particle->setVisible(_bVisible);
_Particle->setColor(_color);
_Particle->setPosition(_Pos);
}
else if (_fElapsedTime > _fLifeTime) {
_bVisible = false;
_Particle->setVisible(_bVisible);
return true; // lͩRgwg
}
else {
sint = sinf(M_PI*_fElapsedTime / _fLifeTime);
cost = cosf(M_PI_2*_fElapsedTime / _fLifeTime);
_Particle->setScale(1 + sint * 2);
_Particle->setOpacity(_fOpacity * cost);
_Particle->setColor(_color);
_Pos.x += _Direction.x * _fVelocity * dt * PIXEL_PERM;
float tt = GRAVITY_Y(_fElapsedTime, dt,_fGravity);
_Pos.y += (_Direction.y * _fVelocity + tt)* dt * PIXEL_PERM;
//_Pos.y += _Direction.y * _fVelocity * dt;
_Particle->setPosition(_Pos);
}
break;
case EXPLOSION:
if (!_bVisible && _fElapsedTime >= _fDelayTime) {
_fElapsedTime = _fElapsedTime - _fDelayTime; // s}lp
_bVisible = true;
_Particle->setVisible(_bVisible);
_Particle->setColor(_color);
_Particle->setPosition(_Pos);
}
else if (_fElapsedTime > _fLifeTime) {
_bVisible = false;
_Particle->setVisible(_bVisible);
return true; // lͩRgwg
}
else {
sint = sinf(M_PI*_fElapsedTime / _fLifeTime);
cost = cosf(M_PI_2*_fElapsedTime / _fLifeTime);
_Particle->setScale(1.25 + sint*2.0);
_Particle->setOpacity(_fOpacity * cost);
_Particle->setColor(Color3B(INTENSITY(_color.r*(1 + sint)), INTENSITY(_color.g*(1 + sint)), INTENSITY(_color.b*(1 + sint))));
_Pos.x += _Direction.x * cost * _fVelocity * dt * PIXEL_PERM;
float tt = GRAVITY_Y(_fElapsedTime, dt, _fGravity);
_Pos.y += (_Direction.y * cost * _fVelocity + tt)* dt * PIXEL_PERM;
_Particle->setPosition(_Pos);
}
break;
case HEARTSHAPE:
case BUTTERFLYSHAPE:
if (!_bVisible && _fElapsedTime >= _fDelayTime) {
_fElapsedTime = _fElapsedTime - _fDelayTime; // s}lp
_bVisible = true;
_Particle->setVisible(_bVisible);
_Particle->setColor(_color);
_Particle->setPosition(_Pos);
}
else if (_fElapsedTime > _fLifeTime) {
_bVisible = false;
_Particle->setVisible(_bVisible);
return true; // lͩRgwg
}
else {
// ھڤ߫ApC@Ӥlפm
sint = sinf(M_PI*_fElapsedTime / _fLifeTime);
cost = cosf(M_PI_2*_fElapsedTime / _fLifeTime);
_Particle->setScale(1.25 + (1 - cost)*2.0);
_Particle->setOpacity(_fOpacity * cost);
_Particle->setColor(_color);
_Pos.x += _Direction.x * cost * _fVelocity * dt * PIXEL_PERM;
float tt = GRAVITY_Y(_fElapsedTime, dt, _fGravity);
_Pos.y += (_Direction.y * cost * _fVelocity + tt)* dt * PIXEL_PERM;
_Particle->setPosition(_Pos);
}
break;
case THUNDER:
if (!_bVisible && _fElapsedTime >= _fRDelayTime) {
float t = rand() % 90;
if (t < 30) {
_Pos.x = _Pos.x - 30* (t / 29);
_Pos.y = _Pos.y - 150* (t / 29);
}
else if (t < 60) {
t -= 30;
_Pos.x = _Pos.x - 30 + 60 * (t / 29);
_Pos.y = _Pos.y - 150 - 70 * (t / 29);
}
else {
t -= 60;
_Pos.x = _Pos.x - 30 + 60 - 30 * (t / 29);
_Pos.y = _Pos.y - 150 - 70 - 230 * (t / 29);
}
_fElapsedTime = 0; // s}lp
_bVisible = true;
_fSize = (0.8 - t / 90 );
_Particle->setVisible(_bVisible);
_Particle->setColor(_color);
_Particle->setPosition(_Pos);
_Particle->setOpacity(255);
}
else if (_fElapsedTime > _fLifeTime) {
_bVisible = false;
_Particle->setVisible(_bVisible);
return true; // lͩRgwg
}
else {
sint = sinf(M_PI*_fElapsedTime / _fLifeTime);
cost = cosf(M_PI*_fElapsedTime / _fLifeTime);
_Particle->setScale(_fSize);
_Particle->setOpacity(_fOpacity * cost);
_Particle->setColor(_color);
_Particle->setPosition(_Pos);
}
break;
case THUNDERCLOUD:
if (!_bVisible && _fElapsedTime >= _fDelayTime) {
_fElapsedTime = _fElapsedTime - _fDelayTime; // s}lp
_bVisible = true;
_Particle->setVisible(_bVisible);
_Particle->setColor(_color);
_Particle->setPosition(_Pos);
}
else if (_fElapsedTime > _fLifeTime) {
_bVisible = false;
_Particle->setVisible(_bVisible);
return true; // lͩRgwg
}
else {
sint = sinf(M_PI*_fElapsedTime / _fLifeTime*2);
cost = cosf(M_PI_2*_fElapsedTime / _fLifeTime);
_Particle->setScale(_fSize + sint * 1.5f);
_Particle->setOpacity(_fOpacity * cost);
_Particle->setColor(_color);
_Pos.x += 5*sint;
_Particle->setPosition(_Pos);
}
break;
case MAGIC:
if (!_bVisible && _fElapsedTime >= _fDelayTime) {
_fElapsedTime = _fElapsedTime - _fDelayTime; // s}lp
_bVisible = true;
_Particle->setVisible(_bVisible);
_Particle->setColor(_color);
_Particle->setPosition(_Pos);
}
else if (_fElapsedTime > _fLifeTime) {
_bVisible = false;
_Particle->setVisible(_bVisible);
return true; // lͩRgwg
}
else {
float r = (_fElapsedTime / _fLifeTime) * M_PI *100;
Vec2 nextPos;
nextPos.x = _Pos.x + 200 * cosf(r);
nextPos.y = _Pos.y + 200 * sinf(r)/2;
sint = sinf(M_PI*_fElapsedTime / _fLifeTime);
cost = cosf(M_PI_2*_fElapsedTime / _fLifeTime);
_Particle->setScale(1.25 + (1 - cost)*2.0);
_Particle->setOpacity(_fOpacity * cost);
_Particle->setColor(_color);
_Particle->setPosition(nextPos);
}
break;
case BALLOON:
if (!_bVisible && _fElapsedTime >= _fDelayTime) {
_fElapsedTime = _fElapsedTime - _fDelayTime; // s}lp
_bVisible = true;
_Particle->setVisible(_bVisible);
_Particle->setColor(_color);
_Particle->setPosition(_Pos);
}
else if (_fElapsedTime> _fLifeTime) {
_bVisible = false;
_Particle->setVisible(_bVisible);
return true; // lͩRgwg
}
else {
Vec2 winddir(sinf(_fWindDir)*_fWindStr / 3, cosf(_fWindDir)*_fWindStr / 3);
sint = sinf(M_PI*_fElapsedTime / _fLifeTime);
cost = cosf(M_PI_2*_fElapsedTime / _fLifeTime);
_Particle->setScale(_fSize + sint * _fVelocity);
_Particle->setOpacity(_fOpacity * cost);
_Particle->setColor(Color3B(INTENSITY((_color.r + sint * 64)*(1 + sint)),
INTENSITY((_color.g - cost * 32)*(1 + sint)), INTENSITY((_color.b - sint * 64)*(1 + sint))));
float tt = GRAVITY_Y(_fElapsedTime, dt, _fGravity);
if (_fVelocity != 0) {
_Pos.y += (_Direction.y * (_fVelocity + _fElapsedTime / _fLifeTime*3.0f) + tt) * dt * PIXEL_PERM;
_Pos.x += _Direction.x * _fVelocity * dt * PIXEL_PERM;
_Pos += winddir;
}
_Particle->setPosition(_Pos);
}
break;
case EMITTER_DEFAULT:
if (!_bVisible && _fElapsedTime >= _fDelayTime) {
_fElapsedTime = _fElapsedTime - _fDelayTime; // s}lp
_bVisible = true;
_Particle->setVisible(_bVisible);
_Particle->setColor(_color);
_Particle->setPosition(_Pos);
}
else if (_fElapsedTime > _fLifeTime) {
_bVisible = false;
_Particle->setVisible(_bVisible);
return true; // lͩRgwg
}
else {
/*float wind = (1.0f + sin(_fElapsedTime/(_fLifeTime*13)))*_fWindStr*_fElapsedTime*3 ;
Vec2 winddir(sinf(_fWindDir)*wind, cosf(_fWindDir)*wind);*/
/* Vec2 winddir = Vec2(cosf(M_PI*(_fElapsedTime+90) / 180 * 100)*_fWindStr, 1);
winddir.x = winddir.x*cosf(_fWindDir) + winddir.y*sinf(_fWindDir);
winddir.y = winddir.x*sinf(_fWindDir)*-1 + winddir.y*cosf(_fWindDir);*/
Vec2 winddir(sinf(_fWindDir)*_fWindStr/3, cosf(_fWindDir)*_fWindStr/3);
sint = sinf(M_PI*_fElapsedTime / _fLifeTime);
cost = cosf(M_PI_2*_fElapsedTime / _fLifeTime);
_Particle->setScale(_fSize + sint * 1.5f);
_Particle->setOpacity(_fOpacity * cost);
_Particle->setColor(_color);
_Pos.x += _Direction.x * _fVelocity * dt * PIXEL_PERM;
float tt = GRAVITY_Y(_fElapsedTime, dt, _fGravity);
_Pos.y += (_Direction.y * _fVelocity + tt)* dt * PIXEL_PERM;
_Pos += winddir;
_Particle->setPosition(_Pos);
}
break;
case FIREWORK:
if (!_bVisible && _fElapsedTime >= _fDelayTime) {
_fElapsedTime = _fElapsedTime - _fDelayTime; // s}lp
_bVisible = true;
_Particle->setVisible(_bVisible);
_Particle->setColor(_color);
_Particle->setPosition(_Pos);
}
else if (_fElapsedTime > _fLifeTime) {
_bVisible = false;
_Particle->setVisible(_bVisible);
return true; // lͩRgwg
}
else {
sint = sinf(M_PI*_fElapsedTime / _fLifeTime);
cost = cosf(M_PI_2*_fElapsedTime / _fLifeTime);
_Particle->setScale(_fSize + sint * 1.5f);
_Particle->setOpacity(_fOpacity * cost);
//_Particle->setColor(Color3B(INTENSITY(_color.r*(1 + sint)), INTENSITY(_color.g*(1 + sint)), INTENSITY(_color.b*(1 + sint))));
_Particle->setColor(_color);
_Pos.x += _Direction.x * _fVelocity * dt * PIXEL_PERM/3;
float tt = GRAVITY_Y(_fElapsedTime, dt, _fGravity);
_Pos.y += (_Direction.y * _fVelocity + tt)* dt * PIXEL_PERM+5;
_Particle->setPosition(_Pos);
}
break;
case ROLL:
if (!_bVisible && _fElapsedTime >= _fDelayTime) {
_fElapsedTime = _fElapsedTime - _fDelayTime; // s}lp
_bVisible = true;
_Particle->setVisible(_bVisible);
_Particle->setColor(_color);
_Particle->setPosition(_Pos);
_Particle->setOpacity(255);
}
else if (_fElapsedTime > _fLifeTime) {
_bVisible = false;
_Particle->setVisible(_bVisible);
return true; // lͩRgwg
}
else {
float wind = (1.0f + sin(_fElapsedTime))*_fWindStr*_fElapsedTime * 3;
Vec2 winddir(sinf(_fWindDir)*wind, cosf(_fWindDir)*wind);
sint = sinf(M_PI*_fElapsedTime / _fLifeTime);
cost = cosf(M_PI_2*_fElapsedTime / _fLifeTime);
_Particle->setScale(_fSize + sint * 1.5f);
_Particle->setOpacity(_fOpacity * cost);
//_Particle->setColor(Color3B(INTENSITY(_color.r*(1 + sint)), INTENSITY(_color.g*(1 + sint)), INTENSITY(_color.b*(1 + sint))));
_Particle->setColor(_color);
_Pos.x += _Direction.x * _fVelocity * dt * PIXEL_PERM;
float tt = GRAVITY_Y(_fElapsedTime, dt, _fGravity);
_Pos.y += (_Direction.y * _fVelocity + tt)* dt * PIXEL_PERM;
_Particle->setPosition(_Pos + winddir);
}
break;
case WATERBALL:
if (!_bVisible && _fElapsedTime >= _fRDelayTime) {
_fElapsedTime = 0; // s}lp
_bVisible = true;
_Particle->setVisible(_bVisible);
_Particle->setColor(_color);
_Particle->setPosition(_Pos);
_Particle->setOpacity(255);
}
else if (_fElapsedTime > _fLifeTime) {
_bVisible = false;
_Particle->setVisible(_bVisible);
return true; // lͩRgwg
}
else if(_bVisible){
sint = sinf(M_PI*_fElapsedTime / _fLifeTime);
cost = cosf(M_PI*(_fElapsedTime) / _fLifeTime/5);
_Particle->setColor(_color);
if (_fElapsedTime > 0.5) {
_Particle->setScale(_fSize + sint *2.0f);
_Pos.x -= _Direction.x * _fVelocity * dt * PIXEL_PERM;
float tt = GRAVITY_Y(_fElapsedTime, dt, _fGravity);
_Pos.y -= (_Direction.y * _fVelocity + tt)* dt * PIXEL_PERM;
}
else {
_Particle->setScale(_fSize + sint / 3.0f*2.0f);
_Pos.x -= _Direction.x * _fVelocity * dt * PIXEL_PERM;
float tt = GRAVITY_Y(_fElapsedTime, dt, _fGravity);
_Pos.y -= (_Direction.y*cost* _fVelocity + tt)* dt * PIXEL_PERM;
}
float r = atan2f(_Direction.y, _Direction.x);
r += _fElapsedTime / _fLifeTime * M_PI;
_Pos.x += cos(r)*1.5;
_Pos.y += sin(r)*1.5;
_Particle->setPosition(_Pos);
}
break;
case BOMB:
if (!_bVisible && _fElapsedTime >= _fRDelayTime) {
_fElapsedTime = 0; // s}lp
_bVisible = true;
_Particle->setVisible(_bVisible);
_Particle->setColor(_color);
_Particle->setPosition(_Pos);
_Particle->setOpacity(255);
}
else if (_fElapsedTime > _fLifeTime) {
_bVisible = false;
_Particle->setVisible(_bVisible);
return true; // lͩRgwg
}
else if (_bVisible) {
sint = sinf(M_PI*_fElapsedTime / _fLifeTime*2);
cost = cosf(M_PI_2*_fElapsedTime / _fLifeTime);
float rx = -cosf((_Pos.x + _em.x) / 45 * M_PI)*5;
//_Particle->setScale(_fSize + sint * 1.5f);
_Particle->setScale(_fSize);
_Particle->setOpacity(_fOpacity * cost);
_Particle->setColor(_color);
float dx = _Direction.x*rx;
_Pos.x += _Direction.x * _fVelocity * dt * PIXEL_PERM;
float tt = GRAVITY_Y(_fElapsedTime, dt, _fGravity);
_Pos.y += (_Direction.y * _fVelocity + tt)* dt * PIXEL_PERM*1.5;
_Particle->setPosition(_Pos);
}
break;
case AIRPLANE:
if (!_bVisible && _fElapsedTime >= _fDelayTime) {
_fElapsedTime = _fElapsedTime - _fDelayTime; // s}lp
_bVisible = true;
_Particle->setVisible(_bVisible);
_Particle->setColor(_color);
_Particle->setPosition(_Pos);
_Particle->setOpacity(255);
}
else if (_fElapsedTime > _fLifeTime) {
_bVisible = false;
_Particle->setVisible(_bVisible);
return true; // lͩRgwg
}
else if (_bVisible) {
cost = cosf(M_PI_2*_fElapsedTime / _fLifeTime);
float rx = -cosf((_Pos.x + _em.x) / 45 * M_PI) * 5;
_Particle->setScale(_fSize);
if(_fVelocity == 0)_Particle->setOpacity(_fOpacity * cost);
_Particle->setColor(_color);
_Pos.x += _Direction.x * _fVelocity * dt;
_Pos.y += _Direction.y * _fVelocity* dt;
_Particle->setPosition(_Pos);
}
break;
}
float degree = _fSpin * _fElapsedTime;
_Particle->setRotation(degree);
// ֥[ɶ
_fElapsedTime += dt;
return false;
}
void CParticle::setBehavior(int iType)
{
float t;
_iType = iType;
switch (_iType) {
case STAY_FOR_TWOSECONDS:
_fVelocity = 0;
_fLifeTime = 2.5f + LIFE_NOISE(0.15f);
_fIntensity = 1;
_fOpacity = 255;
_fSpin = 0;
_fSize = 1;
_color = Color3B(64 + rand() % 128, 64 + rand() % 128, 64 + rand() % 128);
_fElapsedTime = 0;
_fDelayTime = 0;
_fGravity = 0;
_Particle->setOpacity(255);
_Particle->setScale(_fSize);
break;
case RANDOMS_FALLING:
_fVelocity = 5.0f + rand() % 10 / 10.0f; // M/Sec
_Direction.x = 0;
_Direction.y = -1;
_fLifeTime = 3.0f + LIFE_NOISE(0.15f);
_fIntensity = 1;
_fOpacity = 255;
_fSpin = 0;
_fSize = 1;
_color = Color3B(128 + rand() % 128, 128 + rand() % 128, 128 + rand() % 128);
_fElapsedTime = 0;
_fDelayTime = 0;
_fGravity = 0;
break;
case FREE_FLY:
_fVelocity = 5.0f + rand() % 10 / 10.0f; // M/Sec
t = 2.0f * M_PI * (rand() % 1000) / 1000.0f;
_Direction.x = cosf(t);
_Direction.y = sinf(t);
_fLifeTime = 3.0f + LIFE_NOISE(0.15f);
_fIntensity = 1;
_fOpacity = 255;
_fSpin = 0;
_fSize = 1;
_color = Color3B(128 + rand() % 128, 128 + rand() % 128, 128 + rand() % 128);
_fElapsedTime = 0;
_fDelayTime = 0;
_fGravity = 0;
break;
case EXPLOSION:
_fVelocity = 15.0f + rand() % 10 / 10.0f;
t = 2.0f * M_PI * (rand() % 1000) / 1000.0f;
_Direction.x = cosf(t);
_Direction.y = sinf(t);
_fLifeTime = 1.5f + LIFE_NOISE(0.15f);
_fIntensity = 1;
_fOpacity = 255;
_fSpin = 0;
_fSize = 1;
_color = Color3B(64 + rand() % 128, 64 + rand() % 128,64 + rand() % 128);
//_color = Color3B(255, 255, 255);
_fElapsedTime = 0;
_fDelayTime = rand() % 100 / 1000.0f;
_fGravity = 0;
break;
case HEARTSHAPE:
_fVelocity = 1.0f;
t = 2.0f * M_PI * (rand() % 1000) / 1000.0f;
float sint, cost, cos2t, cos3t, cos4t, sin12t;
sint = sinf(t); cost = cosf(t); cos2t = cosf(2*t); cos3t = cosf(3 * t); cos4t = cosf(4 * t);
sin12t = sin(t/12.0f);
_Direction.x = 16*sint*sint*sint;
_Direction.y = 13*cost - 5*cos2t - 2*cos3t - cos4t;
_fLifeTime = 1.5f + LIFE_NOISE(0.15f);
_fIntensity = 1;
_fOpacity = 255;
_fSpin = 0;
_fSize = 1;
_color = Color3B(128 + rand() % 128, 128 + rand() % 128, 128 + rand() % 128);
//_color = Color3B(255, 255, 255);
_fElapsedTime = 0;
_fDelayTime = rand() % 100 / 1000.0f;
_fGravity = 0;
break;
case BUTTERFLYSHAPE:
_fVelocity = 6.5f;
t = 2.0f * M_PI * (rand() % 1000) / 1000.0f;
sint = sinf(t); cost = cosf(t); cos4t = cosf(4 * t); sin12t = sin(t / 12.0f);
_Direction.x = sint*(expf(cost) - 2 * cos4t - powf(sin12t, 5));
_Direction.y = cost*(expf(cost) - 2 * cos4t - powf(sin12t, 5));
_fLifeTime = 1.5f + LIFE_NOISE(0.15f);
_fIntensity = 1;
_fOpacity = 255;
_fSpin = 0;
_fSize = 1;
_color = Color3B(128 + rand() % 128, 128 + rand() % 128, 128 + rand() % 128);
//_color = Color3B(255, 255, 255);
_fElapsedTime = 0;
_fDelayTime = rand() % 100 / 1000.0f;
_fGravity = 0;
break;
case THUNDER:
_fVelocity = 0;
//_Direction = Vec2(-4, -3);
_fLifeTime = 1;
_fIntensity = 1;
_fOpacity = 255;
_fSpin = 0;
_fSize = 0.5f;
_fRDelayTime = 0;
_color = Color3B(0, 58, 255);
_fElapsedTime = 0;
_fGravity = 0;
break;
case THUNDERCLOUD:
_fVelocity = 0.5f;
//_Direction = Vec2(-4, -3);
_fLifeTime = 2;
_fIntensity = 1;
_fOpacity = 100;
_fSpin = 0;
_fDelayTime = 0;
_fSize = 5;
_color = Color3B(255,255,255);
_fElapsedTime = 0;
_fGravity = 0;
break;
case MAGIC:
_fVelocity = 1;
_fLifeTime = 0.5f + LIFE_NOISE(0.15f);
_fIntensity = 1;
_fOpacity = 255;
_fSpin = 0;
_fSize = 0.2f;
_color = Color3B(128 + rand() % 128, 128 + rand() % 128, 128 + rand() % 128);
//_color = Color3B(255, 255, 255);
_fElapsedTime = 0;
_fDelayTime = 0;
_fGravity = 0;
break;
case BALLOON:
//_fVelocity = 0;
//_fLifeTime = 2.5f + LIFE_NOISE(0.15f);
_fIntensity = 1;
_fOpacity = 255;
_fSpin = 0;
//_fSize = 1;
_color = Color3B(64 + rand() % 128, 64 + rand() % 128, 64 + rand() % 128);
_fElapsedTime = 0;
_fDelayTime = 0;
_fGravity = 0;
_Particle->setOpacity(255);
_Particle->setScale(_fSize);
break;
case EMITTER_DEFAULT:
_fIntensity = 1;
_fOpacity = 255;
_fSize = 1;
_color = Color3B(rand() % 128, rand() % 128, 128 + rand() % 128);
_fElapsedTime = 0;
_fDelayTime = 0;
_Particle->setScale(_fSize);
break;
case FIREWORK:
_fIntensity = 1;
_fOpacity = 255;
_fSize = 1;
_color = Color3B(rand() % 128, rand() % 128, 128 + rand() % 128);
_fElapsedTime = 0;
_fDelayTime = 0;
_Particle->setScale(_fSize);
break;
case ROLL:
_fIntensity = 1;
_fOpacity = 255;
_fSize = 1;
_color = Color3B(rand() % 128, rand() % 128, 128 + rand() % 128);
_fElapsedTime = 0;
_fDelayTime = 0;
_Particle->setScale(_fSize);
break;
case WATERBALL:
_fIntensity = 1;
_fOpacity = 255;
_fSize = 1;
_color = Color3B(rand() % 128, rand() % 128, 128 + rand() % 128);
_fElapsedTime = 0;
//_fDelayTime = rand() % 100 / 1000.0f;
_Particle->setScale(_fSize);
break;
case BOMB:
_fIntensity = 1;
_fOpacity = 255;
//_fSize = 1;
_color = Color3B(rand() % 128, rand() % 128, 128 + rand() % 128);
_fElapsedTime = 0;
//_fDelayTime = rand() % 100 / 1000.0f;
_Particle->setScale(_fSize);
break;
case AIRPLANE:
_fIntensity = 1;
_fOpacity = 255;
_fElapsedTime = 0;
_Particle->setScale(_fSize);
break;
}
}
void CParticle::setLifetime(const float lt) {
_fLifeTime = lt + LIFE_NOISE(0.15f);;
}
void CParticle::setParticle(const char *pngName, cocos2d::Layer &inlayer)
{
_Particle = Sprite::createWithSpriteFrameName(pngName);
_Particle->setPosition(Point(rand() % 1024, rand() % 768));
_Particle->setOpacity(255);
_Particle->setColor(Color3B::WHITE);
_bVisible = false;
_Particle->setVisible(false);
_iType = 0;
//BlendFunc blendfunc = {GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA};
BlendFunc blendfunc = { GL_SRC_ALPHA, GL_ONE };
_Particle->setBlendFunc(blendfunc);
inlayer.addChild(_Particle, 1);
}
void CParticle::setVisible()
{
_bVisible = true;
_Particle->setVisible(_bVisible);
}
void CParticle::setPosition(const cocos2d::Point &inPos) {
_Pos = inPos;
};
void CParticle::setGravity(const float fGravity)
{
_fGravity = fGravity;
}
void CParticle::setParticleName(char *pngName) {
_Particle->setSpriteFrame(pngName);
}
| true |
6f087b2af769ecd68f16388eea365f3aa779fc67 | C++ | Aash2802/ShaderManipulation_Task-2 | /Task2ShaderProject/AnalogPinCodes/AnalogPinCodes.ino | UTF-8 | 848 | 3.59375 | 4 | [] | no_license | int AnalogPin0 = A0; //Declare an integer variable, hooked up to analog pin 0
int AnalogPin1 = A1; //Declare an integer variable, hooked up to analog pin 1
int AnalogPin2 = A2;
void setup() {
Serial.begin(9600); // Begin Serial Communication with a baud rate of 9600
}
void loop() {
// New variables are declared to store the readings of the respective pins
int Value1 = analogRead(AnalogPin0);
int Value2 = analogRead(AnalogPin1);
int Value3 = analogRead(AnalogPin2);
/*The Serial.print() function does not execute a "return" or a space
* Also, the "," character is essential for parsing the values,
* The comma is not necessary after the last variable.
*/
Serial.print(Value1, DEC);
Serial.print(",");
Serial.print(Value2, DEC);
Serial.print(",");
Serial.print(Value3, DEC);
Serial.println();
delay(16);
}
| true |
5dfb2f89f2ab156e0e52b2569137e5fdf6aaed9e | C++ | b3n3m/cpp-first-steps | /factorial_project/to_int.cpp | UTF-8 | 318 | 3.09375 | 3 | [] | no_license | #include <sstream>
#include <stdexcept>
#include <string>
#include "factorial.hpp"
using namespace std;
int to_int(char* text) {
stringstream input{text};
int n;
input >> n;
if (input.fail() || !input.eof()) {
throw invalid_argument{string{"Argument '"} + text + "' has wrong format!"};
}
return n;
} | true |
0859c3804107a634987bef71eb709535a9e9bfcf | C++ | zsebastian/Algoritmer_Datastrukturer | /TravelingSalesman/TravelingSalesman/BranchAndBound.h | UTF-8 | 4,405 | 2.65625 | 3 | [] | no_license | #pragma once
/* Reads:
http://lcm.csa.iisc.ernet.in/dsa/node187.html
*/
#include "Graph.h"
#include <vector>
#include <utility>
#include "Path.h"
namespace tsp
{
namespace algorithm
{
/* My kingdom for a friend function! */
template <class T, template <class> class MatrixRep, template <class, template <class> class > class AccessorPolicy>
Path<T> BranchAndBound(const Graph<T, MatrixRep, AccessorPolicy>& graph);
namespace detail
{
template <class T, template <class> class MatrixRep, template <class, template <class> class > class AccessorPolicy>
class BAB
{
template <class T, template <class> class MatrixRep, template <class, template <class> class > class AccessorPolicy>
friend Path<T> BranchAndBound(const Graph<T, MatrixRep, AccessorPolicy>& graph);
public:
BAB(const Graph<T, MatrixRep, AccessorPolicy>& graph);
Path<T> start();
private:
void init();
const Graph<T, MatrixRep, AccessorPolicy>& m_graph;
Path<T> m_best;
void recurce(Path<T>);
};
}
template <class T, template <class> class MatrixRep, template <class, template <class> class > class AccessorPolicy>
Path<T> BranchAndBound(const Graph<T, MatrixRep, AccessorPolicy>& graph)
{
if (*graph.get_nodes().begin() == *graph.get_nodes().end())
return Path<T>();
detail::BAB<T, MatrixRep, AccessorPolicy> branch(graph);
return branch.start();
}
namespace detail
{
template <class T, template <class> class MatrixRep, template <class, template <class> class > class AccessorPolicy>
BAB<T, MatrixRep, AccessorPolicy>::BAB(const Graph<T, MatrixRep, AccessorPolicy>& graph)
:m_graph(graph)
{
}
template <class T, template <class> class MatrixRep, template <class, template <class> class > class AccessorPolicy>
void BAB<T, MatrixRep, AccessorPolicy>::init()
{
auto nodes = m_graph.get_nodes();
auto begin = nodes.begin();
auto end = nodes.end();
int prev = *begin;
++begin;
while (begin != end)
{
m_best.push(Edge(prev, *begin), m_graph);
prev = *begin;
++begin;
}
}
template <class T, template <class> class MatrixRep, template <class, template <class> class > class AccessorPolicy>
Path<T> BAB<T, MatrixRep, AccessorPolicy>::start ()
{
init();
recurce(Path<T>());
/* wrap up road */
m_best.push(Edge((m_best.begin() + m_best.total_edges() - 1)->first.end_node, m_best.front().first.start_node), m_graph);
return m_best;
/*
Naive Branch-and-Bound Solution of TSP
w = w(1,2) + w(2,3) + w(3,4) + ... + w(n-1,n) + w(n,1)
Best_S_so_far = ( n, [ 1, 2, 3, ... , n-1, n ], w )
S = ( 1, [ 1 ], 0 )
Search( S, Best_S_so_far )
print Best_S_so_far
procedure Search( S, Best_S_so_far )
let ( k, [ i1, i2, ... , ik ], w ) = S
let ( n, [ i1B, i2B, ... , inB ], wB ) = Best_S_so_far
if k = n then
new_w = w + w(ik,i1)
if new_w < wB then
Best_S_so_far = ( k, [ i1, i2, ... , ik ], new_w )
end if
else
for all j not in [ i1, i2, ... , ik ]
new_w = w + w(ik,j)
if new_w < wB then
New_S = ( k+1, [ i1, i2, ... , ik, j ], new_w )
Search( New_S, Best_S_so_far )
end if
end for
endif
return
end
*/
}
template <class T, template <class> class MatrixRep, template <class, template <class> class > class AccessorPolicy>
void BAB<T, MatrixRep, AccessorPolicy>::recurce(Path<T> path)
{
int last = 0;
if (path.total_edges() != 0)
last = path.back().first.end_node;
else
last = *m_graph.get_nodes().begin();;
if (path.total_edges() == m_best.total_edges())
{
if (path.total_weight() < m_best.total_weight())
{
m_best = path;
}
}
else
{
for (auto node : m_graph.get_neighbours(last))
{
auto begin = path.begin();
if (std::find_if(begin, path.end(),
[&](const std::pair<Edge, T>& edge) -> bool
{
return edge.first.start_node == node.end_node || edge.first.end_node == node.end_node;
}) == path.end())
{
T new_w = path.total_weight();
if (new_w < m_best.total_weight())
{
Path<T> new_path = path;
new_path.push(node, m_graph);
recurce(new_path);
}
}
}
}
return;
}
}
}
} | true |
8e368afa483f07e8ffcf50f4e833e526873133ee | C++ | melon-li/cpp_course | /test9-5.cpp | UTF-8 | 1,183 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <set>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
void solve(const set<pair<int, int> > &record,
int power,
int id){
set<pair<int, int> >::iterator ptr, fo, ba;
ptr = record.find(make_pair(power, id));
fo = record.end();
fo--;
if(ptr == record.begin()){
fo = ptr;
fo++;
printf("%d %d\n", ptr->second, fo->second);
}else if(ptr == fo){
ba = ptr;
ba--;
printf("%d %d\n", ptr->second, ba->second);
}else{
fo = ptr; fo++;
ba = ptr; ba--;
if((fo->first - ptr->first)<(ptr->first - ba->first))
printf("%d %d\n", ptr->second, fo->second);
else
printf("%d %d\n", ptr->second, ba->second);
}
return;
}
int main(){
int n;
set<pair<int, int> > record;
scanf("%d", &n);
record.insert(make_pair(1000000000, 1));
for(int i=0; i<n; i++){
int power, id;
scanf("%d%d", &id, &power);
record.insert(make_pair(power, id));
solve(record, power, id);
}
return 0;
}
| true |
e41e0fedc4dcc306c83fd3f0a7eb5898297f6af1 | C++ | googleplexplex/FakeTypes | /FakeTypesProject/fakeBool.hpp | UTF-8 | 3,448 | 2.984375 | 3 | [] | no_license | #pragma once
#include "registerCore.hpp"
class fakeBool : public registerableClass
{
public:
bool val;
fakeBool(bool _val, const char* name, bool codeLine)
: registerableClass(boolType, name, codeLine)
{
val = _val;
}
fakeBool(const char* name, bool codeLine)
: registerableClass(boolType, name, codeLine) {}
fakeBool(bool _val)
: registerableClass(boolType, "?", -1)
{
val = _val;
}
fakeBool()
: registerableClass(boolType, "?", -1) {}
template <typename T>
fakeBool operator=(T right)
{
return (val = right);
}
fakeBool operator=(fakeBool right)
{
return (val = right.val);
}
template <typename T>
fakeBool operator+(T right)
{
return (val + right);
}
fakeBool operator+(fakeBool right)
{
return (val + right.val);
}
template <typename T>
fakeBool operator-(T right)
{
return (val - right);
}
fakeBool operator-(fakeBool right)
{
return (val - right.val);
}
template <typename T>
fakeBool operator*(T right)
{
return (val * right);
}
fakeBool operator*(fakeBool right)
{
return (val * right.val);
}
template <typename T>
fakeBool operator/(T right)
{
return (val / right);
}
fakeBool operator/(fakeBool right)
{
return (val / right.val);
}
template <typename T>
fakeBool operator+=(T right)
{
return (val += right);
}
fakeBool operator+=(fakeBool right)
{
return (val += right.val);
}
template <typename T>
fakeBool operator-=(T right)
{
return (val -= right);
}
fakeBool operator-=(fakeBool right)
{
return (val -= right.val);
}
template <typename T>
fakeBool operator*=(T right)
{
return (val *= right);
}
fakeBool operator*=(fakeBool right)
{
return (val *= right.val);
}
template <typename T>
fakeBool operator/=(T right)
{
return (val /= right);
}
fakeBool operator/=(fakeBool right)
{
return (val /= right.val);
}
fakeBool operator++(int right)
{
return val++;
}
fakeBool operator++()
{
return ++val;
}
template <typename T>
fakeBool operator==(T right)
{
return val == right;
}
fakeBool operator==(fakeBool right)
{
return val == right.val;
}
template <typename T>
fakeBool operator!=(T right)
{
return !(val == right);
}
fakeBool operator!=(fakeBool right)
{
return !(val == right.val);
}
template <typename T>
fakeBool operator>(T right)
{
return val > right;
}
fakeBool operator>(fakeBool right)
{
return val > right.val;
}
template <typename T>
fakeBool operator<(T right)
{
return val < right;
}
fakeBool operator<(fakeBool right)
{
return val < right.val;
}
template <typename T>
fakeBool operator>=(T right)
{
return val >= right;
}
fakeBool operator>=(fakeBool right)
{
return val >= right.val;
}
template <typename T>
fakeBool operator<=(T right)
{
return val <= right;
}
fakeBool operator<=(fakeBool right)
{
return val <= right.val;
}
}; | true |
68b8175c3e8753ea199caaf839f25df7ef1bec06 | C++ | ShreyasP7495/DP-2 | /ques22.cpp | UTF-8 | 667 | 3.203125 | 3 | [] | no_license | Time Complexity-O(n*m) Here 'n' is the amount and 'm' is the size of the input vector
HSpace Complexity-O(n) Here 'n' is the amount
Did the code run on Leetcode? Yes
#include <iostream>
#include<vector>
using namespace std;
class Solution {
public:
int change(int amount, vector<int>& coins) {
vector<int>dp(amount+1,0);
dp[0]=1;
for(auto x:coins)
{
for(int i=x;i<=amount;i++)
{
dp[i]=dp[i]+dp[i-x];
}
}
return dp[amount];
}
};
int main() {
vector<int>m={1,2,5};
int target=5;
Solution soln;
int result=soln.change(target,m);
cout<<result;
return 0;
}
| true |
c27ff897fbe77de7fd7c1bb6e437b3e7edc80abb | C++ | danegottwald/OpenGL | /src/vendor/include/glm/ext/scalar_common.inl | UTF-8 | 3,457 | 2.59375 | 3 | [] | no_license | namespace glm {
template<typename T>
GLM_FUNC_QUALIFIER T
min(T
a,
T b, T
c) {
return
glm::min(glm::min(a, b), c
);
}
template<typename T>
GLM_FUNC_QUALIFIER T
min(T
a,
T b, T
c,
T d
)
{
return
glm::min(glm::min(a, b), glm::min(c, d)
);
}
template<typename T>
GLM_FUNC_QUALIFIER T
max(T
a,
T b, T
c)
{
return
glm::max(glm::max(a, b), c
);
}
template<typename T>
GLM_FUNC_QUALIFIER T
max(T
a,
T b, T
c,
T d
)
{
return
glm::max(glm::max(a, b), glm::max(c, d)
);
}
# if GLM_HAS_CXX11_STL
using std::fmin;
# else
template<typename T>
GLM_FUNC_QUALIFIER T
fmin(T
a,
T b
)
{
GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559,
"'fmin' only accept floating-point input");
if (
isnan(a)
)
return
b;
return
min(a, b
);
}
# endif
template<typename T>
GLM_FUNC_QUALIFIER T
fmin(T
a,
T b, T
c)
{
GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559,
"'fmin' only accept floating-point input");
if (
isnan(a)
)
return
fmin(b, c
);
if (
isnan(b)
)
return
fmin(a, c
);
if (
isnan(c)
)
return
min(a, b
);
return
min(a, b, c
);
}
template<typename T>
GLM_FUNC_QUALIFIER T
fmin(T
a,
T b, T
c,
T d
)
{
GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559,
"'fmin' only accept floating-point input");
if (
isnan(a)
)
return
fmin(b, c, d
);
if (
isnan(b)
)
return
min(a, fmin(c, d)
);
if (
isnan(c)
)
return
fmin(min(a, b), d
);
if (
isnan(d)
)
return
min(a, b, c
);
return
min(a, b, c, d
);
}
# if GLM_HAS_CXX11_STL
using std::fmax;
# else
template<typename T>
GLM_FUNC_QUALIFIER T
fmax(T
a,
T b
)
{
GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559,
"'fmax' only accept floating-point input");
if (
isnan(a)
)
return
b;
return
max(a, b
);
}
# endif
template<typename T>
GLM_FUNC_QUALIFIER T
fmax(T
a,
T b, T
c)
{
GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559,
"'fmax' only accept floating-point input");
if (
isnan(a)
)
return
fmax(b, c
);
if (
isnan(b)
)
return
fmax(a, c
);
if (
isnan(c)
)
return
max(a, b
);
return
max(a, b, c
);
}
template<typename T>
GLM_FUNC_QUALIFIER T
fmax(T
a,
T b, T
c,
T d
)
{
GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559,
"'fmax' only accept floating-point input");
if (
isnan(a)
)
return
fmax(b, c, d
);
if (
isnan(b)
)
return
max(a, fmax(c, d)
);
if (
isnan(c)
)
return
fmax(max(a, b), d
);
if (
isnan(d)
)
return
max(a, b, c
);
return
max(a, b, c, d
);
}
// fclamp
template<typename genType>
GLM_FUNC_QUALIFIER genType
fclamp(genType
x,
genType minVal, genType
maxVal)
{
GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559,
"'fclamp' only accept floating-point or integer inputs");
return
fmin(fmax(x, minVal), maxVal
);
}
template<typename genType>
GLM_FUNC_QUALIFIER genType
clamp(genType
const& Texcoord)
{
return
glm::clamp(Texcoord,
static_cast<genType>(0), static_cast<genType>(1));
}
template<typename genType>
GLM_FUNC_QUALIFIER genType
repeat(genType
const& Texcoord)
{
return
glm::fract(Texcoord);
}
template<typename genType>
GLM_FUNC_QUALIFIER genType
mirrorClamp(genType
const& Texcoord)
{
return
glm::fract(glm::abs(Texcoord)
);
}
template<typename genType>
GLM_FUNC_QUALIFIER genType
mirrorRepeat(genType
const& Texcoord)
{
genType const Abs = glm::abs(Texcoord);
genType const Clamp = glm::mod(glm::floor(Abs), static_cast<genType>(2));
genType const Floor = glm::floor(Abs);
genType const Rest = Abs - Floor;
genType const Mirror = Clamp + Rest;
return
mix(Rest,
static_cast<genType>(1) - Rest, Mirror >= static_cast<genType>(1));
}
}//namespace glm
| true |
e7cfa62241f23f52c4dd739340fb52e4b6f1a251 | C++ | 2109/win32lualib | /oolua/unit_tests/cpp_classes/cpp_function_params.h | UTF-8 | 2,367 | 2.703125 | 3 | [
"MIT"
] | permissive | #ifndef CPP_FUNCTION_PARAMS_H_
# define CPP_FUNCTION_PARAMS_H_
# include "oolua_tests_pch.h"
# include "gmock/gmock.h"
template<typename Specialisation , typename ParamType>
class FunctionParamType
{
public:
virtual ~FunctionParamType(){}
/**[ValueParam]*/
virtual void value(ParamType instance) = 0;
/**[ValueParam]*/
/**[PtrParam]*/
virtual void ptr(ParamType* instance) = 0;
/**[PtrParam]*/
/**[RefParam]*/
virtual void ref(ParamType& instance)=0;
/**[RefParam]*/
/**[RefPtrParam]*/
virtual void refPtr(ParamType*& instance) = 0;
/**[RefPtrParam]*/
virtual void constant(ParamType const instance) = 0;
virtual void refConst(ParamType const & instance) = 0;
virtual void ptrConst(ParamType const * instance) = 0;
/**[RefPtrConstParam]*/
virtual void refPtrConst(ParamType const* & instance) = 0;
/**[RefPtrConstParam]*/
virtual void constPtr(ParamType * const instance) = 0;
virtual void refConstPtr(ParamType * const& instance) = 0;
virtual void constPtrConst(ParamType const * const instance) = 0;
virtual void refConstPtrConst(ParamType const * const & instance) = 0;
virtual void twoRefs(ParamType & instance1, ParamType & instance2) = 0;
};
#ifdef _MSC_VER
/* I do not understand this warning for Visual Studio as the functions parameters are the same,
that is unless googlemock is doing something really strange?
Anyway, a big bag of Shhhhhhh
*/
# pragma warning(push)
# pragma warning(disable : 4373)
#endif
template<typename Specialisation , typename ParamType>
class MockFunctionParamType : public FunctionParamType<Specialisation, ParamType>
{
public:
MOCK_METHOD1_T(value, void(ParamType));
MOCK_METHOD1_T(ptr, void(ParamType*)); // NOLINT(readability/function)
MOCK_METHOD1_T(ref, void(ParamType&));
MOCK_METHOD1_T(refPtr, void(ParamType*&));
MOCK_METHOD1_T(constant, void(ParamType const));
MOCK_METHOD1_T(refConst, void(ParamType const &));
MOCK_METHOD1_T(ptrConst, void(ParamType const *));
MOCK_METHOD1_T(refPtrConst, void(ParamType const* &));
MOCK_METHOD1_T(constPtr, void(ParamType * const));
MOCK_METHOD1_T(refConstPtr, void(ParamType * const&));
MOCK_METHOD1_T(constPtrConst, void(ParamType const * const));
MOCK_METHOD1_T(refConstPtrConst, void(ParamType const * const &));
MOCK_METHOD2_T(twoRefs, void(ParamType &, ParamType &));
};
#ifdef _MSC_VER
# pragma warning(pop)
#endif
#endif
| true |
f021a397c4548beca9e9be98ae9feec67b1c65e6 | C++ | SimonRene/LikeMinecraft | /GameEngine/include/mesh.h | UTF-8 | 1,589 | 2.609375 | 3 | [] | no_license | #pragma once
#include <vector>
#include <string>
#include <glm/glm.hpp>
#include "../texture.h"
namespace GE {
enum MeshType {
COLORED_MESH,
TEXTURED_MESH
};
class ShaderProgram;
class Mesh {
public:
virtual void draw(ShaderProgram* shader) = 0;
virtual void setupMesh() = 0;
protected:
unsigned int VAO, VBO, EBO;
std::vector<unsigned int> indices;
};
class TexturedMesh : public Mesh {
public:
struct TexturedVertex {
TexturedVertex(glm::vec3 pos, glm::vec3 normal, glm::vec2 textureCoordinate);
glm::vec3 Position;
glm::vec3 Normal;
glm::vec2 TextureCoordinate;
};
public:
// mesh data
TexturedMesh();
//TexturedMesh(std::vector<TexturedVertex> vertices, std::vector<unsigned int> indices);
void draw(ShaderProgram* shader);
void setupMesh();
unsigned int addVertex(glm::vec3 point, glm::vec3 normal, glm::vec2 textureCoordinate);
void addTriangleToMesh(unsigned int vertex1, unsigned int vertex2, unsigned int vertex3);
private:
std::vector<TexturedVertex> vertices;
//Texture texture;
};
/*
class TexturedMesh : public Mesh {
public:
struct TextureVertex {
TextureVertex(glm::vec3 pos, glm::vec3 normal, glm::vec2 texureCoordinate);
glm::vec3 Position;
glm::vec3 Normal;
glm::vec2 TeturexCoordinates;
};
// mesh data
std::vector<TextureVertex> vertices;
std::vector<Texture> textures;
TexturedMesh(std::vector<TextureVertex> vertices, std::vector<unsigned int> indices, std::vector<Texture> textures);
void Draw(ShaderProgram& shader);
private:
};
*/
} | true |
90b7b45aa58ef65d194fffa188564cf9e53d145a | C++ | DMLfor/leetcode | /1-10/8_string_to_interger_atoi.cpp | UTF-8 | 1,454 | 2.84375 | 3 | [] | no_license | class Solution
{
public:
int myAtoi(string str)
{
int flag = 0, mark = 0, i = 0;
string MIN = "2147483648", MAX = "2147483647";
int dmin = -2147483648, dmax = 2147483647;
while(str[i] == ' ' && i<str.size())
i++;
// cout<<i<<endl;
if(i >= str.size())
return 0;
if(str[i] == '-')
flag = 1;
string digit = "";
// cout<<flag<<endl;
// cout<<"yes"<<endl;
if(str[i] == '-' || str[i] == '+')
{
i++;
//cout<<str[i]<<endl;
while(str[i] == '0')
{
if(str[i] == '+' && flag == 1 || str[i] == '-' && flag == 0)
return 0;
i++;
}
}
// cout<<str[i]<<endl;
while(i<str.size())
{
if(str[i]<='9' && str[i]>='0')
digit += str[i];
else break;
i++;
}
if(flag == 1)
{
if(digit.size() > MIN.size() || digit.size() == MIN.size() && digit > MIN)
return dmin;
}
else
{
if(digit.size() > MAX.size() || digit.size() == MAX.size() && digit > MAX)
return dmax;
}
int ans = 0;
for(int i = 0; i<digit.size(); i++)
ans = ans*10 + digit[i] - '0';
if(flag)
ans *= -flag;
return ans;
}
};
| true |
52f993c5d9daed0142163cc582f11396a69f1685 | C++ | alienxcn/LeetCodeAcceptedCode | /MEDIUM/[TREE]_987_Vertical Order Traversal of a Binary Tree.cpp | UTF-8 | 1,017 | 3.140625 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
map<int, vector<pair<int, int>>> m;
void dfs(TreeNode* root, int x, int y){
if(root == NULL)
return;
m[x].push_back({y, root->val});
dfs(root->left, x-1, y+1);
dfs(root->right, x+1, y+1);
}
vector<vector<int>> verticalTraversal(TreeNode* root) {
dfs(root, 0, 0);
vector<vector<int>> res;
map<int, vector<pair<int, int>>>::iterator iter = m.begin();
for(; iter!=m.end(); iter++){
vector<int> temp;
sort(iter->second.begin(), iter->second.end());
vector<pair<int, int>>::iterator it = iter->second.begin();
for(; it!=iter->second.end(); it++)
temp.push_back(it->second);
res.push_back(temp);
}
return res;
}
}; | true |
a9ccd8562e542d227323ac16acba539170f75412 | C++ | Mohamed-Ali-Mohamed/Chess | /Chess/King.cpp | UTF-8 | 1,463 | 2.921875 | 3 | [] | no_license | #include"King.h"
#include"ChessBoard.h"
#include"GLOBALS.h"
vector<Possible_Move> King::move()
{
ChessPiecePosition current_position;
Possible_Move possible_move;
///////////////////////////////////////
vector< vector<ChessPiece*> > Board = ChessBoard::GetBoard();
vector<Possible_Move> All_Possible_Positions;
current_position = GetPosition();
bool Current_White = GetWhite();
////
int dx[]={1,1,0,-1,-1,-1, 0, 1};
int dy[]={0,1,1, 1, 0,-1,-1,-1};
////
for(int i=0 ; i<8 ; i++)
{
int x=current_position.x+dx[i];
int y=current_position.y+dy[i];
if(x>=0 && x<8 && y>=0 && y<8)
{
ChessPiece NewPiece = *Board[y][x];
ChessPiecePosition p;
p.x=x;
p.y=y;
if(NewPiece.GetName() == "")
{
possible_move.position=p;
possible_move.Action=GLOBALS::Action_Move;
All_Possible_Positions.push_back(possible_move);
}
else
{
if(NewPiece.GetWhite() != Current_White)
{
possible_move.position=p;
possible_move.Action=GLOBALS::Action_Attack;
All_Possible_Positions.push_back(possible_move);
}
}
}
}
return All_Possible_Positions;
}
void King::Draw(RenderWindow &window)
{
Texture texture;
Sprite sprite;
if(this->GetWhite())
texture.loadFromFile("Graphics\\KingW.png");
else
texture.loadFromFile("Graphics\\KingB.png");
sprite.setTexture(texture);
sprite.setPosition(this->GetPosition().x * Board_Square_Width,this->GetPosition().y * Board_Square_Height);
window.draw(sprite);
} | true |
8154be001720e256527ddfef31b6efc51aa48d15 | C++ | nitasn/SearchingAlgoServer | /log_info.cpp | UTF-8 | 570 | 2.796875 | 3 | [] | no_license | //
// Created by Nitsan BenHanoch on 29/01/2020.
//
#include <iostream>
#include "log_info.h"
using namespace std;
class IgnoreStream : public ostream
{
public:
IgnoreStream() : ostream(nullptr) {}
IgnoreStream(const IgnoreStream &) : ostream(nullptr) {}
};
template<class T>
const IgnoreStream &operator<<(IgnoreStream &&os, const T &value)
{
return os;
}
IgnoreStream nowhere;
// todo make log_info an object that inherit ostream and contains the methods:
// + output_to_cout
// + output_to_nowhere
ostream &log_info = nowhere;
//ostream &log_info = cout; | true |
c20fdf1fa67d4ef34b9460279ba439f63ec2e48b | C++ | snoplus/oxsx | /src/fitutil/EventSystematicManager.cpp | UTF-8 | 749 | 2.71875 | 3 | [] | no_license | #include <EventSystematicManager.h>
#include <EventSystematic.h>
#include <Event.h>
void
EventSystematicManager::Clear(){
fSystematics.clear();
}
void
EventSystematicManager::Add(EventSystematic* sys_){
fSystematics.push_back(sys_);
}
const std::vector<EventSystematic*>&
EventSystematicManager::GetSystematics() const{
return fSystematics;
}
size_t
EventSystematicManager::GetNSystematics() const{
return fSystematics.size();
}
Event
EventSystematicManager::ApplySystematics(const Event& event_) const{
if (!fSystematics.size())
return event_;
Event modified = event_;
for(size_t i = 0; i < fSystematics.size(); i++)
modified = fSystematics.at(i)->operator()(modified);
return modified;
}
| true |
4068166ff65b684c7eacdd58ed7a00a0990188bc | C++ | mdepp/3d-rendering | /3D Rendering/GameEngine.cpp | UTF-8 | 4,370 | 2.53125 | 3 | [] | no_license | #include "GameEngine.h"
GameEngine::GameEngine()
{
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
cerr << "Error in GameEngine::GameEngine() - " << SDL_GetError() << endl;
}
else
{
window = NULL;
window = SDL_CreateWindow("3D Rendering", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (window == NULL)
{
cerr << "Error in GameEngine::GameEngine() - " << SDL_GetError() << endl;
}
else
{
screenSurface = SDL_GetWindowSurface(window);
}
}
renderer = new RenderingEngine(this);
player.getCamera()->setPosition(glm::vec3(0, 0, 500));
player.getCamera()->setDirection(glm::vec3(0, 0, -1));
models.push_back(Model());
models.back().loadFromFile("TIEF.3DS", "tief3DS/");
models.back().setScale(glm::vec3(100, 100, 100));
models.back().setTranslation(glm::vec3(0, 0 , 0));
lights.push_back(Light(glm::normalize(glm::vec4(1, 0, 1, 0)), glm::vec3(255, 255, 255), .3f, Light::TYPE_DIFFUSE));
lights.push_back(Light(glm::vec4(0, 0, 1, 0), glm::vec3(255, 255, 255), 0.5, Light::TYPE_DIFFUSE));
lights.push_back(Light(glm::vec4(0, 0, -1, 0), glm::vec3(255, 255, 255), 0.03f, Light::TYPE_AMBIENT));
}
GameEngine::~GameEngine()
{
delete renderer;
SDL_DestroyWindow(window);
SDL_Quit();
}
static void putpixel(SDL_Surface *surface, int x, int y, Uint32 pixel)
{
int bpp = surface->format->BytesPerPixel;
/* Here p is the address to the pixel we want to set */
Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;
switch (bpp) {
case 1:
*p = pixel;
break;
case 2:
*(Uint16 *)p = pixel;
break;
case 3:
if (SDL_BYTEORDER == SDL_BIG_ENDIAN) {
p[0] = (pixel >> 16) & 0xff;
p[1] = (pixel >> 8) & 0xff;
p[2] = pixel & 0xff;
}
else {
p[0] = pixel & 0xff;
p[1] = (pixel >> 8) & 0xff;
p[2] = (pixel >> 16) & 0xff;
}
break;
case 4:
*(Uint32 *)p = pixel;
break;
}
}
void GameEngine::mainLoop()
{
SDL_Event event;
bool quit = false;
SDL_ShowCursor(false);
bool wPressed = false, sPressed = false, aPressed = false, dPressed = false;
glm::vec2 moveDir;
while (!quit)
{
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT) quit = true;
else if (event.type == SDL_KEYDOWN)
{
if (event.key.keysym.sym == SDLK_ESCAPE) quit = true;
if (event.key.keysym.sym == SDLK_w) wPressed = true;
if (event.key.keysym.sym == SDLK_a) aPressed = true;
if (event.key.keysym.sym == SDLK_s) sPressed = true;
if (event.key.keysym.sym == SDLK_d) dPressed = true;
}
else if (event.type == SDL_KEYUP)
{
if (event.key.keysym.sym == SDLK_w) wPressed = false;
if (event.key.keysym.sym == SDLK_a) aPressed = false;
if (event.key.keysym.sym == SDLK_s) sPressed = false;
if (event.key.keysym.sym == SDLK_d) dPressed = false;
}
else if (event.type == SDL_MOUSEMOTION)
{
if (event.motion.x != HALF_SCREEN_WIDTH || event.motion.y != HALF_SCREEN_HEIGHT)
{
player.getCamera()->rotateY((HALF_SCREEN_WIDTH - event.motion.x) / 100.f);
player.getCamera()->rotateX(-(HALF_SCREEN_HEIGHT - event.motion.y) / 100.f);
SDL_WarpMouseInWindow(window, HALF_SCREEN_WIDTH, HALF_SCREEN_HEIGHT);
}
}
}
// Process
if (wPressed) moveDir.y = 1;
else if (sPressed) moveDir.y = -1;
else moveDir.y = 0;
if (dPressed) moveDir.x = 1;
else if (aPressed) moveDir.x = -1;
else moveDir.x = 0;
{
static int lastTime = SDL_GetTicks(), deltaTime;
deltaTime = SDL_GetTicks() - lastTime;
player.moveByDirection(moveDir, 0.05f*deltaTime);
lastTime = SDL_GetTicks();
}
{
static int lastTime = SDL_GetTicks(), deltaTime;
deltaTime = SDL_GetTicks() - lastTime;
models[0].rotate(0.00005f*deltaTime, glm::vec3(0, 0, 1));
lastTime = SDL_GetTicks();
}
// Rendering code
renderer->setViewMatrix(player.getCamera()->getViewMatrix());
vector<vector<DepthPixel>>* buffer = renderer->renderModels(models, lights);
{
static SDL_Rect r = { 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT };
SDL_FillRect(screenSurface, &r, 0x000000);
for (int i = 0; i < SCREEN_WIDTH; i++)
{
for (int j = 0; j < SCREEN_HEIGHT; j++)
{
if ((*buffer)[i][j].depth < 0) continue;
putpixel(screenSurface, i, j, SDL_MapRGBA(screenSurface->format, (*buffer)[i][j].r, (*buffer)[i][j].g, (*buffer)[i][j].b, 1));
}
}
SDL_UpdateWindowSurface(window);
}
}
} | true |
749d86e26cc8e8e8cbbb54d47d0fe1486ecefd77 | C++ | FunnyPhantom/ACM_SUMMER_CAMP | /Training/week_4_classroom/entekhab.cpp | UTF-8 | 775 | 2.53125 | 3 | [] | no_license | //
// Created by Mohamad on 8/5/2018.
//
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int max_nk = 1003;
ll dp[max_nk][max_nk];
ll peymane = 1e9 + 7;
void init() {
for (int i = 0; i < max_nk; ++i) {
for (int j = 0; j < max_nk; ++j) {
dp[i][j] = -1;
}
}
}
long long entekhab(int n, int k) {
if (n <= 0) return 0;
if (k == 1) return n;
if (n == k) return 1;
if (k > n) return 0;
if (dp[n][k] != -1) return dp[n][k];
dp[n][k] = (entekhab(n - 1, k - 1) + entekhab(n - 1, k)) % peymane;
return dp[n][k];
}
int main() {
// ios_base::sync_with_stdio(false);
// cin.tie(NULL);
int n, k;
cin >> n >> k;
init();
cout << entekhab(n, k) << endl;
return 0;
} | true |
fd9019a8d7a7f448426155fb9da9060b71fcd765 | C++ | thomas-westfall/labs-136 | /project1/sum.cpp | UTF-8 | 340 | 3.28125 | 3 | [] | no_license | //Thomas Westfall
//Lab 1 CSCI 135
#include <iostream>
using namespace std;
int main() {
int val; //current value
int ans = 0; //sum of the values
while(cin >> val) { // While there are still values to add
ans = ans + val; //adds the integer to the current sum
}
cout<<ans<<endl; //print the answer when the loop finishes
}
| true |
2835f9ca3af9232767ce5500848e989a50c2fa35 | C++ | MINDS-i/MINDS-i-LaserTarget | /src/sample.cpp | UTF-8 | 1,358 | 2.75 | 3 | [
"Apache-2.0"
] | permissive | #include "sample.h"
sample::sample() :m_win_start_time(0), m_num_values_read(0), m_win_span(0)
{
;
}
sample::~sample() {
;
}
bool sample::Init(unsigned long timer, unsigned long win_span) {
m_win_span = win_span;
reset(timer);
}
void sample::reset(unsigned long timer) {
m_win_start_time = timer;
m_num_values_read = 0;
for (int i = 0; i < NUMSENSORS; i++) {
m_culmSumValues[i] = 0.f;
}
}
bool sample::Exec(unsigned long timer, int sensorValues[]) {
unsigned long dtime = timer - m_win_start_time;
if (dtime >= m_win_span) {
windowEnd(sensorValues);
reset(timer);
return false;
}
/*
for (int i = 0; i < NUMSENSORS; i++) {
m_culmSumValues[i] += ((float)sensorValues[i]);
}
m_num_values_read++;
*/
return true;
}
bool sample::GetValues(int values[]) {
for (int i = 0; i < NUMSENSORS; i++) {
values[i] = m_values[i];
}
return true;
}
void sample::windowEnd(int sensorValues[]) {
/*simplified version due to odd lock up for low sample time intervals*/
for(int i=0; i<NUMSENSORS;i++){
m_values[i]=sensorValues[i];
}
//if (m_num_values_read > 0) {
/*
float num_values_read = (float)m_num_values_read;
for (int i = 0; i < NUMSENSORS; i++) {
m_culmSumValues[i] /= num_values_read;
m_values[i] = ((int)roundf(m_culmSumValues[i]));
}
*/
//}
}
| true |
8abd8bbfca1c1cf6ff2a6aad6a75401aab4922be | C++ | jeremy-coulon/boostgeometryvector | /include/BoostGeometryVector/strategies/cartesian/length_pythagoras.hpp | UTF-8 | 12,140 | 2.53125 | 3 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // Copyright Jeremy Coulon 2012-2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#pragma once
//===========================
//== BoostGeometryVector ==
//===========================
#include "BoostGeometryVector/geometries/concepts/vector_concept.hpp"
#include "BoostGeometryVector/strategies/tags.hpp"
#include "BoostGeometryVector/strategies/length.hpp"
//=============
//== Boost ==
//=============
#include <boost/numeric/conversion/cast.hpp>
#include <boost/geometry/util/calculation_type.hpp>
#include <boost/geometry/geometries/concepts/check.hpp>
namespace boost
{
namespace geometry
{
namespace strategy
{
namespace length
{
#ifndef DOXYGEN_NO_DETAIL
namespace detail
{
template <typename Geometry1, size_t I, typename T>
struct compute_pythagoras
{
static inline T apply(Geometry1 const& g1)
{
T const d = boost::numeric_cast<T>(get<I-1>(g1));
return d * d + compute_pythagoras<Geometry1, I-1, T>::apply(g1);
}
};
template <typename Geometry1, typename T>
struct compute_pythagoras<Geometry1, 0, T>
{
static inline T apply(Geometry1 const&)
{
return boost::numeric_cast<T>(0);
}
};
} // namespace detail
#endif
namespace comparable
{
/*!
\brief Strategy to calculate comparable length between two vectors
\ingroup strategies
\tparam Vector \tparam_vector
\tparam CalculationType \tparam_calculation
*/
template
<
typename Vector,
typename CalculationType = void
>
class pythagoras
{
public:
/// numeric type for calculation
typedef typename util::calculation_type::geometric::unary
<
Vector,
CalculationType
>::type calculation_type;
/*!
\brief applies the comparable length calculation using pythagoras
\return the calculated comparable length (not taking the square root)
\param v vector
*/
static inline calculation_type apply(Vector const& v)
{
BOOST_CONCEPT_ASSERT( (concept::ConstVector<Vector>) );
// Calculate distance using Pythagoras
return detail::compute_pythagoras
<
Vector,
dimension<Vector>::value,
calculation_type
>::apply(v);
}
};
} // namespace comparable
/*!
\brief Strategy to calculate the length of vector
\ingroup strategies
\tparam Vector \tparam_vector
\tparam CalculationType \tparam_calculation
*/
template
<
typename Vector,
typename CalculationType = void
>
class pythagoras
{
typedef comparable::pythagoras<Vector, CalculationType> comparable_type;
public:
/// numeric type for calculation
typedef typename util::calculation_type::geometric::unary
<
Vector,
CalculationType,
double,
double // promote integer to double
>::type calculation_type;
/*!
\brief applies the length calculation using pythagoras
\return the calculated length (including taking the square root)
\param v vector
*/
static inline calculation_type apply(Vector const& v)
{
calculation_type const t = comparable_type::apply(v);
return sqrt(t);
}
};
#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS
namespace services
{
template <typename Vector, typename CalculationType>
struct tag<pythagoras<Vector, CalculationType> >
{
typedef strategy_tag_length_vector type;
};
template <typename Vector, typename CalculationType>
struct return_type<pythagoras<Vector, CalculationType> >
{
typedef typename pythagoras<Vector, CalculationType>::calculation_type type;
};
template
<
typename Vector1,
typename CalculationType,
typename V1
>
struct similar_type<pythagoras<Vector1, CalculationType>, V1>
{
typedef pythagoras<V1, CalculationType> type;
};
template
<
typename Vector1,
typename CalculationType,
typename V1
>
struct get_similar<pythagoras<Vector1, CalculationType>, V1>
{
static inline typename similar_type
<
pythagoras<Vector1, CalculationType>, V1
>::type apply(pythagoras<Vector1, CalculationType> const& )
{
return pythagoras<V1, CalculationType>();
}
};
template <typename Vector1, typename CalculationType>
struct comparable_type<pythagoras<Vector1, CalculationType> >
{
typedef comparable::pythagoras<Vector1, CalculationType> type;
};
template <typename Vector1, typename CalculationType>
struct get_comparable<pythagoras<Vector1, CalculationType> >
{
typedef comparable::pythagoras<Vector1, CalculationType> comparable_type;
public :
static inline comparable_type apply(pythagoras<Vector1, CalculationType> const& )
{
return comparable_type();
}
};
template <typename Vector1, typename CalculationType>
struct result_from_length<pythagoras<Vector1, CalculationType> >
{
private :
typedef typename return_type<pythagoras<Vector1, CalculationType> >::type return_type;
public :
template <typename T>
static inline return_type apply(pythagoras<Vector1, CalculationType> const& , T const& value)
{
return return_type(value);
}
};
// Specializations for comparable::pythagoras
template <typename Vector1, typename CalculationType>
struct tag<comparable::pythagoras<Vector1, CalculationType> >
{
typedef strategy_tag_length_vector type;
};
template <typename Vector1, typename CalculationType>
struct return_type<comparable::pythagoras<Vector1, CalculationType> >
{
typedef typename comparable::pythagoras<Vector1, CalculationType>::calculation_type type;
};
template
<
typename Vector1,
typename CalculationType,
typename V1
>
struct similar_type<comparable::pythagoras<Vector1, CalculationType>, V1>
{
typedef comparable::pythagoras<V1, CalculationType> type;
};
template
<
typename Vector1,
typename CalculationType,
typename V1
>
struct get_similar<comparable::pythagoras<Vector1, CalculationType>, V1>
{
static inline typename similar_type
<
comparable::pythagoras<Vector1, CalculationType>, V1
>::type apply(comparable::pythagoras<Vector1, CalculationType> const& )
{
return comparable::pythagoras<V1, CalculationType>();
}
};
template <typename Vector1, typename CalculationType>
struct comparable_type<comparable::pythagoras<Vector1, CalculationType> >
{
typedef comparable::pythagoras<Vector1, CalculationType> type;
};
template <typename Vector1, typename CalculationType>
struct get_comparable<comparable::pythagoras<Vector1, CalculationType> >
{
typedef comparable::pythagoras<Vector1, CalculationType> comparable_type;
public :
static inline comparable_type apply(comparable::pythagoras<Vector1, CalculationType> const& )
{
return comparable_type();
}
};
template <typename Vector1, typename CalculationType>
struct result_from_length<comparable::pythagoras<Vector1, CalculationType> >
{
private :
typedef typename return_type<comparable::pythagoras<Vector1, CalculationType> >::type return_type;
public :
template <typename T>
static inline return_type apply(comparable::pythagoras<Vector1, CalculationType> const& , T const& value)
{
return_type const v = value;
return v * v;
}
};
template <typename Geometry1>
struct default_strategy<vector_tag, Geometry1, cartesian_tag, void>
{
typedef pythagoras<Geometry1> type;
};
} // namespace services
#endif
} // namespace length
} // namespace strategy
} // namespace geometry
} // namespace boost
| true |
4c9f9a996c08d978be14988bf6a6a03419a11213 | C++ | araafario/opencv_learn | /opencv_10_detectionClick/main.cpp | UTF-8 | 5,708 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
bool enable,clicked;
Mat imgOriginal;
int iLowH = 0;
int iHighH = 179;
int iLowS = 0;
int iHighS = 255;
int iLowV = 0;
int iHighV = 255;
String control = "Control";
String original = "Original";
String thresholded = "threshold";
void eventHandler(int event, int x, int y, int flags, void* param){
if(event == EVENT_RBUTTONDOWN && clicked == false){
clicked = true;
Mat image = imgOriginal.clone();
Vec3b rgb = image.at < Vec3b > (y, x);
int B = rgb.val[0];
int G = rgb.val[1];
int R = rgb.val[2];
Mat HSV;
Mat RGB = image(Rect(x, y, 1, 1));
cvtColor(RGB, HSV, COLOR_BGR2HSV);
Vec3b hsv = HSV.at < Vec3b > (0, 0);
iLowH = hsv.val[0];
iLowS = hsv.val[1];
iLowV = hsv.val[2];
cout << iLowH << " " << iLowS << " " << iLowV << endl;
}
if(event == EVENT_RBUTTONUP && clicked == true){
clicked = false;
}
}
void trackBar(){
createTrackbar("LowH", "Control", &iLowH, 179); //Hue (0 - 179)
createTrackbar("HighH", "Control", &iHighH, 179);
createTrackbar("LowS", "Control", &iLowS, 255); //Saturation (0 - 255)
createTrackbar("HighS", "Control", &iHighS, 255);
createTrackbar("LowV", "Control", &iLowV, 255); //Value (0 - 255)
createTrackbar("HighV", "Control", &iHighV, 255);
}
void trackBar_update(){
setTrackbarPos("LowH", "Control", iLowH);
setTrackbarPos("HighH", "Control", iHighH);
setTrackbarPos("LowS", "Control", iLowS);
setTrackbarPos("HighS", "Control", iHighS);
setTrackbarPos("LowV", "Control", iLowV);
setTrackbarPos("HighV", "Control", iHighV);
}
int main(int argc, char ** argv) {
VideoCapture cap(0); //capture the video from webcam
if (!cap.isOpened()) // if not success, exit program
{
cout << "Cannot open the web cam" << endl;
return -1;
}
enable = clicked = false;
namedWindow(control, WINDOW_NORMAL); //create a window called "Control"
namedWindow(original, WINDOW_NORMAL); //create a window called "Control"
namedWindow(thresholded, WINDOW_NORMAL); //create a window called "Control"
resizeWindow(control,200,100);
resizeWindow(original,1280/2,720/2);
resizeWindow(thresholded,1280/2,720/2);
//Create trackbars in "Control" window
createTrackbar("LowH", "Control", &iLowH, 179); //Hue (0 - 179)
createTrackbar("HighH", "Control", &iHighH, 179);
createTrackbar("LowS", "Control", &iLowS, 255); //Saturation (0 - 255)
createTrackbar("HighS", "Control", &iHighS, 255);
createTrackbar("LowV", "Control", &iLowV, 255); //Value (0 - 255)
createTrackbar("HighV", "Control", &iHighV, 255);
setMouseCallback(original, eventHandler);
int iLastX = -1;
int iLastY = -1;
//Capture a temporary image from the camera
Mat imgTmp;
cap.read(imgTmp);
//Create a black image with the size as the camera output
Mat imgLines = Mat::zeros(imgTmp.size(), CV_8UC3);;
while (true) {
bool bSuccess = cap.read(imgOriginal); // read a new frame from video
if (!bSuccess) //if not success, break loop
{
cout << "Cannot read a frame from video stream" << endl;
break;
}
Mat imgHSV;
cvtColor(imgOriginal, imgHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV
Mat imgThresholded;
inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image
//morphological opening (removes small objects from the foreground)
erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
//morphological closing (removes small holes from the foreground)
dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
//Calculate the moments of the thresholded image
Moments oMoments = moments(imgThresholded);
double dM01 = oMoments.m01;
double dM10 = oMoments.m10;
double dArea = oMoments.m00;
// if the area <= 10000, I consider that the there are no object in the image and it's because of the noise, the area is not zero
if (dArea > 10000) {
//calculate the position of the ball
int posX = dM10 / dArea;
int posY = dM01 / dArea;
if (iLastX >= 0 && iLastY >= 0 && posX >= 0 && posY >= 0) {
//Draw a red line from the previous point to the current point
if (enable == true) line(imgLines, Point(posX, posY), Point(iLastX, iLastY), Scalar(0, 0, 255), 5);
}
iLastX = posX;
iLastY = posY;
}
Mat flipTresholded;
flip(imgThresholded,flipTresholded,1);
imshow(thresholded, flipTresholded); //show the thresholded image
imgOriginal = imgOriginal + imgLines;
Mat flipOriginal;
flip(imgOriginal,flipOriginal,1);
imshow(original, flipOriginal); //show the original image
trackBar();
trackBar_update();
if (waitKey(1) == 122) enable ^= true;
if (waitKey(1) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
{
cout << "esc key is pressed by user" << endl;
break;
}
}
return 0;
} | true |
68ce7a1dd3ef8a53cd360e589c5430f54d75b412 | C++ | phillipchan124/Program-Design-Data-Structures | /Lab13/MySortableStaticArray.cpp | UTF-8 | 2,240 | 3.46875 | 3 | [] | no_license | // Lab 13a, Write A Sortable Array Class Template
// Programmer: Kwun Hang Chan
// Editor(s) used: Xcode
// Compliers(s) used: Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)
#include <iostream>
using namespace std;
#include <vector>
#include <cstdlib>
#include <fstream>
#include "SortableStaticArray.h"
const char* const DELIMITER = " ";
int main()
{
// print my name and this assignment's title
cout << "Lab 13a, Write A Sortable Array Class Template\n";
cout << "Programmer: Kwun Hang Chan\n";
cout << "Editor(s) used: Xcode\n";
cout << "Compliers(s) used: Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)\n";
cout << "File: " << __FILE__ << endl;
cout << "Complied: " << __DATE__ << " at " << __TIME__ << endl << endl;
SortableStaticArray<int,100> a;
char buf [100];
const char* token[3] = {};
int index, value;
// input loop
while (true)
{
cout << "Input an index and a value [Q to quit]:";
cin.getline(buf, 200);
token[0] = strtok(buf, DELIMITER); // first token
if(strcmp(token[0], "Q") == 0 || strcmp(token[0], "q") == 0) break;
token[1] = strtok(0, DELIMITER); // second token
index = atoi(token[0]);
value = atoi(token[1]);
a[index] = value;
}
// display all values in static array
cout << "\nI stored this many values: " << a.size() << endl;
cout << "The values are:" << endl;
const SortableStaticArray<int, 100> copy = a;
for (int i = 0; i < copy.capacity(); i++)
if (copy.containsKey(i))
cout << " " << i << " " << copy[i] << endl;
// output loop
while (true)
{
cout << "Input an index for me to look up [Q to quit]:";
cin >> buf;
if (buf[0] == 'Q' || buf[0] == 'q') break;
index = atoi(buf);
if (copy.containsKey(index))
cout << "Found it -- the value stored at "
<< index << " is " << copy[index] << endl;
else
cout << "I didn't find it" << endl;
}
cout << "\nThe stored values are: " << a.size() << endl;
cout << "The values are:" << endl;
a.sort();
const SortableStaticArray<int, 100> copysort = a;
for (int i = 0; i < copysort.capacity(); i++)
if (copysort.containsKey(i))
cout << " " << i << " " << copysort[i] << endl;
} | true |
533bc3973df4790f1dd560e5f122e6d7f381ce93 | C++ | MinhazRahman/CPPBasics | /arrays/linearSearch.cpp | UTF-8 | 522 | 4 | 4 | [] | no_license | #include <iostream>
using namespace std;
//write a program to find an element in an array using linear search
int search(int[]);
//returns the index where the element is found otherwise returns -1
int search(int *arr, int n, int x)
{
for (int i = 0; i < n; i++)
{
if (arr[i] == x)
{
return i;
}
}
return -1;
}
int main()
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int n = sizeof(a) / sizeof(a[0]); // number of elements
cout << "Found element at index: " << search(a, n, 5) << endl;
}
| true |
17635ec8180805a343174a0bf415767897e61b70 | C++ | schme/KoomGL | /src/ks_glutils.cpp | UTF-8 | 3,559 | 2.78125 | 3 | [] | no_license | #include "ks_glutils.h"
#include <assert.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#define PRINT_SHADER_ERROR( shader )\
do {\
GLint logSize = 0;\
glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &logSize);\
GLchar *errorMessage = (GLchar*)malloc( (u32)logSize );\
glGetShaderInfoLog( shader, logSize, NULL, errorMessage);\
std::cout << errorMessage << std::endl;\
free(errorMessage);\
} while(0)
#define PRINT_PROGRAM_ERROR( program)\
do {\
GLint logSize = 0;\
glGetProgramiv( program, GL_INFO_LOG_LENGTH, &logSize);\
char* errorMessage = (char*)malloc( (u32)logSize );\
glGetProgramInfoLog( program, logSize, NULL, errorMessage);\
std::cout << errorMessage << std::endl;\
free(errorMessage);\
} while(0)
inline std::string
fileToString( const char *filename) {
std::ifstream file( filename);
if( !file.is_open()) {
assert( 0 && "FAIL: Opening file ");
std::string msg("FAIL: Opening file: ");
msg += filename; msg += "\n";
std::cout << msg.c_str() << std::endl;
}
std::stringstream buffer;
buffer << file.rdbuf();
file.close();
return buffer.str();
}
GLint
loadShader( const char *filename, GLenum shaderType) {
GLint shader = 0;
std::string shaderStr = fileToString( filename);
assert(!shaderStr.empty());
shader = glCreateShader( shaderType);
glShaderSource( shader, 1, (const GLchar**)&shaderStr, NULL);
glCompileShader( shader);
GLint status;
glGetShaderiv( shader, GL_COMPILE_STATUS, &status);
if( status == GL_FALSE) {
#if ENABLE_CONSOLE
PRINT_SHADER_ERROR( shader);
#endif
assert(!"Shader didn't compile!");
} else {
#if ENABLE_CONSOLE
printf("Shader compilation succeeded\n");
#endif
}
return shader;
}
GLint
createProgram(const char *vertex, const char *fragment) {
GLint program = glCreateProgram();
GLint vertexObject = loadShader( vertex, GL_VERTEX_SHADER);
GLint fragmentObject = loadShader( fragment, GL_FRAGMENT_SHADER);
glAttachShader( program, vertexObject);
glAttachShader( program, fragmentObject);
glLinkProgram( program);
glDetachShader( program, vertexObject);
glDetachShader( program, fragmentObject);
GLint status;
glGetProgramiv( program, GL_LINK_STATUS, &status);
if( status == GL_FALSE) {
PRINT_PROGRAM_ERROR( program);
assert(0 && "Shader linking failed!\n");
glDeleteProgram( program );
program = 0;
}
return program;
}
GLint
createProgram(const char *vertex, const char *fragment, const char *geometry) {
GLint program = glCreateProgram();
GLint vertexObject = loadShader( vertex, GL_VERTEX_SHADER);
GLint fragmentObject = loadShader( fragment, GL_FRAGMENT_SHADER);
GLint geometryObject = loadShader( geometry, GL_GEOMETRY_SHADER);
glAttachShader( program, vertexObject);
glAttachShader( program, fragmentObject);
glAttachShader( program, geometryObject);
glLinkProgram( program);
glDetachShader( program, vertexObject);
glDetachShader( program, fragmentObject);
glDetachShader( program, geometryObject);
GLint status;
glGetProgramiv( program, GL_LINK_STATUS, &status);
if( status == GL_FALSE) {
PRINT_PROGRAM_ERROR( program);
assert(0 && "Shader linking failed!\n");
glDeleteProgram( program );
program = 0;
}
return program;
}
| true |
5c4a02063bfbf6836a7f11cf940ce8758abc2886 | C++ | luni64/TeensyTimerTool | /src/API/baseTimer.cpp | UTF-8 | 616 | 2.546875 | 3 | [
"MIT"
] | permissive | #include "baseTimer.h"
//#include "Arduino.h"
#include "types.h"
namespace TeensyTimerTool
{
BaseTimer::BaseTimer(TimerGenerator *generator, bool periodic)
: timerGenerator(generator)
{
this->timerGenerator = generator;
this->timerChannel = nullptr;
this->isPeriodic = periodic;
}
BaseTimer::~BaseTimer()
{
if (timerChannel != nullptr)
{
delete timerChannel;
}
}
errorCode BaseTimer::setPrescaler(int psc)
{
this->prescaler = psc;
return errorCode::OK;
}
} // namespace TeensyTimerTool | true |
9186a2620dcd1c796a1793863416c815763b36b2 | C++ | p-gonzo/cpp_practice | /chp12/listing_12_10.cpp | UTF-8 | 294 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <string>
class Display
{
public:
void operator () (std::string input) const
{
std::cout << input << std::endl;
}
};
int main()
{
Display displayFuncObj;
displayFuncObj("Hello");
displayFuncObj.operator()("World");
return 0;
} | true |
0a33c1cd47b854fe6b0a338beb53186f03f7345f | C++ | akin666/bolt | /lib/core/component/property.hpp | UTF-8 | 1,646 | 2.90625 | 3 | [] | no_license | /*
* property.h
*
* Created on: 14.10.2011
* Author: akin
*
* Property is like the Model from ModelViewController pattern.
* Property adds some properties to the entity, once attached, the entity
* has as set of data, bound to it, inside the Property..
* The arrangement of the data is recommended (for now) to be in array/vector structure,
* so that the whatever modifies the data, has access, in a cache friendly way.
* The Entity is/should be, totally oblivious to the fact, that it has some data structures attached to it.
*
* Calling attach, multiple times should be allowed, BUT the dataset is only created upon first attach.
* Calling detach, should perform detach operation, no matter how many times attach has been called. Detach
* should be considered to be operation, that is called upon entity destruction.
* Detach can be called multiple times, ultimately whether the property uses reference counting with attach/detach
* is the designers decision.
*/
#ifndef COMPONENT_PROPERTY_HPP_
#define COMPONENT_PROPERTY_HPP_
#include <string>
#include <common>
#include <entity.hpp>
namespace bolt
{
class Property
{
protected:
static uint sm_id;
static uint getNewId();
uint id;
std::string name;
public:
Property( std::string name );
virtual ~Property();
virtual void initialize();
std::string getName() const;
uint getId() const;
virtual void attach( Entity& entity ) = 0;
virtual void detach( Entity& entity ) = 0;
};
} /* namespace bolt */
#endif /* COMPONENT_PROPERTY_HPP_ */
| true |
5081c9064bf6723fdf31c032c906fec89a6b7800 | C++ | dantlz/VERY_OLD_Academic_Projects | /Undergraduate_SecondYear/CSCI104/HW3: Array List, Stack, Copy Constructor, Operator Overloading/boolexpr.cpp | UTF-8 | 7,736 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <cstdlib>
#include <utility>
#include <cctype>
#include "stackint.h"
#include <sstream>
using namespace std;
bool toBool(char character);
void printTruth(bool truth, const string t, const string f,string error);
int main(int argc, char* argv[]){
//___________________________________PREPARATION____________________________________________________
//Check for invalid command line inputs
if(argc != 3){
cout << "Please include the correct command line files" << endl;
return 1;
}
//Instream
ifstream expr_file(argv[1]);
ifstream var_file (argv[2]);
//Constants
const string malformed = "Malformed";
const string unknown = "Unknown Variable";
const string noError = "ne";
const string t_String = "T";
const string f_String = "F";
const int open_parenthesis = -10;
const int intAnd = -11;
const int intOr = -12;
const int intNot = -13;
const int t = -1;
const int f = -2;
map<int, char> map;
map.insert(pair<int, char>(-1,'T'));
map.insert(pair<int, char>(-2,'F'));
//_____________________________READ VARIABLE ASSIGNMENT FILE________________________________________
string input;
int variable;
char truthVal;
int counter = 0;
while(var_file >> input){
//Even counter means it is a variable
if(counter % 2 == 0){
variable = atoi(input.c_str());
}
//Odd counter means it is a truth value
else if(counter % 2 != 0){
truthVal=input[0];
//Every time we have an odd counter, it means we have a pair. Insert it.
map.insert(pair<int,char>(variable,truthVal));
}
//Increment the counter
counter++;
}
//___________________________________READ BOOLEAN EXPRESSION FILE___________________________
while(getline(expr_file, input)){
//Check for empty lines
if(input == "")
continue;
bool truth;
string error = noError;
StackInt stack;
//_________________________PUSH EVERYTHING INTO THE STACK___________________________
for(int i = 0;(unsigned)i < input.size()&&error==noError;i++){
if(input[i] == ' '){ /*Ignore blank spaces*/}
else if(input[i] == '&')
stack.push(intAnd);
else if(input[i] == '|')
stack.push(intOr);
else if(input[i] == '~')
stack.push(intNot);
else if(input[i] == '(')
stack.push(open_parenthesis);
else if(input[i] == 'T')
stack.push(t);
else if(input[i] == 'F')
stack.push(f);
//____________________SPECIAL CASE OF MEETING A CLOSING PARENTHESIS_______________
else if(input[i] == ')'){
//____________________GET FIRST FULL INTEGER VALUE BEFORE )_______________________
int value=stack.top();
ostringstream val;
string integer="";
if(value>=0){
while(value>=0){
val.str("");
val<<value;
integer=val.str()+integer;
stack.pop();
value=stack.top();
}
if(map.count(atoi(integer.c_str()))==0){
error = unknown;
break;
}
else
truth=toBool(map[atoi(integer.c_str())]);
}
else if(value==t||value==f){
truth=toBool(map[value]);
stack.pop();
value=stack.top();
}
else{
error = malformed;
break;
}
//Check if (12)
if(value==open_parenthesis){
error=malformed;
break;
}
//__________________LOOP TO CHECK STACK UNTIL OPENING PARENTHESIS___________________
//lock to prevent (2|3&4)
int lock=0;
while(value!=open_parenthesis){
//___________________THE NEXT OPERATOR IS &_____________________________________
if(value==intAnd&&(lock==0||lock==1)){
stack.pop();
value=stack.top();//check malform here
ostringstream val;
integer="";
if(value>=0){
while(value>=0){
val.str("");
val<<value;
integer=val.str()+integer;
stack.pop();
value=stack.top();
}
if(map.count(atoi(integer.c_str()))==0){
error = unknown;
break;
}
else
truth = truth && toBool(map[atoi(integer.c_str())]);
}
else if(value==t||value==f){
truth=truth && toBool(map[value]);
stack.pop();
value=stack.top();
}
else{
error = malformed;
break;
}
lock=1;
}
//___________________________THE NEXT OPERATOR IS |_____________________________
else if(value==intOr&&(lock==0||lock==2)){
stack.pop();
value=stack.top();
ostringstream val;
integer="";
if(value>=0){
while(value>=0){
val.str("");
val<<value;
integer=val.str()+integer;
stack.pop();
value=stack.top();
}
if(map.count(atoi(integer.c_str()))==0){
error = unknown;
break;
}
else
truth = truth || toBool(map[atoi(integer.c_str() ) ] );
}
else if(value==t||value==f){
truth=truth||toBool(map[value]);
stack.pop();
value=stack.top();
}
else{
error = malformed;
break;
}
lock=2;
}
//____________________THE NEXT OPERATOR IS ~ OR MALFORMED______________________
else if(value==intNot){
truth = !truth;
stack.pop();
value=stack.top();
if(lock == 0 && value == open_parenthesis){
error = malformed;
break;
}
}
else {
error = malformed;
break;
}
}
//______________________IF NO ERROR YET BUT MISSING OPEN PARENTHESIS________________
if(error == noError && stack.top()!=open_parenthesis){
error = malformed;
break;
}
//Pop the opening parenthesis
stack.pop();
//The end result between the parenthesis
if(truth)
stack.push(t);
else
stack.push(f);
}//Special case of meeting a closed parenthesis
else
stack.push( input[i]-'0' );
}//Pushing one line to the stack
int top=stack.top();
//_____________PRINTING OUTPUT FOR PARENTHESIZED EXPRESSIONS WITH ERRORS_______________
if(error != noError){
printTruth(truth, t_String,f_String,error);
}
//__________PRINTING OUTPUT FOR PARENTHESIZED EXPRESSIONS OR T||F WITHOUT PARENTHESIS______
else if(top==f||top==t){
truth=toBool( map[top] ) ;
stack.pop();
while(!stack.empty()){
int value=stack.top();
if(value!=intNot){
error = malformed;
break;
}
else{
truth=!truth;
}
stack.pop();
}
printTruth(truth,t_String,f_String,error);
}
//________________PRINTING OUTPUT FOR INTEGERS WITHOUT PARENTHESIS________________________
else {
int value=stack.top();
ostringstream val;
string integer="";
if(value>=0){
while(value>=0){
val.str("");
val<<value;
integer=val.str()+integer;
stack.pop();
if(!stack.empty())
value=stack.top();
else
break;
}
if(map.count(atoi(integer.c_str()))==0){
error = unknown;
}
else
truth = toBool(map[atoi(integer.c_str())]);
}
if(!stack.empty()&&stack.top()==intNot){
while(!stack.empty()){
value=stack.top();
if(value!=intNot){
error = malformed;
break;
}
else{
truth=!truth;
}
stack.pop();
}
}
else if(!stack.empty()){
error = malformed;
}
printTruth(truth,t_String,f_String,error);
}
}
return 0;
}//Main
//______________________________HELPER FUNCTIONS__________________________________
void printTruth(bool truth, const string t, const string f, string error){
if(error != "ne"){
cout<<error<<endl;
}
else{
if(truth)
cout<<t<<endl;
else
cout<<f<<endl;
}
}
bool toBool(char character){
if(character=='T'){
return true;
}
else
return false;
}
//bool assembleInt(){
//} | true |
e7eec7b4ab4db7a970af3d27150f1b6aa920dffa | C++ | mju/acm | /107.cpp | UTF-8 | 647 | 3.28125 | 3 | [] | no_license | #include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <cmath>
int exponent(int &a,int &b)
{
int i,j;
for (i=1;i<=b;i++)
for (j=1;pow(i+1,j)<=a;j++)
if (pow(i+1,j)==a && pow(i,j)==b)
{
a=i+1,b=i;
return j;
}
}
void count(int &a,int &b)
{
int exp;
exp=exponent(a,b);
//cout<<a<<" "<<b<<endl;
int i,j;
int total=0;
int total1=0;
for (i=1,j=pow(a,exp);j>1;i*=b,j/=a)
total+=i,total1+=i*j;
total1+=i;
a=total;
b=total1;
}
main()
{
int a,b;
while (cin>>a>>b && a || b)
{
count(a,b);
cout<<a<<" "<<b<<endl;
}
return 0;
}
| true |
274d3429c7136fa62e937e52272d0b80d9055116 | C++ | mlaniewski/SPA | /src/PQL/Field.cpp | UTF-8 | 1,864 | 3.015625 | 3 | [] | no_license | #ifndef _STDLIB_H_
#include <stdlib.h>
#endif
#include <iostream>
#include <sstream>
#include "Field.h"
Field::Field() {
this->nazwaProcedury = false;
this->nazwaZmiennej = false;
this->wartosc = false;
this->statement = false;
}
Field::Field(string type, string value) {
this->type = type;
this->value = value;
this->nazwaProcedury = false;
this->nazwaZmiennej = false;
this->wartosc = false;
this->statement = false;
}
Field::Field(string type, string value, bool nazwaProcedury, bool varName, bool val,
bool stmt) {
this->type = type;
this->value = value;
this->nazwaProcedury = nazwaProcedury;
this->nazwaZmiennej = varName;
this->wartosc = val;
this->statement = stmt;
}
Field::~Field() {
// TODO Auto-generated destructor stub
}
bool Field::czyStatement() {
return statement;
}
void Field::setStatement(bool stmt) {
this->statement = stmt;
}
string& Field::getTyp() {
return type;
}
void Field::setTyp(string& type) {
this->type = type;
}
bool Field::getWartosc1() {
return wartosc;
}
void Field::setWartosc1(bool val) {
this->wartosc = val;
}
string& Field::getWartosc() {
return value;
}
int Field::stringNaInt() {
return std::stoi(value);
}
void Field::setWartosc(string& value) {
this->value = value;
}
bool Field::czyNazwaProcedury() {
return nazwaProcedury;
}
void Field::setNazwaProcedury(bool nazwaProcedury) {
this->nazwaProcedury = nazwaProcedury;
}
bool Field::czyNazwaZmiennej() {
return nazwaZmiennej;
}
void Field::setNazwaZmiennej(bool varName) {
this->nazwaZmiennej = varName;
}
string Field::printField()
{
stringstream fieldText;
fieldText << "Field: [" << this->type << " " << this->value << "] {nazwaProcedury: " << this->nazwaProcedury << ", varName: " << this->nazwaZmiennej << ", stmt#: " << this->statement << ", value: " << this->wartosc << "}" << endl;
return fieldText.str();
}
| true |
e48e29408c54da0c665d06469da5a699421180ef | C++ | AliTaheriNastooh/Time-Series-Motifs | /Phase 2/Project2/saxquantizer.hpp | UTF-8 | 7,785 | 2.71875 | 3 | [
"MIT"
] | permissive | /*
Copyright (c) 2014 Mohamed Elsabagh <melsabag@gmu.edu>
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#ifndef SAXQUANTIZER_HPP
#define SAXQUANTIZER_HPP
#include <deque>
#include <vector>
#include <cassert>
#include <boost/math/distributions/normal.hpp>
using std::deque;
using std::vector;
namespace SaxQuantizer {
/**
* Helper routine to generate the SAX codebook (list of cutpoints) of a given size
* @param <alphabet_size>: number of desired codewords
* @param <cutpoints> (out): resulting codebook
*/
inline void fill_cutpoints(size_t alphabet_size, vector<double> *cutpoints) {
assert(alphabet_size > 0);
static boost::math::normal dist(0.0, 1.0);
std::cout << "alphabet: " << alphabet_size << std::endl;
cutpoints->reserve(alphabet_size);
cutpoints->push_back(-DBL_MAX);
for (size_t i = 1; i < alphabet_size; ++i) {
double cdf = ((double) i) / alphabet_size;
cutpoints->push_back(quantile(dist, cdf));
}
}
/**
* Symbolic Aggregate Approximation with fractional sliding window, numerosity reduction, and scaling
*/
class Sax {
private:
size_t m_window_size;
size_t m_string_size;
size_t m_alphabet_size;
double m_baseline_mean;
double m_baseline_stdev;
vector<double> m_cutpoints;
bool m_trained;
/**
* SAX with fractional sliding window and automatic scaling.
* @param <it>: start iterator
* @param <end>: end iterator
* @param <syms> (out): quantized range
*/
template<class Iter>
void saxify(Iter it, const Iter end, vector<int> *syms) {
// perform PAA using a fractional sliding window
double paa[m_string_size];
double paa_window = ((double) m_window_size) / m_string_size;
double p = 0; // p for progress
double w = 1; // w for weight
size_t available = 0;
for (size_t i = 0; i < m_string_size && it != end; ++i, ++available) {
// normalize around baseline
double normalized = (*it - m_baseline_mean) / m_baseline_stdev;
paa[i] = 0;
double j = 0;
while (j < paa_window && it != end) {
paa[i] += w * normalized; // sum of (partial) elements inside the window
j += w;
p += w;
// window full
if (paa_window == p) {
if (fabs(w - 1.0) <= 0.01) { // if last element fully consumed,
++it; // then just move next.
} else { // o.w.,
w = 1.0 - w; // set remaining portion.
}
p = 0; // reset progress
// window not full, but next must be split
} else if (paa_window - p < 1.0) {
w = paa_window - p; // set needed portion
++it; // move to next
// window not full, next can be fully consumed
} else {
++it; // move to next
}
}
paa[i] /= j; // averaging
}
// map to symbols. 0-based.
for (size_t i = 0; i < available; ++i) {
int cnt = -1;
for (const auto & cp : m_cutpoints) {
if (paa[i] >= cp) ++cnt;
}
syms->push_back(cnt);
}
}
public:
/**
* Constructs a SAX quantizer of a given window size, string size and alphabet size.
* @param <window_size>: sliding window size
* @param <string_size>: output string size for each sliding window (can be greater than window_size)
* @param <alphabet_size>: number of codewords
*/
Sax(size_t window_size, size_t string_size, size_t alphabet_size)
: m_window_size(window_size), m_string_size(string_size), m_alphabet_size(alphabet_size),
m_baseline_mean(0), m_baseline_stdev(1), m_trained(false) {
assert(window_size > 0);
assert(string_size > 0);
assert(alphabet_size > 0);
fill_cutpoints(alphabet_size, &m_cutpoints);
}
virtual ~Sax() {
m_cutpoints.clear();
}
/**
* Trains the quantizer from a given sample. This sets the baseline mean and stdevs, which are used in
* normalizing the input.
*
* @param <samples>: list of training values
*/
template<typename Container>
void train(const Container & samples) {
double mean = 0;
double stdev = DBL_MIN;
assert(!samples.empty());
if (samples.size() < 2) {
mean = samples[0];
stdev = DBL_MIN;
} else {
size_t n = 0;
double M2 = 0;
for (const auto & val : samples) {
++n;
double delta = val - mean;
mean += delta / n;
M2 += delta * (val - mean);
}
stdev = sqrt(M2 / (n-1));
}
if (stdev == 0) stdev = DBL_MIN;
m_baseline_mean = mean;
m_baseline_stdev = stdev;
m_trained = true;
}
/**
* Quantizes the given input sequence into a discrete alphabet using SAX.
* Calling this method will also train the quantizer using the input sequence, if
* not already trained.
*
* @param <seq>: the input sequence to be quantized
* @param <qseq> (out): quantized output sequence
* @param reduce (default true): if true, applies run-length numerosity reduction
*
* Returns the number of consumed symbols from the input sequence.
*/
template<typename Container>
size_t quantize(const Container & seq, vector<int> *qseq, bool reduce=true) {
if (!m_trained) train(seq);
vector<int> buf1, buf2;
auto *syms_buf = &buf1;
auto *old_syms_buf = &buf2;
size_t consumed = 0;
for (consumed = 0; consumed < seq.size(); ++consumed) {
if (reduce) { // run-length numerosity reduction
syms_buf->clear();
saxify(seq.begin() +consumed, seq.end(), syms_buf);
// skip window if same as previous
if (*syms_buf != *old_syms_buf) {
qseq->insert(qseq->end(), syms_buf->begin(), syms_buf->end());
std::swap(syms_buf, old_syms_buf);
}
} else { // no reduction
saxify(seq.begin() +consumed, seq.end(), qseq);
}
// ignore excess elements, if sequence size isn't a multiple of window size
//if (seq.size() - consumed <= m_window_size) break;
}
return consumed;
}
/**
* Returns the order of the quantizer (here, the window size)
*/
inline size_t order() const {
return m_window_size;
}
/**
* Returns the compression ratio of the quantizer (input size / output size)
*/
inline double ratio() const {
return ((double) m_window_size) / m_string_size;
}
};
}
#endif
| true |
497efc8d084106ab93daf081da85f8e41556f51e | C++ | svetthesaiyan/uni-projects-1st-year-2nd-trimester | /2021.02.26 Exercise 7/exercise_7.cpp | UTF-8 | 1,054 | 3.25 | 3 | [] | no_license | /* Да се напише програма, в която са дефинирани низове със стойности ТМ и Телематика.
* Във вторият низ да се копира стойността на първия низ като се използва вградената функция за копиране.
* Да се отпечатат стойностите на низовете преди и след копирането.
*/
#include <iostream>
#include <cstring>
using namespace std;
int find(char seq[][15], int count, char* pattern)
{
int i;
for(i=0; i<count; i++)
if(!strcmp(pattern, seq[i]))
return 1;
return 0;
}
int main()
{
char string1[]="TM";
char string2[]="Телематика";
cout<<"Преди копирането: "<<endl;
cout<<"Низ 1: "<<string1<<endl;
cout<<"Низ 2: "<<string2<<endl;
strcpy(string2, string1);
cout<<"След копирането: "<<endl;
cout<<"Низ 1: "<<string1<<endl;
cout<<"Низ 2: "<<string2<<endl;
system("pause");
return 0;
}
| true |
b8799204b2c11eddd874089a5095c82c08210c92 | C++ | aman-aman/Algorithms | /count-divisior.cpp | UTF-8 | 556 | 3.640625 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
/*
aman kumar jha
This algorithm count the number of divisors of a number in O(sqrt(n)) time.
*/
int countdivisor(int n)
{
int c=0;
for (int i=1; i<=sqrt(n); i++)
{
if (n%i==0)
{
if (n/i == i)
c++;
else
c=c+2;
}
}
return c;
}
int main()
{
int n;
printf("Enter the Number: ");
scanf("%d",&n);
printf("Number of divisor of %d is: %d\n",n,countdivisor(n));
return 0;
}
| true |
4e9fd37ea4c769332a8d97a5c39e88fd1e6c96dc | C++ | delecui/oneAPI-samples | /DirectProgramming/DPC++/ProjectTemplates/Hello_World_GPU/src/main.cpp | WINDOWS-1252 | 864 | 2.578125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | //==============================================================
// Copyright 2020, Intel Corporation. All rights reserved.
//
// SPDX-License-Identifier: MIT
// =============================================================
#include <iostream>
#include <CL/sycl.hpp>
using namespace cl::sycl;
int main() {
// GPU Device selector
gpu_selector device_selector;
// Buffer creation
constexpr int num = 16;
auto R = range<1>{ num };
buffer<int> A{ R };
// Kernel
class ExampleKernel;
queue q{ device_selector };
q.submit([&](handler& h) {
auto out = A.get_access<access::mode::write>(h);
h.parallel_for<ExampleKernel>(R, [=](id<1> idx) { out[idx] = idx[0]; });
});
// Consume result
auto result = A.get_access<access::mode::read>();
for (int i = 0; i < num; ++i)
std::cout << result[i] << "\n";
return 0;
} | true |
3ca4210df71b3dd57d63a8701078f1d3aace7585 | C++ | cajet/Leetcode | /my-leetcode-master/96.cpp | UTF-8 | 321 | 2.734375 | 3 | [] | no_license | class Solution {
public:
int numTrees(int n) {
int* G = new int[n+1];
fill(G, G+n+1, 0);
G[0]=G[1]=1;
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= i; j++) {
G[i] += G[j-1]*G[i-j];
}
}
int ans = G[n];
delete[] G;
return ans;
}
};
| true |
106625f13c4ec7bc9dff72d9e85e9f79aaf8f97d | C++ | limziwen/Pokemon | /Player.h | UTF-8 | 530 | 2.796875 | 3 | [] | no_license | #pragma once
#ifndef Player_H
#define Player_H
#include "Pokemon.h"
#include "string"
using namespace std;
class Player
{
private:
Pokemon PokemonArray[6];
//need pointer to hold location of next free space
string name;
int ptr; //Holds positon of next empty space
public:
Player(); //set ptr to 0
~Player();
void AddPokemon(Pokemon, Moves[99]);
void SetName(string);
string GetName();
/*void DisplayPokemonMoves(int);*/
int ReturnPointer();
Pokemon SendPokemon(int);
};
#endif
| true |
2a349cf03debb13171ab559ad8e008d66512a90a | C++ | DoviWidawsky/dovi_proj | /Utils.cpp | UTF-8 | 1,152 | 3.125 | 3 | [] | no_license | //
// Created by ori on 1/12/19.
//
#include "Utils.h"
string Utils::coordinatesToString(vector<string> crdnts) {
string c1, c2 = crdnts[0];
string path;
for (int i = 1; i < crdnts.size(); ++i) {
c1=c2;
c2=crdnts[i];
if(this->getRowCoordintae(c1)-1==this->getRowCoordintae(c2)){
path+="Down,";
}
if(this->getRowCoordintae(c1)==this->getRowCoordintae(c2)-1){
path+="Up,";
}
if(this->getColCoordintae(c1)-1==this->getColCoordintae(c2)){
path+="Right,";
}
if(this->getColCoordintae(c1)==this->getColCoordintae(c2)-1){
path+="Left,";
}
}
path.erase(path.size()-1);
return path;
}
int Utils::getRowCoordintae(string crdnt) {
int i=0;
int row=0;
while (crdnt[i]!=','){
row*=10;
row+=(crdnt[i]-'0');
++i;
}
return row;
}
int Utils::getColCoordintae(string crdnt) {
int i=0;
int col=0;
while (crdnt[i]!=','){
++i;
}
++i;
while (i<crdnt.size()){
col*=10;
col+=(crdnt[i]-'0');
++i;
}
return col;
}
| true |
78656c3662cff58b8bed1cc89d32f0548347747c | C++ | dfavato/bh_dynamics | /LineSensor.h | UTF-8 | 772 | 3 | 3 | [] | no_license | #ifndef LineSensor_h
#define LineSensor_h
#include "GenericSensor.h"
class LineSensor : public GenericSensor {
int state; // estado do sensor, sobre ou fora da linha
int line_threshold; // limiar para decidir que o sensor está sobre a linha
int offline_threshold; // limiar para decidir que o sensor está fora da linha
int persistent_address_line;
int persistent_address_offline;
void store_values();
void load_values();
public:
LineSensor(int pin); // construtor
const static int ON_LINE = 0;
const static int OFF_LINE = 1;
int status(); // retorna o status atual, sobre ou fora da linha
void calibrate(int line, int offline); // calibragem, os argumentos devem ser os valores médios de leitura na linha e fora dela
};
#endif
| true |
c09bf0498a1c658f9c9a97548cef421c44655696 | C++ | ak566g/Data-Structures-and-Algorithms | /Recursion/14_StairCase.cpp | UTF-8 | 508 | 3.578125 | 4 | [] | no_license | // A child is running up a staircase with N steps, and can hop either 1 step, 2 steps or 3 steps at a time.
// Implement a method to count how many possible ways the child can run up to the stairs.
// You need to return number of possible ways W.
#include<bits/stdc++.h>
using namespace std;
int stairCase(int n)
{
if(n<0)
return 0;
if(n==0){
return 1;
}
return stairCase(n-1)+stairCase(n-2)+stairCase(n-3);
}
int main()
{
int n;
cin>>n;
cout<<stairCase(n);
} | true |
47273b66b9c8701f8f3ae12e9188ef8b03bd8fd9 | C++ | vayct/exercises | /C/problems/11799.cpp | UTF-8 | 310 | 2.65625 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int TC;
int z =1;
cin >> TC;
while(TC--)
{
int n;
int highest = 0;
int curr;
cin >> n;
while(n--){
cin >> curr;
highest = max(curr, highest);
}
printf("Case %d: %d\n", z++, highest);
}
}
| true |
cb6ff7ac36d36122db6743f7398217001c7aa2f3 | C++ | naveenls/Competitive-Coding | /C++/test453.cpp | UTF-8 | 2,701 | 2.59375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
const int maxN=2*1e5+10;
long long val[3*maxN+1];
long long val1[3*maxN+1];
void Update(long long new_val,int pos,int ind,int start,int end,int f)
{
if(pos<start || pos>end)
return;
if(start==end)
{
if(f==0)
{
val[ind]=max(val[ind],new_val);
}
else
{
val1[ind]=max(val1[ind],new_val);
}
}
else
{
int mid=(start+end)>>1;
Update(new_val,pos,2*ind+1,start,mid,f);
Update(new_val,pos,2*ind+2,mid+1,end,f);
if(f==0)
{
val[ind]=max(val[2*ind+1] , val[2*ind+2]);
}
else
{
val1[ind]=max(val1[2*ind+1],val1[2*ind+2]);
}
}
}
long long get_sum(int ind,int start,int end,int l,int r,int f)
{
if(start>r || end<l)
return -1e18;
if(start>=l && end<=r)
{
if(f==0)
{
return val[ind];
}
else
{
return val1[ind];
}
}
else
{
int mid=(start+end)>>1;
long long v1=get_sum(2*ind+1,start,mid,l,r,f);
long long v2=get_sum(2*ind+2,mid+1,end,l,r,f);
return max(v1, v2);
}
}
void set_min()
{
for(int i=0;i<=3*maxN;i++)
{
val[i]=val1[i]=-1e18;
}
}
int main()
{
int n,m;
cin>>n>>m;
int c;
cin>>c;
long long x[c],y[c];
set<long long> s;
vector<pair<long long,pair<int,int> > > v;
for(int i=0;i<c;i++)
{
cin>>x[i]>>y[i];
s.insert(y[i]);
v.push_back({x[i],{2,i}});
}
int h;
cin>>h;
long long x1[h],y1[h];
for(int i=0;i<h;i++)
{
cin>>x1[i]>>y1[i];
s.insert(y1[i]);
v.push_back({x1[i],{1,i}});
}
sort(v.begin(),v.end());
map<long long,int> mp;
int cnt=0;
for(auto ele:s)
{
mp[ele]=cnt;
cnt++;
}
set_min();
long long ma_val[h]={0};
for(int i=0;i<v.size();i++)
{
int type=v[i].second.first;
int ind=v[i].second.second;
if(type==1)
{
long long a1=get_sum(0,0,cnt,0,mp[y1[ind]],1);
long long a2=get_sum(0,0,cnt,mp[y1[ind]],cnt,0);
long long ma=max(x1[ind]+y1[ind]+a1,x1[ind]-y1[ind] + a2);
ma_val[ind]=max(ma_val[ind],ma);
}
else
{
Update(-x[ind]+y[ind],mp[y[ind]],0,0,cnt,0);
Update(-x[ind]-y[ind],mp[y[ind]],0,0,cnt,1);
}
}
set_min();
for(int i=v.size()-1;i>=0;i--)
{
int type=v[i].second.first;
int ind=v[i].second.second;
if(type==1)
{
long long a1=get_sum(0,0,cnt,0,mp[y1[ind]],1);
long long a2=get_sum(0,0,cnt,mp[y1[ind]],cnt,0);
long long ma=max(-x1[ind]+y1[ind]+a1,-x1[ind]-y1[ind] + a2);
ma_val[ind]=max(ma_val[ind],ma);
}
else
{
Update(x[ind]+y[ind],mp[y[ind]],0,0,cnt,0);
Update(x[ind]-y[ind],mp[y[ind]],0,0,cnt,1);
}
}
long long mi=1e18;
int ind;
for(int i=0;i<h;i++)
{
if(mi>ma_val[i])
{
mi=ma_val[i];
ind=i;
}
}
cout<<mi<<endl;
cout<<ind+1<<endl;
return 0;
}
| true |
3b82e621947ba76c4671e7d9a7e6d8301e14db09 | C++ | solnor/Prosjekt-MAS-234 | /Del1/PWMdioder/PWMdioder/main.cpp | WINDOWS-1252 | 1,158 | 2.640625 | 3 | [] | no_license | /*
* PWMdioder.cpp
*
* Created: 19/11/2020 12:10:03
* Author : mathi
*/
#include <avr/io.h>
#define F_CPU 1000000UL //Definerer mikrokontrollerfrekvens,
//viktig for at delayfunksjonen skal fungere riktig
#include <util/delay.h> //Inkluderer delay
int main(void)
{
/*
Setter data direction for PB1 og PB2 til ut/HIGH
COM1(A/B)1 setter pins PB1 og PB2 til 0 ved compare match av OCR1(A/B)
WGM13-10 setter hvilken modus timeren er i, i denne
modusen er timeren satt til 10bit-fastPWM med TOP p 1023
CS10 setter prescaleren N til 1,
som gir den raskest mulige frekvensen i denne modusen.
*/
DDRB |= 1 << PB1 | 1 << PB2;
TCCR1A |= 1 << COM1A1 | 1 << COM1B1 | 1 << WGM11 | 1 << WGM10;
TCCR1B |= 1 << WGM12 | 1 << CS10;
OCR1A = 0;
OCR1B = 1023; //Starter OCR1A i 0 og OCR1B i 1023
/*I while-loopen er det to for-looper som bytter p
inkrementere/dekrementere OCR1(A/B), diodene
pulserer da 180 grader ute av fase
*/
while (1)
{
for(int i = 0; i < 511; i++){
OCR1A+=2;
OCR1B-=2;
_delay_ms(1);
}
for(int i = 0; i < 511; i++){
OCR1A-=2;
OCR1B+=2;
_delay_ms(1);
}
}
}
| true |
2cd3d600d5064cc3c5bc65540cadfd3e84daf17b | C++ | abhishekmishra11/Interest-Calculator | /IT210_Interest-Calculator.cpp | UTF-8 | 6,830 | 3.625 | 4 | [] | no_license | //IT210 BUSINESS APPLICATIONS WITH C++
//PROGRAMMER:ADRIAN ALEY
//DATE:APRIL 11, 2014
//PROGRAM ASSIGNMENT 4
//Preprocessor directives
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void headerfn();
void namefn(string &first, string &last);
int cardfn(int card);
void checkfn(int card);
void accountfn(float &netBalance, float &payment, int &d1, int &d2);
void adbfn(float &averageDailyBalance, float &payment, float &netBalance, int &d1, int &d2);
float APRfn(float &APR, float &averageDailyBalance);
void intfn(float &APR, float &averageDailyBalance, float &interest);
void outputfn(float &netBalance, float &payment, float &interest, float &APR, float &averageDailyBalance, int &d1, int &d2, string &first, string &last, int &card);
//function definitions
int main(){
headerfn();
//declarations
float netBalance, payment, interest, APR, averageDailyBalance;
int d1, d2, card;
string first, last;
cout<<"This program calculates the interest on one or more customer's"<<endl;
cout<<"unpaid credit card balances using the average daily balance"<<endl<<endl;
cout<<left<<fixed<<setprecision(0)<<left<<fixed;
namefn(first, last);
cardfn(card);
checkfn(card);
accountfn(netBalance, payment, d1, d2);
outputfn(netBalance, payment, interest, APR, averageDailyBalance, d1, d2, first, last, card);
int exit=0;
cout<<"Please enter 0 to exit or 1 for another customer: ";
cin>>exit;
cout<<endl;
while(exit!=0){//begin infinite while
headerfn();
cout<<"This program calculates the interest on one or more customer's"<<endl;
cout<<"unpaid credit card balances using the average daily balance"<<endl<<endl;
cout<<left<<fixed<<setprecision(0)<<left<<fixed;
namefn(first, last);
cardfn(card);
checkfn(card);
accountfn(netBalance, payment, d1, d2);
outputfn(netBalance, payment, interest, APR, averageDailyBalance, d1, d2, first, last, card);
cout<<"Please enter 0 to exit or 1 for another customer: ";
cin>>exit;
cout<<endl;
}
return 0;
}//end of main
void headerfn(){
cout<<"=******************************************="<<endl;
cout<<"* IT210 Business Applications with C++ *"<<endl;
cout<<"* Programmer: Adrian Aley *"<<endl;
cout<<"* Date: April 11, 2014 *"<<endl;
cout<<"* Interest Calculator *"<<endl;
cout<<"=******************************************="<<endl;
cout<<endl;
}//end headerfn
void namefn(string &first, string &last){
cout<<"Please enter first and last name on credit card: ";
cin>>first>>last;
cout<<endl;
cout<<"You entered "<<first<<" "<<last<<endl<<endl;
}//end namefn
int cardfn(int card){
cout<<"Please enter credit card number: ";
cin>>card;
cout<<endl;
cout<<"You entered "<<card<<endl<<endl;
}
void checkfn(int card){
int correct=0;
cout<<"If this is correct, press 0 or 1 to try again: ";
cin>>correct;
cout<<endl;
while(correct!=0){//start of while
cout<<"Please enter credit card number: ";
cin>>card;
cout<<endl;
cout<<"You entered "<<card<<endl<<endl;
cout<<"If this is correct, press 0 or 1 to try again: ";
cin>>correct;
cout<<endl;
}//end of infinite while and checkfn
}
void accountfn(float &netBalance, float &payment, int &d1, int &d2){
cout<<"Please enter the balance shown in the credit card bill: ";
cin>>netBalance;
cout<<endl;
cout<<"You entered $"<<netBalance<<endl<<endl;
cout<<"Please enter payment amount: ";
cin>>payment;
cout<<endl;
cout<<"You entered $"<<payment<<endl<<endl;
cout<<"Please enter number of days in billing cycle: ";
cin>>d1;
cout<<endl;
cout<<"You entered "<<d1<<endl<<endl;
cout<<"Please enter number of days payment is made before billing cycle: ";
cin>>d2;
cout<<endl;
cout<<"You entered "<<d2<<endl<<endl;
}
void adbfn(float &averageDailyBalance, float &payment, float &netBalance, int &d1, int &d2){
averageDailyBalance=(netBalance*d1-payment*d2)/d1;
}
float APRfn(float &APR, float &averageDailyBalance){
if(averageDailyBalance<100){//begin if esle statement
APR=5;
}
else if(100<averageDailyBalance<1000){
APR=10;
}
else{
APR=15;
}//end if else statement
}
void intfn(float &APR, float &averageDailyBalance, float &interest){
interest=averageDailyBalance*APR/(100*12);
}
void outputfn(float &netBalance, float &payment, float &interest, float &APR, float &averageDailyBalance, int &d1, int &d2, string &first, string &last, int &card){
cout<<setw(50)<<setfill('*')<<"*"<<endl;
cout<<"12345678901234567890123456789012345678901234567890"<<endl;
cout<<setw(50)<<setfill('*')<<"*"<<endl<<endl;
cout<<left<<setw(15)<<setfill(' ')<<first;
cout<<left<<setw(15)<<setfill(' ')<<last;
cout<<left<<setw(15)<<setfill(' ')<<card<<endl;
cout<<setw(50)<<setfill('-')<<"-"<<endl;
cout<<left<<setw(15)<<setfill(' ')<<"FIRST NAME";
cout<<left<<setw(15)<<setfill(' ')<<"LAST NAME";
cout<<left<<setw(15)<<setfill(' ')<<"CARD NUMBER"<<endl;
cout<<setw(50)<<setfill('=')<<"="<<endl<<endl;
cout<<left<<setw(40)<<setfill('.')<<"Credit Card Balance"
<<right<<setw(10)<<setfill(' ')<<setprecision(2)<<netBalance<<endl<<endl;
adbfn(averageDailyBalance, payment, netBalance, d1, d2);
APRfn(APR, averageDailyBalance);
intfn(APR, averageDailyBalance, interest);
cout<<left<<setw(40)<<setfill('.')<<"Annual Interest Rate"
<<right<<setw(10)<<setfill(' ')<<setprecision(2)<<APR<<endl<<endl;
cout<<left<<setw(40)<<setfill('.')<<"Payment Made"
<<right<<setw(10)<<setfill(' ')<<setprecision(2)<<payment<<endl<<endl;
cout<<left<<setw(40)<<setfill('.')<<"Number of Days in Billing Cycle"
<<right<<setw(10)<<setfill(' ')<<setprecision(2)<<d1<<endl<<endl;
cout<<left<<setw(40)<<setfill('.')<<"Number of Days Before Billing Cycle"
<<right<<setw(10)<<setfill(' ')<<setprecision(2)<<d2<<endl<<endl;
cout<<left<<setw(40)<<setfill('.')<<"Average Daily Balance"
<<right<<setw(10)<<setfill(' ')<<setprecision(2)<<averageDailyBalance<<endl<<endl;
cout<<left<<setw(40)<<setfill('.')<<"Interest on Unpaid Balance"
<<right<<setw(10)<<setfill(' ')<<fixed<<setprecision(2)<<interest<<endl<<endl;
cout<<setw(50)<<setfill('*')<<"*"<<endl<<endl;
}
| true |
7270c23142c30ac003e4469d8243215d08f6d3f2 | C++ | likeweilikewei/Algorithm-Data-Structure-Implement | /链表/带头结点反转单链表/construct.cpp | GB18030 | 549 | 3.34375 | 3 | [] | no_license | #include"head_link.h"
NODE construct()
{
NODE head = new Node;
//αʹ
NODE current = head;
if (NULL == head)
{
cout << "new Node failed." << endl;
exit(-1);
}
current->next = NULL;
//
cout << "please input list value.q to quit." << endl;
int value;
while (cin >> value)
{
NODE tmp_node = new Node;
if (NULL == tmp_node)
{
cout << "new Node failed." << endl;
exit(-1);
}
tmp_node->next = NULL;
tmp_node->value = value;
current->next = tmp_node;
current = tmp_node;
}
return head;
}
| true |
d0c898d149f2d23c14ac75d80ffa4bdf8572a8e5 | C++ | TolimanStaR/tp-lab-6 | /include/Engineer.h | UTF-8 | 1,238 | 2.71875 | 3 | [] | no_license | // copyright 2021 Toliman
#ifndef INCLUDE_ENGINEER_H_
#define INCLUDE_ENGINEER_H_
#include <string>
#include "Interfaces.h"
#include "Personal.h"
class Engineer : public Project,
public Projectbudget,
public Personal {
public:
int calcBudgetPart(float projectPart, int budget);
explicit Engineer(std::string name1,
int worktime1, Project *project1,
int position1,
int salary1);
virtual void calc(int hours);
};
class Programmer : public Engineer {
public:
explicit Programmer(std::string name1,
int worktime1,
Project *project1,
int position1,
int salary1);
virtual int calcProAdditions(int relativePart);
virtual void printInfo();
virtual void calc(int hours);
virtual void calcBonus(int times);
virtual int getPayment();
};
class Tester : public Engineer {
public:
explicit Tester(std::string name1,
int worktime1,
Project *project1,
int position1,
int salary1);
virtual int calcProAdditions(int relativePart);
virtual void printInfo();
virtual void calc(int hours);
virtual void calcBonus(int times);
};
#endif // INCLUDE_ENGINEER_H_
| true |
1d94fc14dd778d35debb96b48fa5611ce9883210 | C++ | sonaspy/LeetCode | /c/normal_hard/lettercombines.cpp | UTF-8 | 987 | 2.75 | 3 | [] | no_license | // author -sonaspy@outlook.com
// coding - utf_8
#include <bits/stdc++.h>
#define test() freopen("in", "r", stdin)
using namespace std;
class Solution
{
public:
vector<string> letterCombinations(string digits)
{
vector<string> res;
if (digits.empty()) return res;
string s;
dfs(res, s, digits, 0);
return res;
}
void dfs(vector<string> &res, string &str, string &digits, int k)
{
if (str.size() == digits.size())
{
res.push_back(str);
return;
}
string tmp = mp[digits[k]];
for (char w : tmp)
{
str.push_back(w);
dfs(res, str, digits, k + 1);
str.pop_back();
}
return;
}
unordered_map<char, string> mp{{'2', "abc"}, {'3', "def"}, {'4', "ghi"}, {'5', "jkl"}, {'6', "mno"}, {'7', "pqrs"}, {'8', "tuv"}, {'9', "wxyz"}};
};
int main(int argc, char const *argv[])
{
/* code */
//test();
return 0;
} | true |
7c9b8f02354388aa53d57d5cfb990e0195ecd291 | C++ | NyamLand/HuntingBrave | /HuntingBrave_client/source/Player.cpp | SHIFT_JIS | 6,278 | 2.515625 | 3 | [] | no_license |
#include <vector>
#include <fstream>
#include "iextreme.h"
#include "GlobalFunction.h"
#include "Player.h"
#include "CSVReader.h"
#include "BaseEquipment.h"
//***************************************************************
//
// PlayerNX
//
//***************************************************************
//------------------------------------------------------------------------------------
// O[o
//------------------------------------------------------------------------------------
// f
#define Y2009_SCALE 0.02f
// Xs[h
#define ANGLE_ADJUST_MOVE_SPEED 0.3f
#define ANGLE_ADJUST_MAGIC_SPEED 0.05f
#define MOVE_SPEED 0.5f
// ͏
#define MIN_INPUT_STICK 0.3f
//------------------------------------------------------------------------------------
// E
//------------------------------------------------------------------------------------
// RXgN^
Player::Player(void) : texture(nullptr)
{
}
// fXgN^
Player::~Player( void )
{
SafeDelete( texture );
}
//
bool Player::Initialize( void )
{
// ǂݍ
Load( "DATA/CHR/Y2009/Y2009.IEM" );
SetPos( Vector3( 0.0f, 0.0f, 0.0f ) );
SetAngle( 0.0f );
SetScale( Y2009_SCALE );
SetMotion( 1 ); // l
speed = MOVE_SPEED;
SetMode(MODE::MOVE);
// eNX`eXg
obj->SetTexture( 0, "DATA/CHR/Y2009/testTexture.png" );
// |C^
ModeFunction[MODE::MOVE] = &Player::MoveMode;
ModeFunction[MODE::SWOADATTACK] = &Player::ModeSwordAttack;
ModeFunction[MODE::MAGICATTACK] = &Player::ModeMagicAttack;
ModeFunction[MODE::AVOID] = &Player::ModeAvoid;
// XV
UpdateInfo();
//-----------------------------
//std::fstream r("DATA\\test.csv", std::ios::in);
//CSVReader csv(r);
//vector<string> tokens;
//while (!csv.Read(tokens))
//{
// for (unsigned int i = 0; i<tokens.size(); i++)
// {
// if (tokens[0] == "HP")
// {
// hp = std::atoi(tokens[1].c_str());
// }
// }
//}
//csv.Close();
//return 0;
//---------------------------------
if ( obj == nullptr ) return false;
return true;
}
//
//------------------------------------------------------------------------------------
// XVE`
//------------------------------------------------------------------------------------
// XV
void Player::Update( void )
{
// e[hɉ
( this->*ModeFunction[mode] )();
// XV
BaseChara::Update();
}
void Player::Render( iexShader* shader, LPSTR technique )
{
BaseChara::Render();
}
//------------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------------
// ړ[h
void Player::MoveMode( void )
{
// XeBbNɂړ
Move();
if ( KEY_Get( KEY_A ) == 3 ) SetMode( MODE::SWOADATTACK ); //
if ( KEY_Get( KEY_B ) == 3 ) SetMode( MODE::MAGICATTACK );
if ( KEY_Get( KEY_C ) == 3 ) SetMode( MODE::AVOID );
}
void Player::ModeSwordAttack( void )
{
bool param = SwordAttack();
if(param)SetMode(MODE::MOVE);
}
void Player::ModeMagicAttack( void )
{
bool param = MagicAttack();
if(param)SetMode(MODE::MOVE);
}
void Player::ModeAvoid(void)
{
bool param = Avoid();
if(param)SetMode(MODE::MOVE);
}
//------------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------------
// ړ
bool Player::Move( void )
{
// XeBbN̓̓`FbN
float axisX = ( float )input[0]->Get( KEY_AXISX );
float axisY = -( float )input[0]->Get( KEY_AXISY );
float length = sqrtf( axisX * axisX + axisY * axisY ) * 0.001f;
// ͂Έړ
if ( length >= MIN_INPUT_STICK )
{
// [Vݒ
SetMotion( MOTION::MOVE ); // 胂[V
//
AngleAdjust(
Vector3( axisX, 0.0f, axisY ),
ANGLE_ADJUST_MOVE_SPEED );
// ړ
SetMove( Vector3( sinf( angle ), 0.0f, cosf( angle ) ) * speed );
}
else
{
// [Vݒ
SetMotion( MOTION::WAIT ); // ҋ@[V
}
return false;
}
//U
bool Player::SwordAttack(void)
{
SetMotion( MOTION::ATTACK ); //
if (!initflag) initflag = true;
//
if (obj->GetFrame() == 413)
{
initflag = false;
return true; //U삪I
}
return false;
}
//@U
bool Player::MagicAttack(void)
{
SetMotion(MOTION::ATTACK2); //
if (!initflag)
{
initflag = true;
timer = 0;
move = Vector3(0, 0, 0);
}
// XeBbN̓̓`FbN
float axisX = (float)input[0]->Get(KEY_AXISX);
float axisY = -(float)input[0]->Get(KEY_AXISY);
float length = sqrtf(axisX * axisX + axisY * axisY) * 0.001f;
switch (step)
{
case 0:
// ͂
if (length >= MIN_INPUT_STICK)
{
//
AngleAdjust(
Vector3(axisX, 0.0f, axisY),
ANGLE_ADJUST_MAGIC_SPEED);
//if (axisX > 0) angle += 0.1f;
//else angle -= 0.1f;
}
if (KEY_Get(KEY_B) == 2) step++;
break;
case 1:
timer++; //d
SetMotion(MOTION::RIGOR);
if (timer > 100)
{
initflag = false;
return true;
}
}
return false;
}
//
bool Player::Avoid(void)
{
Vector3 front = GetFront();
SetMotion(MOTION::AVOID);
if (!initflag)
{
initflag = true;
timer = 0;
move.x += front.x * 1.1f;
move.z += front.z * 1.1f;
}
timer++;
if (timer > 30)
{
initflag = false;
return true;
}
return false;
}
//------------------------------------------------------------------------------------
// ݒ
//------------------------------------------------------------------------------------
void Player::SetMode(int mode)
{
if (this->mode != mode)
{
step = 0;
this->mode = mode;
}
}
//------------------------------------------------------------------------------------
// 擾
//------------------------------------------------------------------------------------
| true |
1048cba89a5bcb142620875f9db107422a45f5ae | C++ | ChosenxOne/CHOSEN | /test2/test2.cpp | GB18030 | 1,114 | 3.171875 | 3 | [] | no_license | /*ջֲʱ
ɼԣ˽Աӹ
*/
#include<stdio.h>
#include<math.h>
/*int g_max = 10;
int fun(int x, int y)
{
int a = x + y;
int b = x - y+g_max;
a= g_min;//ִ£
return a + b;
}
int g_min = 0;//
int main()
{
int a = 10, b = 20;
fun(a, b);
int c = g_max + g_min;
return 0;
}*/
//鶨
/*int main()
{
int i = 10;
int ar[10] = { 10,20,30,45,50,60,70,80,90,100 };
for (int i = 0; i < 10; ++i)
{
printf("%d", ar[i]);
}
printf("\n");
return 0;
}*/
/*
int main()
{
int a = 3, b = 4,c = 5;
a *= b + c;
printf("%d", a);
return 0;
}
*/
//Ŀ
/*
int MaxInt(int a, int b)
{
if (a > b)
{
return a;
}
else
{
return b;
}
}
{
return a > b ? a : b;
}
int main()
{
int a = 0, b = 0;
int max = 0;
scanf_s("%d,%d", &a, &b) ;
max = MaxInt(a, b);
printf("%d\n", max);
return 0;
}
*/
int main()
{
int n = 26;
for (int i = 0; i < n; ++i)
{
int k = i;
for (int j = 0; j < n; ++j)
{
printf("%c", k + 'A');
k = (k + 1) % n;
}
printf("\n");
}
return 0;
} | true |
f56da81588562a9cc0b87488360c71abcefc2d7d | C++ | tatsuya4649/muldia | /muldia/include/name.h | UTF-8 | 385 | 2.796875 | 3 | [] | no_license | // <name.h> header is a header that defines the name of the namespace and
// allows you to use the abbreviated name.
//
#ifndef NAME_H
#define NAME_H
#include <string>
// the abbreviations below allo refer to the same namespace
#define MULDIA muldia
#define MD muldia
#define _md muldia
namespace _md{
extern std::string namespace_; // "muldia"
} // namespace _md
#endif // NAME_H
| true |
a40d4c7be6360226ba265783954f3032c5abd3bb | C++ | dianartanto/PLCArduinoku | /examples/A. Modul IO Aktif High/02. IO Analog/O1_IO_Analog/O1_IO_Analog.ino | UTF-8 | 1,127 | 2.546875 | 3 | [] | no_license | /*
1.Rangkaian:
Modul Input Output Aktif High.
Kaki Input Analog : A4, A5 (kaki A4 dan A5 Arduino)
Kaki Output Analog : Y6, Y9 (kaki PWM: D6 dan D9 Arduino)
Alat Input Analog : Potensio 2x
Alat Output Analog : LED 2x
2.Program:
A4
1 ||--------------------{READ ADC}----||
|| {DIV Y6 :=} ||
2 ||----------{ A4 / 4 }-----------||
|| Y6 ||
3 ||------------------{PWM 1.00 kHz}--||
|| A5 ||
4 ||--------------------{READ ADC}----||
|| {DIV Y9 :=} ||
5 ||----------{ A5 / 4 }-----------||
|| Y9 ||
6 ||------------------{PWM 1.00 kHz}--||
Ketika potensio di kaki A4 diputar knobnya,
maka LED di kaki D6 akan berubah intensitas cahayanya
Begitu pula ketika potensio di kaki A5 diputar knobnya,
maka LED di kaki D9 akan berubah intensitas cahayanya
*/
#include<PLCArduinoku.h>
void setup() {
setupku();
outLow();
}
void loop() {
inAnalog(A4);
outPWM(Y6);
inAnalog(A5);
outPWM(Y9);
}
| true |
4f0b2eb348c093ed0e97637f4ca68956b0fd531f | C++ | OctupusTea/Online-Judge | /Zero Judge/b553.cpp | UTF-8 | 276 | 2.625 | 3 | [] | no_license | #include <stdio.h>
int main( void)
{
int n = 0, counter = 0;
while( ~scanf( "%d", &n) )
{
counter = 0;
while( n != 1)
{
if( n % 2 == 1)
{
n *= 3;
n++;
}
else
{
n /= 2;
}
counter++;
}
printf( "%d\n", counter);
}
return 0;
}
| true |
0d19fbd4aa9f20b4c6ec353b9a7238a458c3b19a | C++ | revsic/HYU-ITE1015 | /hw8-1/rectangle_main.cc | UTF-8 | 605 | 3.265625 | 3 | [
"MIT"
] | permissive | #include "rectangle.h"
#include <iostream>
int main() {
while (true) {
std::string given;
std::cin >> given;
Rectangle* rect = nullptr;
if (given == "nonsquare") {
int width, height;
std::cin >> width >> height;
rect = new NonSquare(width, height);
}
else if (given == "square") {
int width;
std::cin >> width;
rect = new Square(width);
}
else if (given == "quit") {
break;
}
rect->Print();
delete rect;
}
return 0;
}
| true |
9487aff697fedba35e1a12c3c80ac56eb30c2b36 | C++ | lemaitre/concepts | /test.cpp | UTF-8 | 1,340 | 2.6875 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | #include <iostream>
#include <list>
#include <unordered_set>
#include <complex>
#include "concepts.h"
using namespace Concepts;
using namespace std;
Common{...Args} void common(Args... args) {}
Compatible{A, B} void compatible(A,B){}
Incrementable{I} void incr(I){}
#define PRINT(...) std::cout << #__VA_ARGS__ ":\t" << __VA_ARGS__ << std::endl
struct Foo{};
int main() {
common(3, std::complex<double>());
compatible(3, 3.0f);
std::cout << std::boolalpha;
PRINT(Incrementable<int>);
PRINT(Bitmask<int>);
PRINT(Bitmask<float>);
PRINT(ShiftableBitmask<int>);
PRINT(Ordered<int, float>);
PRINT(Ordered<complex<float>>);
PRINT(Arithmetic<int>);
PRINT(Arithmetic<complex<float>>);
PRINT(CompatibleArithmetic<complex<float>, float>);
PRINT(CompatibleArithmetic<float, complex<float>>);
PRINT(Swappable<int>);
PRINT(ValueSwappable<int*>);
PRINT(RandomAccessIterator<int*>);
PRINT(BidirectionnalIterator<list<int>::iterator>);
PRINT(RandomAccessIterator<list<int>::iterator>);
PRINT(ForwardIterator<unordered_set<int>::iterator>);
PRINT(BidirectionnalIterator<unordered_set<int>::iterator>);
PRINT(ReversibleContainer<list<int>>);
PRINT(Container<unordered_set<int>>);
PRINT(ReversibleContainer<unordered_set<int>>);
PRINT(Container<int[]>);
PRINT(Allocator<allocator<int>>);
return 0;
}
| true |
75294b0d6cb6023dc9c5bb0b64e7de65c5769304 | C++ | jesusrafaell/task2-3 | /task2/tarea2.cpp | UTF-8 | 7,237 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
#define M 1000 //total de hijos
//Vampiros
int table_vampires[M][M];
string name_vampires[M];
int n_vampires; //numero de vampieros
//Busquedas de Vampiros
string quest_vampieres[M]; //resultado de las las quest
int n_quest; //numero de quest resultas
//Clanes
string clanes[M]; //lideres de los clanes
int nro_clanes; //numero de clanes
//Nodos de la lista
struct nodo {
int nro_clans;
string boss_clan[M];
int mienbros_clan[M];
int generation_clan[M];
int n_response;
string response[M];
nodo *next;
};
//Lista para Imprimir los casos de prueba
typedef struct nodo *Jlist;
//Ordenar los clanes alfabeticamente
void order_clans(){
int salto = nro_clanes / 2;
while(salto > 0){
for(int i = salto; i < nro_clanes; i++){
int j = i - salto;
while(j >= 0){
int k = j + salto;
if(clanes[j].compare(clanes[k]) < 0){
j = -1;
}else{
string aux = clanes[j];
clanes[j] = clanes[k];
clanes[k] = aux;
}
}
}
salto /= 2;
}
}
//Cantidad de clanes
int clans(){
int cont = 0;
bool es_clan = false;
for (int i = 0; i < n_vampires; i++){
for (int j = 0; j < n_vampires; j++){
if(table_vampires[j][i] == 1){
es_clan = true;
}
}
if(!es_clan){
clanes[cont] = name_vampires[i];
cont++;
//cout << name_vampires[i] << endl;
}
es_clan = false;
}
nro_clanes = cont;
return cont;
}
//Posicion del nombre actual
int position(string name){
for (int i = 0; i < n_vampires; i++){
if(!name_vampires[i].compare(name)){
return i;
}
}
name_vampires[n_vampires] = name;
n_vampires++;
return (n_vampires-1);
}
//Si es una hoja del arbol o no
int is_hoja(int actual){
for (int i = 0; i < n_vampires; i++){
if(table_vampires[actual][i] == 1)
return 0;
}
return 1;
}
//Cantidad de mienbros de un clan
int cant_mienbros(int actual){
int cont = 0;
int cola[M];
int t_cola = 0;
int x = 0;
while(1){
for (int i = 0; i < n_vampires; i++){
if(table_vampires[actual][i] == 1){
cola[t_cola] = i;
t_cola++;
}
}
if(t_cola == x){
break;
}
actual = cola[x];
x++;
}
return t_cola;
}
//Numero de generaciones que tiene un clan
int cant_generation(int actual, int cont, int mcont){
if(is_hoja(actual)){
if(cont > mcont){
return cont;
}
return mcont;
}else{
for(int i = 0; i < n_vampires; i++){
if(table_vampires[actual][i] == 1){
mcont = cant_generation(i, cont+1, mcont);
}
}
}
return mcont;
}
//Si un nombre esta en el clan o no
int in_clan(int actual, string name,int x){
if(!name_vampires[actual].compare(name)){
return 1;
}else{
for(int i = 0; i < n_vampires; i++){
if(table_vampires[actual][i] == 1){
x = in_clan(i,name, x);
}
}
}
return x;
}
//inicializar la tabla de vampiros y las variables
void init_table(){
n_vampires = 0;
n_quest = 0;
for (int i = 0; i < M; i++){
for (int j = 0; j < M; j++){
table_vampires[i][j] = 0;
}
name_vampires[i] = " ";
}
}
//Donde seperar los dos nombres
int mitad(string names){ //Divición de los nombres
int cont = 0;
for (int i = 0; i < sizeof(names); i++){
if(names[i] == ' '){
return i;
}
}
return cont;
}
//Recorrer y imprimir los valores en la lista
void imprimir_lista(Jlist &list){
Jlist Node = list;
int cont=1;
while (Node != NULL){
cout << "Caso " << cont << ":" << endl; //Nro del caso
cout << Node->nro_clans << endl; //total de clanes
for(int i = 0; i < Node->nro_clans; i++){
cout << "Clan " << i+1 << ":" << endl << Node->boss_clan[i] << endl;
cout << Node->mienbros_clan[i] << " " << Node->generation_clan[i] << endl;
}
for(int i = 0; i < Node->n_response; i++){
cout << Node->response[i] << endl;
}
cout << endl;
cont++;
Node = Node->next;
}
}
//Guardar los casos de pruebas resultos
void save_case(Jlist &list){
Jlist Node = new (struct nodo);
Node->next = NULL;
Node->nro_clans = nro_clanes;
//Se guardan los lideres de los clanes
for(int i = 0; i < nro_clanes; i++){
Node->boss_clan[i] = clanes[i];
}
//Se guardan la cant de mienbros y nro de generaciones de cada clan
for (int i = 0; i < nro_clanes; i++){
int pos = position(clanes[i]);
Node->mienbros_clan[i] = cant_mienbros(pos) + 1; //cantidad de mienbros del clan
Node->generation_clan[i] = cant_generation(pos, 1, 1); //las generaciones mas el lider
}
//Se guardan las respuestas a las busquedas de nombres
Node->n_response = n_quest;
int x=0;
string line;
for(int j = 0; j < n_quest; j++){
line = quest_vampieres[j];
for (int i = 0; i < nro_clanes; i++){
int pos = position(clanes[i]);
if(in_clan(pos, line, 0)){
Node->response[x] = clanes[i];
x++;
break;
}
}
}
//Agregar grupo a la lista
if(list == NULL)
list = Node;
else{
Jlist t = list;
while(t->next != NULL){
t = t->next;
}
t->next = Node;
}
}
int main(){
int c;
cin >> c;
Jlist list = NULL;
for (int x = 1; x <= c; x++){
string k,l; //k fue convertido por l
string line;
init_table();
int parte2=false;
//Leer las lineas siguiente hasta que sea "."
while(1){
cin.sync();
getline(cin, line);
if (!line.compare(".")){
nro_clanes=clans();
order_clans();
save_case(list);
break;
}
int p = mitad(line);
if(p == 0){
parte2=true; //Ya solo se puede preguntar por nombres
}
if(parte2){ //Preguntar por un nombre
quest_vampieres[n_quest] = line;
n_quest++;
}else{ //Agregar vampiros
k = line.substr(0,p);
l = line.substr(p+1,sizeof(line));
int a = position(k);
int b = position(l);
table_vampires[a][b] = 1;
}
}
}
imprimir_lista(list); //Imprimir los casos de pruebas
} | true |
0f1df7094f9cf99caf0f9eb4c97a320b2179ff6c | C++ | kkathpal153/Spoj- | /familyp.cpp | UTF-8 | 761 | 2.75 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int i,j,k,l,n,s,d,c;
cin>>n;
int z[100][100];
while(n--)
{
cin>>s>>c;
for(i=0;i<s;i++)
cin>>z[0][i];
// till herer insertion is done
//first subroutine calculate delta and other dealts^n
for(i=1;i<s;i++)
for(j=0;j<s-i;j++)
z[i][j]=z[i-1][j+1]-z[i-1][j];
//here the calculation of the delta ends
for(i=1;i<c+1;i++)
z[s-1][i]=z[s-1][0];
//here the addition of the constant ends here
//now the main tast to add that new series to the whole equation
for(i=s-2;i>=0;i--)
for(j=s-i;j<s-i+c;j++)
z[i][j]=z[i][j-1]+z[i+1][j-1];
for(i=s;i<s+c;i++)
cout<<z[0][i]<<" ";
cout<<endl;
}
}
| true |
6c12582729b02b98ea14485e9cdf647d8854939a | C++ | NikitaGrebeniuk/cs50 | /Home/hw25.02/task2.cpp | UTF-8 | 4,887 | 3.5 | 4 | [] | no_license | #include <stdio.h>
#include <iostream> //Подключаем библиотеку, обрабатывающую
//стандартные потоки ввода/вывода
//#include <conio.h>
const int ABCSize = 26; //Размер алфавита
const char low_ch[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; //Массив
//строчных букв, которые шифруются также строчными
const char high_ch[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; //Массив
//заглавных букв, которые шифруются также заглавными
std::string cipher(const std::string &input_s, const int shift)
{ //Функция осуществляет сдвиг строки по алфавиту на указанную величину
bool Ok; //Был ли символ определен как буква алфавита и затем зашифрован
std::string output_s(""); //Зашифрованная строка, вначале инициализируется
//пустой строкой
for(unsigned i = 0; i < input_s.length(); i++)
{ //Для всех символов шифруемой строки
Ok = false; //Вначале сбрасываем значение флага
for(int j = 0; j < ABCSize; j++)
{ //Перебираем все буквы алфавита на поиск соответствия
if (input_s[i] == low_ch[j]) //Если символ оказался строчной буквой алфавита
{
j += shift; //Сдвигаем букву по алфавиту на указанное значение
while (j >= ABCSize) j -= ABCSize; //Если значение вышло за диапазон,
while (j < 0) j += ABCSize; //корректируем его
output_s += low_ch[j]; //Добавляем полученный символ в конец
//зашифрованной строки
Ok = true; //Символ был благополучно зашифрован и добавлен в строку
break; //Перебор для данного символа можно закончить
}
else if (input_s[i] == high_ch[j]) //То же самое, если символ оказался
//заглавной буквой алфавита
{
j += shift;
if (j >= ABCSize) j -= ABCSize;
else if (j < 0) j += ABCSize;
output_s += high_ch[j];
Ok = true;
break;
}
}
if (!Ok) output_s += input_s[i]; //Если символ не является буквой алфавита,
//записываем его без изменений
}
return output_s; //По окончании возвращаем получившуюся строку
}
int main()
{
std::string s; //Шифруемая/дешифруемая строка
std::cout << "If you want to cipher string, press \"1\", if you want to decode,"
" press \"2\"";
bool Ok = false; //Корректна ли нажатая клавиша
int shift = 0; //Величина сдвига
while(!Ok) //Пока не будет нажато "1" или "2"
{
switch(getchar())
{
case '1': //Если нажато "1", шифруем строку
{
std::cout << "\nInput shift: ";
std::cin >> shift;
std::cout << "Input string to cipher: ";
while (std::cin >> s) //Шифруем одним и тем же сдвигом по одному слову
{
std::cout << cipher(s, shift) << ' ';
if (std::cin.get() == '\n') break; //Заканчиваем по нажатию Enter
}
Ok = true; //Клавиша была нажата корректно
} break;
case '2': //Если нажато "2", пытаемся дешифровать строку
{
bool Done = false; //Завершен ли процесс дешифровки
std::cout << "\nInput string to decode: ";
getline(std::cin, s); //Считываем всю дешифруемую строку
for (int i = 0; i < ABCSize && !Done; i++) //Пробуем разные величины сдвига
//до тех пор, пока не расшифруем или не проверим все возможные его значения
{
std::cout << "\nWith shift equal " << i << " we have such string:\n";
std::cout << cipher(s, i);
std::cout << "\nIf decoding is done, press \"1\"";
if (getchar() == '1') Done = true; //Строка дешифрована
}
Ok = true; //Клавиша была нажата корректно
} break;
default: std::cout << "Press either \"1\" or \"2\"!"; //Некорректно нажатая
//клавиша
}
}
getchar();
} | true |
487bc2ec28dcec16e3924127a85e606fa1703b38 | C++ | watashi/AlgoSolution | /zoj/30/3051.cpp | UTF-8 | 4,912 | 3.046875 | 3 | [] | no_license | #include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Hand;
class Card
{
friend class Hand;
private:
int suit, rank;
public:
friend bool operator<(const Card& lhs, const Card& rhs)
{
return lhs.rank < rhs.rank;
}
friend istream& operator>>(istream& is, Card& c)
{
char ch;
is >> ch;
switch(ch) {
case 'H': c.suit = 0; break;
case 'S': c.suit = 1; break;
case 'D': c.suit = 2; break;
case 'C': c.suit = 3; break;
default: throw "INVAILD_SUIT";
}
is >> ch;
switch(ch) {
case 'T': c.rank = 10; break;
case 'J': c.rank = 11; break;
case 'Q': c.rank = 12; break;
case 'K': c.rank = 13; break;
case 'A': c.rank = 14; break;
default:
if (!(ch >= '2' && ch <= '9')) {
throw "INVALID_RANK";
}
c.rank = ch - '0'; break;
}
return is;
}
};
class Hand
{
private:
vector<Card> vc;
bool isflush()
{
for (size_t i = 1; i < 5; i++) {
if (vc[i].suit != vc[0].suit) {
return false;
}
}
return true;
}
bool isstraihgt()
{
for (size_t i = 1; i < 5; i++) {
if (vc[i].rank != vc[0].rank + i) {
return false;
}
}
return true;
}
bool has_4()
{
return vc[0].rank == vc[3].rank || vc[1].rank == vc[4].rank;
}
bool has_3_2()
{
return vc[0].rank == vc[2].rank && vc[3].rank == vc[4].rank ||
vc[0].rank == vc[1].rank && vc[2].rank == vc[4].rank;
}
bool has_3()
{
for (int i = 2; i < 5; i++) {
if (vc[i - 2].rank == vc[i].rank) {
return true;
}
}
return false;
}
int cnt_2()
{
int ret = 0;
for (int i = 1; i < 5; i++) {
if (vc[i].rank == vc[i - 1].rank) {
++ret;
}
}
return ret;
}
public:
void add(const Card& c)
{
vc.push_back(c);
}
int rate()
{
if (vc.size() != 5) {
throw "INVALID_HAND";
}
sort(vc.begin(), vc.end());
bool flush = isflush(), straihgt = isstraihgt();
if (flush && straihgt) {
return (vc[4].rank == 14) ? 500 : 100;
}
else if (has_4()) {
return 50;
}
else if (has_3_2()) {
return 15;
}
else if (flush) {
return 10;
}
else if (straihgt) {
return 8;
}
else if (has_3()) {
return 4;
}
else {
switch (cnt_2()) {
case 2: return 3;
case 1: return 2;
case 0: return 0;
default: throw "INVAILD_CNT_2";
}
}
}
};
int rate(const vector<Card>& vc)
{
int ret = 0;
vector<bool> p(5, false);
for (size_t i = vc.size() - 5; i < 5; i++) {
p[i] = true;
}
do {
Hand h;
for (size_t i = 0; i < 5; i++) {
if (p[i]) {
h.add(vc[i]);
}
}
for (size_t i = 5; i < vc.size(); i++) {
h.add(vc[i]);
}
ret = max(ret, h.rate());
} while (next_permutation(p.begin(), p.end()));
return ret;
}
int main(void)
{
int n;
while (cin >> n) {
vector<Card> vc(n);
for (int i = 0; i < n; i++) {
cin >> vc[i];
}
vector<int> dp(n + 1, 0);
dp[0] = 1;
for (int i = 5; i <= n; i++) {
for (int j = max(0, i - 10); j <= i - 5; j++) {
dp[i] = max(dp[i], min(9999, dp[j] * rate(vector<Card>(vc.begin() + j, vc.begin() + i))));
}
}
int ans = *max_element(dp.begin() + 5, dp.end());
cout << 16 + ((ans == 0) ? -1 : (10 * (ans - 1))) << endl;
}
return 0;
}
//Run ID Submit Time Judge Status Problem ID Language Run Time(ms) Run Memory(KB) User Name
//1711140 2008-11-26 21:25:48 Accepted 3051 C++ 170 184 watashi@Zodiac
// 2012-09-07 01:58:46 | Accepted | 3051 | C++ | 170 | 188 | watashi | Source
| true |
26151ce624786c8606e0e3229add079a5e9e6e31 | C++ | lilieming/libpqxx | /include/pqxx/strconv.hxx | UTF-8 | 10,505 | 3 | 3 | [
"BSD-3-Clause"
] | permissive | /* String conversion definitions.
*
* DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/stringconv instead.
*
* Copyright (c) 2000-2019, Jeroen T. Vermeulen.
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*/
#ifndef PQXX_H_STRINGCONV
#define PQXX_H_STRINGCONV
#include "pqxx/compiler-public.hxx"
#include <limits>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <typeinfo>
namespace pqxx
{
/**
* @defgroup stringconversion String conversion
*
* The PostgreSQL server accepts and represents data in string form. It has
* its own formats for various data types. The string conversions define how
* various C++ types translate to and from their respective PostgreSQL text
* representations.
*
* Each conversion is defined by a specialisation of the @c string_traits
* template. This template implements some basic functions to support the
* conversion, ideally in both directions.
*
* If you need to convert a type which is not supported out of the box, define
* your own @c string_traits specialisation for that type, similar to the ones
* defined here. Any conversion code which "sees" your specialisation will now
* support your conversion. In particular, you'll be able to read result
* fields into a variable of the new type.
*
* There is a macro to help you define conversions for individual enumeration
* types. The conversion will represent enumeration values as numeric strings.
*/
//@{
// TODO: Do better! Was having trouble with template variables.
/// A human-readable name for a type, used in error messages and such.
/** The default implementation falls back on @c std::type_info::name(), which
* isn't necessarily human-friendly.
*/
template<typename TYPE> const std::string type_name{typeid(TYPE).name()};
} // namespace pqxx
namespace pqxx::internal
{
/// Throw exception for attempt to convert null to given type.
[[noreturn]] PQXX_LIBEXPORT void throw_null_conversion(
const std::string &type);
/// Helper: string traits implementation for built-in types.
/** These types all look much alike, so they can share much of their traits
* classes (though templatised, of course).
*
* The actual `to_string` and `from_string` are implemented in the library,
* but the rest is defined inline.
*/
template<typename TYPE> struct PQXX_LIBEXPORT builtin_traits
{
static constexpr bool has_null() noexcept { return false; }
static constexpr bool is_null(TYPE) { return false; }
static void from_string(std::string_view str, TYPE &obj);
static std::string to_string(TYPE obj);
};
constexpr char number_to_digit(int i) noexcept
{ return static_cast<char>(i+'0'); }
} // namespace pqxx::internal
namespace pqxx
{
/// Traits class for use in string conversions.
/** Specialize this template for a type for which you wish to add to_string
* and from_string support.
*/
template<typename T, typename = void> struct string_traits;
/// Helper class for defining enum conversions.
/** The conversion will convert enum values to numeric strings, and vice versa.
*
* To define a string conversion for an enum type, derive a @c string_traits
* specialisation for the enum from this struct.
*
* There's usually an easier way though: the @c PQXX_DECLARE_ENUM_CONVERSION
* macro. Use @c enum_traits manually only if you need to customise your
* traits type in more detail, e.g. if your enum has a "null" value built in.
*/
template<typename ENUM>
struct enum_traits
{
using underlying_type = typename std::underlying_type<ENUM>::type;
using underlying_traits = string_traits<underlying_type>;
static constexpr bool has_null() noexcept { return false; }
[[noreturn]] static ENUM null()
{ internal::throw_null_conversion("enum type"); }
static void from_string(std::string_view str, ENUM &obj)
{
underlying_type tmp;
underlying_traits::from_string(str, tmp);
obj = ENUM(tmp);
}
static std::string to_string(ENUM obj)
{ return underlying_traits::to_string(underlying_type(obj)); }
};
/// Macro: Define a string conversion for an enum type.
/** This specialises the @c pqxx::string_traits template, so use it in the
* @c ::pqxx namespace.
*
* For example:
*
* #include <iostream>
* #include <pqxx/strconv>
* enum X { xa, xb };
* namespace pqxx { PQXX_DECLARE_ENUM_CONVERSION(x); }
* int main() { std::cout << to_string(xa) << std::endl; }
*/
#define PQXX_DECLARE_ENUM_CONVERSION(ENUM) \
template<> \
struct string_traits<ENUM> : pqxx::enum_traits<ENUM> \
{ \
[[noreturn]] static ENUM null() \
{ internal::throw_null_conversion(type_name<ENUM>); } \
}
//@}
} // namespace pqxx
namespace pqxx
{
/// Helper: declare a string_traits specialisation for a builtin type.
#define PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(TYPE) \
template<> struct PQXX_LIBEXPORT string_traits<TYPE> : \
internal::builtin_traits<TYPE> \
{ \
[[noreturn]] static TYPE null() \
{ pqxx::internal::throw_null_conversion(type_name<TYPE>); } \
}
PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(bool);
PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(short);
PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(unsigned short);
PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(int);
PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(unsigned int);
PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(long);
PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(unsigned long);
PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(long long);
PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(unsigned long long);
PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(float);
PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(double);
PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(long double);
#undef PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION
/// String traits for C-style string ("pointer to const char").
template<> struct PQXX_LIBEXPORT string_traits<const char *>
{
static constexpr bool has_null() noexcept { return true; }
static constexpr bool is_null(const char *t) { return t == nullptr; }
static constexpr const char *null() { return nullptr; }
static void from_string(std::string_view str, const char *&obj)
{ obj = str.data(); }
static std::string to_string(const char *obj) { return obj; }
};
/// String traits for non-const C-style string ("pointer to char").
template<> struct PQXX_LIBEXPORT string_traits<char *>
{
static constexpr bool has_null() noexcept { return true; }
static constexpr bool is_null(const char *t) { return t == nullptr; }
static constexpr const char *null() { return nullptr; }
// Don't allow this conversion since it breaks const-safety.
// static void from_string(std::string_view str, char *&obj);
static std::string to_string(char *obj) { return obj; }
};
/// String traits for C-style string constant ("array of char").
template<size_t N> struct PQXX_LIBEXPORT string_traits<char[N]>
{
static constexpr bool has_null() noexcept { return true; }
static constexpr bool is_null(const char t[]) { return t == nullptr; }
static constexpr const char *null() { return nullptr; }
static std::string to_string(const char obj[]) { return obj; }
};
template<> struct PQXX_LIBEXPORT string_traits<std::string>
{
static constexpr bool has_null() noexcept { return false; }
static constexpr bool is_null(const std::string &) { return false; }
[[noreturn]] static std::string null()
{ internal::throw_null_conversion(type_name<std::string>); }
static void from_string(std::string_view str, std::string &obj)
{ obj = str; }
static std::string to_string(const std::string &obj) { return obj; }
};
template<> struct PQXX_LIBEXPORT string_traits<const std::string>
{
static constexpr bool has_null() noexcept { return false; }
static constexpr bool is_null(const std::string &) { return false; }
[[noreturn]] static const std::string null()
{ internal::throw_null_conversion(type_name<std::string>); }
static std::string to_string(const std::string &obj) { return obj; }
};
template<> struct PQXX_LIBEXPORT string_traits<std::stringstream>
{
static constexpr bool has_null() noexcept { return false; }
static constexpr bool is_null(const std::stringstream &) { return false; }
[[noreturn]] static std::stringstream null()
{ internal::throw_null_conversion(type_name<std::stringstream>); }
static void from_string(std::string_view str, std::stringstream &obj)
{ obj.clear(); obj << str; }
static std::string to_string(const std::stringstream &obj)
{ return obj.str(); }
};
/// Weird case: nullptr_t. We don't fully support it.
template<> struct PQXX_LIBEXPORT string_traits<std::nullptr_t>
{
static constexpr bool has_null() noexcept { return true; }
static constexpr bool is_null(std::nullptr_t) noexcept { return true; }
static constexpr std::nullptr_t null() { return nullptr; }
static std::string to_string(const std::nullptr_t &)
{ return "null"; }
};
// TODO: Implement date conversions.
/// Attempt to convert postgres-generated string to given built-in type
/** If the form of the value found in the string does not match the expected
* type, e.g. if a decimal point is found when converting to an integer type,
* the conversion fails. Overflows (e.g. converting "9999999999" to a 16-bit
* C++ type) are also treated as errors. If in some cases this behaviour should
* be inappropriate, convert to something bigger such as @c long @c int first
* and then truncate the resulting value.
*
* Only the simplest possible conversions are supported. No fancy features
* such as hexadecimal or octal, spurious signs, or exponent notation will work.
* No whitespace is stripped away. Only the kinds of strings that come out of
* PostgreSQL and out of to_string() can be converted.
*/
template<typename T> inline void from_string(std::string_view str, T &obj)
{
if (str.data() == nullptr)
throw std::runtime_error{"Attempt to read null string."};
string_traits<T>::from_string(str, obj);
}
template<typename T>
inline void from_string(const std::stringstream &str, T &obj) //[t00]
{ from_string(str.str(), obj); }
/// Convert built-in type to a readable string that PostgreSQL will understand
/** No special formatting is done, and any locale settings are ignored. The
* resulting string will be human-readable and in a format suitable for use in
* SQL queries.
*/
template<typename T> std::string to_string(const T &obj)
{ return string_traits<T>::to_string(obj); }
} // namespace pqxx
#endif
| true |
5bd3894b2ab0f13ddef214825c53553ba886e2a3 | C++ | yangjiang123/possumwood | /src/libs/dependency_graph/data.cpp | UTF-8 | 1,716 | 3.3125 | 3 | [
"MIT"
] | permissive | #include "data.inl"
namespace dependency_graph {
Data::Data() {
}
Data::Data(const Data& d) {
m_data = d.m_data;
assert(std::string(d.typeinfo().name()) == std::string(typeinfo().name()));
}
Data& Data::operator = (const Data& d) {
// it should be possible to:
// 1. assign values between the same types
// 2. assign a value to a null (void) data - connecting void ports
// 3. assign a null (void) to a value - disconnecting void ports
assert(std::string(d.typeinfo().name()) == std::string(typeinfo().name()) || empty() || d.empty());
m_data = d.m_data;
return *this;
}
bool Data::operator == (const Data& d) const {
assert(m_data != nullptr && d.m_data != nullptr);
return m_data->isEqual(*d.m_data);
}
bool Data::operator != (const Data& d) const {
assert(m_data != nullptr && d.m_data != nullptr);
return !m_data->isEqual(*d.m_data);
}
const std::type_info& Data::typeinfo() const {
if(m_data == nullptr)
return typeid(void);
return m_data->typeinfo();
}
Data Data::create(const std::string& type) {
auto it = StaticInitialisation::dataFactories().find(type);
if(it == StaticInitialisation::dataFactories().end()) {
std::stringstream err;
err << "Error instantiating type '" << type << "' - no registered factory found (plugin not loaded?)";
throw std::runtime_error(err.str());
}
return it->second();
}
std::string Data::type() const {
return dependency_graph::unmangledName(typeinfo().name());
}
std::string Data::toString() const {
if(m_data == nullptr)
return "(null)";
return m_data->toString();
}
bool Data::empty() const {
return m_data == nullptr;
}
std::ostream& operator << (std::ostream& out, const Data& bd) {
out << bd.toString();
return out;
}
}
| true |
d958391e7eca892d57cadca0f2861a67e6c3404b | C++ | kajames2/double_auction | /include/market/market.h | UTF-8 | 1,635 | 2.734375 | 3 | [] | no_license | #ifndef _MARKET_MARKET_H_
#define _MARKET_MARKET_H_
#include <map>
#include <ostream>
#include "market/clearing_queue.h"
#include "market/holdings.h"
#include "market/market_state.h"
#include "market/offer_validity.h"
namespace market {
class Market {
public:
Market() : auction_(true, true) {}
Market(std::map<int, Holdings> init)
: auction_(true, true), player_holdings_(init) {}
template <typename T>
std::vector<Transaction> AcceptOffer(T offer) {
auction_.AddOffer(offer);
return Update(offer.timestamp);
}
template <typename T>
OfferValidity CheckOffer(T offer) const;
void RetractOffer(int unique_id) { auction_.RetractOffer(unique_id); }
Holdings GetHoldings(int id) const { return player_holdings_.at(id); }
std::map<int, Holdings> GetAllHoldings() const { return player_holdings_; }
std::vector<Bid> GetBids(int id) const { return auction_.GetBids(id); }
std::vector<Ask> GetAsks(int id) const { return auction_.GetAsks(id); }
std::vector<Transaction> GetTransactionHistory() const {
return auction_.GetHistory();
}
MarketState GetState() const {
return MarketState{player_holdings_, GetTransactionHistory(),
auction_.GetBidQueue(), auction_.GetAskQueue()};
}
private:
std::vector<Transaction> Update(double time);
bool SufficientCash(Bid bid) const;
bool SufficientUnits(Ask ask) const;
bool SufficientCash(Ask ask) const {return true;}
bool SufficientUnits(Bid bid) const {return true;}
market::ClearingQueue auction_;
std::map<int, Holdings> player_holdings_;
};
} // namespace market
#endif // _MARKET_MARKET_H_
| true |
850aa062ea2be9dbb8dc6d8483e013f031000422 | C++ | 4625204/lab3 | /lab3.cpp | UTF-8 | 391 | 2.78125 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{ int i,data,num,sum=0;
vector<int> a;
ifstream infile("file.in",ios::in);
infile>>num;
while(infile>>data)
{ a.push_back(data);}
sort(a.begin(),a.end());
reverse(a.begin(),a.end());
for(i=0;i<5;++i)
{sum=sum+a.at(i);}
cout<<sum<<endl;
return 0;
}
| true |
b8fbe93b6741e26c12ef1c100bfc5d5d6e3538c1 | C++ | iamukasa/pookas | /quiz bot/TestBot/code/QuizParticipant.cpp | UTF-8 | 1,320 | 2.59375 | 3 | [] | no_license | #include "QuizParticipant.h"
QuizParticipant::QuizParticipant(void)
{
score = 0;
name = "";
}
QuizParticipant::QuizParticipant( int session )
{
sessionID = session;
state = QUIZPLAYER_CLICKED;
score = 0;
}
QuizParticipant::~QuizParticipant(void)
{
}
void QuizParticipant::setState( PlayerState s )
{
state = s;
}
PlayerState QuizParticipant::getState()
{
return state;
}
void QuizParticipant::setSessionID( int session )
{
sessionID = session;
}
int QuizParticipant::getSessionID()
{
return sessionID;
}
//sphere collision with a sphere centred at point x, y, z
bool QuizParticipant::checkCollision( Vect3D objPos, int radius )
{
//get this player's position
if ( int rc = aw_avatar_location (NULL, sessionID, NULL) )
{
return false;
}
Vect3D playerPos( (float)aw_int(AW_AVATAR_X), (float)aw_int(AW_AVATAR_Y), (float)aw_int(AW_AVATAR_Z) );
//check collision with the object pos
float dist = Vect3D::Distance( playerPos, objPos );
if ( dist <= radius )
{
return true;
}
return false;
}
void QuizParticipant::addScore()
{
score+=1;
}
int QuizParticipant::getScore()
{
return score;
}
void QuizParticipant::setName(std::string n)
{
name = n;
}
std::string QuizParticipant::getName()
{
return name;
} | true |
897aeac7432929530c80ae18270bf5f822b2a41b | C++ | hyperpace/study_algo_gangnam | /CNK/codePlus_basic/day01/04_1406_main.cpp | UTF-8 | 1,054 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
using namespace std;
/*
에디터
https://www.acmicpc.net/problem/1406
*/
int main() {
ios_base::sync_with_stdio(false);
string str;
int n;
stack<char> left, right;
cin >> str;
cin >> n;
for (int i = 0; i < str.size(); i++) {
left.push(str[i]);
}
while (n--) {
string command;
cin.ignore();
cin >> command;
if (command == "L") {
if (!left.empty()) {
right.push(left.top());
left.pop();
}
}
if (command == "D") {
if (!right.empty()) {
left.push(right.top());
right.pop();
}
}
if (command == "B") {
if(!left.empty()) {
left.pop();
}
}
if (command == "P") {
char c;
cin >> c;
left.push(c); // char 단위
}
}
while(!left.empty()) {
right.push(left.top());
left.pop();
}
while(!right.empty()) {
cout << right.top();
right.pop();
}
cout << '\n';
return 0;
} | true |
1591f9d75c8807094c3a867030b94aab1a88c840 | C++ | AlirezaMojtabavi/misInteractiveSegmentation | /misDatasetManager/ColorMapBoneCT.cpp | UTF-8 | 2,025 | 2.609375 | 3 | [] | no_license | #include "stdafx.h"
#include "ColorMapBoneCT.h"
#include <boost/range/iterator_range.hpp>
ColorMapBoneCT::ColorMapBoneCT(double minThreshold, double maxThreshold)
: m_MaxThreshold(maxThreshold),
m_MinThreshold(minThreshold)
{
}
void ColorMapBoneCT::SetViewingThreshold( bool usedDefaultThreshold, double minThreshold)
{
const auto range = 2400;
if (usedDefaultThreshold)
{
m_MinThreshold = 250;
m_MaxThreshold = m_MinThreshold + range;
}
else
{
m_MaxThreshold = m_MinThreshold + range;
}
}
void ColorMapBoneCT::SetMinThreshold(double value)
{
m_MinThreshold = value;
}
void ColorMapBoneCT::SetMaxThreshold(double value)
{
m_MaxThreshold = value;
}
misColorListTypedef ColorMapBoneCT::GetColorMap(bool useDefaultThreshold, const misColorStruct& objectColor) const
{
misColorListTypedef colorList;
if (useDefaultThreshold)
{
misColorStruct redColor;
redColor.red = 229;
redColor.green = 40;
redColor.blue = 20;
redColor.alpha = 0.0;
colorList[m_MinThreshold - 1] = redColor;
redColor.alpha = 0.2;
colorList[m_MinThreshold] = redColor;
misColorStruct sunflowerColor;
sunflowerColor.red = 229;
sunflowerColor.green = 203;
sunflowerColor.blue = 138;
sunflowerColor.alpha = 1.0;
colorList[m_MinThreshold + 100] = sunflowerColor;
colorList[m_MinThreshold + 269] = sunflowerColor;
sunflowerColor.ChangeColor( 25, 20, 5);
sunflowerColor.alpha = 1.0;
colorList[m_MaxThreshold] = sunflowerColor;
sunflowerColor.alpha = 0;
colorList[m_MaxThreshold + 1] = sunflowerColor;
}
else
{
misColorStruct redColor(255,0,0,1.0);
misColorStruct whiteColor(249,255,255,0.36);
auto color = objectColor;
redColor.alpha = 0.0;
colorList[m_MinThreshold - 1] = redColor;
redColor.alpha = 0.0;
colorList[m_MinThreshold+150] = redColor;
redColor.alpha = 1.0;
colorList[m_MinThreshold + 265] = whiteColor;
color.alpha = 1.0;
colorList[m_MinThreshold + 968] = color;
color.alpha = 0;
colorList[m_MaxThreshold + 1] = color;
}
return colorList;
}
| true |
fd9aa27e2fe89e55996a6acbf6043a5f8a73be3c | C++ | ALXlixiong/day_code | /other_code/4_21_test/str/strcat.cc | UTF-8 | 385 | 3.234375 | 3 | [] | no_license | #include<iostream>
using namespace std;
#include<string.h>
#include<assert.h>
char *my_strcat(char*str1,const char* str2)
{
assert(str1);
assert(str2);
char *ret = str1;
while(*str1)
{
str1++;//
}
while(*str1++ = *str2++)
{
;
}
return ret;
}
int main()
{
char str1[14] = "hello ";
char *str2 = "world";
cout<<my_strcat(str1,str2)<<endl;
return 0;
}
| true |