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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
492414f52b1f41783ff0bfd462cd79cd128cff0d | C++ | cde8eae8/ITMO-s5 | /machine-learning/codeforces/linear-regression/linear-regression.cpp | UTF-8 | 12,195 | 2.546875 | 3 | [] | no_license | //
// Created by nikita on 9/29/20.
//
#include <numeric>
#include <cmath>
#include <queue>
#include <cassert>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <iostream>
#include <algorithm>
#ifdef LOCAL
#include "../debug.h"
#endif
#define NORMALIZE
double sign(double v) {
return v < 0 ? -1 : 1;
}
double SMAPE(double exp, double act) {
return (fabs(exp - act)) / (fabs(exp) + fabs(act));
}
using Matrix = std::vector<std::pair<std::vector<double>, double>>;
using RegressionCoefficients = std::vector<double>;
using NormalizationCoefficients = std::vector<std::pair<double, double>>;
double applyLinear(std::vector<double> const &ws, std::vector<double> const &xs) {
return std::inner_product(xs.begin(), xs.end(), ws.begin(), 0.0);
}
struct SMAPEFunc {
static double func(double predicted, double label) {
return SMAPE(predicted, label);
}
static std::vector<double> diff(double predicted, double label, std::vector<double> const &xs) {
double sum_abss = fabs(predicted) + fabs(label);
double k = 1 / pow(sum_abss + 0.000000001, 2);
std::vector<double> diff_vec;
for (size_t j = 0; j < xs.size(); ++j) {
double delta = k * (sign(predicted - label) * xs[j] * sum_abss
- fabs(predicted - label) * (sign(predicted)) * xs[j]);
diff_vec.push_back(delta);
}
return diff_vec;
}
};
struct SquareFunc {
static double func(double predicted, double label) {
return pow(predicted - label, 2);
}
static std::vector<double> diff(double predicted, double label, std::vector<double> const &xs) {
// (label - <ws, xs>)^2
// 2*(label - <ws, xs>) * x[i]
std::vector<double> diff_vec(xs.size());
std::transform(xs.begin(), xs.end(), diff_vec.begin(), [&, predicted, label](double v) {
return 2 * (predicted - label) * v;
});
return diff_vec;
}
};
template<typename Func>
std::vector<double> regression(Matrix matrix,
size_t iterations, double step, double l1, double a, size_t b_max, double alpha) {
// std::cout << iterations << " " << step << " " << l1 << " " << a << " " << b_max << " " << alpha << std::endl;
std::for_each(matrix.begin(), matrix.end(), [](auto &v) { v.first.push_back(1); });
std::vector<double> ws(matrix[0].first.size(), 0.0);
std::for_each(ws.begin(), ws.end(), [&](double &v) {
double n = matrix.size() * 2;
// v = static_cast<double>(rand() % n) / n;
size_t n_step = 1000;
v = static_cast<double>(rand() % n_step) / n_step / n - 0.5 / n;
});
double error = std::accumulate(matrix.begin(), matrix.end(), 0.0, [&](double acc, auto &v) {
double predicted = applyLinear(ws, v.first);
return acc + Func::func(predicted, v.second);
});
std::vector<double> accumulated_delta(ws.size());
std::deque<double> last_errors;
for (size_t iter = 0; iter <= iterations * b_max; ++iter) {
size_t i = iter % matrix.size();
double label = matrix[i].second;
const std::vector<double> &xs = matrix[i].first;
double predicted = applyLinear(ws, xs);
error = (1 - alpha) * error + alpha * (Func::func(predicted, label));
std::vector<double> diff_vec = Func::diff(predicted, label, xs);
// std::for_each(diff_vec.begin(), diff_vec.end(), [](double&v) { v = std::max(-0.1, std::min(v, 0.1)); });
// std::for_each(diff_vec.begin(), diff_vec.end(), [&](double &v) { v = 0.5 / matrix.size() * v; });
std::transform(diff_vec.begin(), diff_vec.end(), accumulated_delta.begin(), accumulated_delta.begin(),
[](double d, double a) { return d + a; });
if (iter % b_max == 0) {
last_errors.push_back(error);
double diff = *std::max_element(last_errors.begin(), last_errors.end())
- *std::min_element(last_errors.begin(), last_errors.end());
size_t size = 5;
if (last_errors.size() > size && diff < 1e-3) {
std::cout << "break " << iter << std::endl;
break;
}
if (last_errors.size() > size) {
last_errors.pop_back();
}
std::for_each(accumulated_delta.begin(), accumulated_delta.end(), [=](double &v) {
v /= b_max;
});
double p = static_cast<double>(iter) / b_max;
double s = step / sqrt(p + 1);
for (size_t j = 0; j < xs.size(); ++j) {
// === ||w||^2_2 ===
// L + ||w||^2_2 = L + t*sum(w_i^2)
// diff = L' + 2t*w_i
// ws_k+1 = ws_k - s*L' - s*2t*ws_k
// ws_k+1 = ws_k * (1 - s * 2t) - s * L'
// === ||w|| ===
// ||w||' = sign(w_i)
// ws[j] = ws[j] - s * (a * (1 - l1) * ws[j] + accumulated_delta[j]); //- a * l1 * sign(ws[j]));
ws[j] = ws[j] - s * (accumulated_delta[j] + a * ws[j]); //- a * l1 * sign(ws[j]));
accumulated_delta[j] = 0;
}
}
}
return ws;
}
Matrix readMatrix(size_t n_obj, size_t n_features) {
if (n_obj == 0) return {};
Matrix matrix(n_obj, {std::vector<double>(n_features), 0});
int32_t f;
for (size_t i = 0; i < n_obj; ++i) {
for (size_t j = 0; j < n_features; ++j) {
std::cin >> f;
matrix[i].first[j] = f;
}
std::cin >> f;
matrix[i].second = f;
}
return matrix;
}
NormalizationCoefficients normalize(Matrix &matrix) {
size_t n_obj = matrix.size();
size_t n_features = matrix[0].first.size();
NormalizationCoefficients ncoeffs(n_features + 1);
std::vector<double> means(n_features + 1);
std::vector<double> stds(n_features + 1);
for (size_t i = 0; i < n_obj; ++i) {
for (size_t j = 0; j < n_features; ++j) {
means[j] += matrix[i].first[j];
}
means.back() += matrix[i].second;
}
std::for_each(means.begin(), means.end(), [&](double &d) { d /= matrix.size(); });
for (size_t i = 0; i < n_obj; ++i) {
for (size_t j = 0; j < n_features; ++j) {
stds[j] += pow(matrix[i].first[j] - means[j], 2);
}
stds.back() += pow(matrix[i].second - means.back(), 2);
}
std::for_each(stds.begin(), stds.end(), [&](double &d) { d = sqrt(d / matrix.size()); });
for (size_t i = 0; i < n_features + 1; ++i) {
ncoeffs[i] = {means[i], stds[i] == 0 ? 1 : stds[i]};
}
for (size_t i = 0; i < n_obj; ++i) {
for (size_t j = 0; j < n_features; ++j) {
matrix[i].first[j] -= ncoeffs[j].first;
matrix[i].first[j] /= ncoeffs[j].second;
}
matrix[i].second -= ncoeffs.back().first;
matrix[i].second /= ncoeffs.back().second;
}
return ncoeffs;
}
std::vector<double> denormalize(std::vector<double> coeffs, std::vector<std::pair<double, double>> const &ncoeffs) {
size_t n_features = coeffs.size() - 1;
for (size_t i = 0; i < n_features; ++i) {
coeffs.back() -= ncoeffs[i].first / ncoeffs[i].second * coeffs[i];
coeffs[i] = coeffs[i] / ncoeffs[i].second;
}
for (size_t i = 0; i < n_features + 1; ++i) {
coeffs[i] *= ncoeffs.back().second;
}
coeffs.back() += ncoeffs.back().first;
return coeffs;
}
template<typename Func>
std::vector<double>
normalized_regression(Matrix d_train, size_t iterations, double step, double l1, double a, size_t b_max, double alpha) {
NormalizationCoefficients ncoeffs = normalize(d_train);
RegressionCoefficients coeffs = regression<Func>(d_train, iterations, step, l1, a, b_max, alpha);
coeffs = denormalize(coeffs, ncoeffs);
return coeffs;
}
#ifdef PYMODULE
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
namespace py = pybind11;
PYBIND11_MODULE(pylinear, m) {
m.def("norm_linear", &normalized_regression<SquareFunc>);
m.def("linear", ®ression<SquareFunc>);
m.def("smnorm_linear", &normalized_regression<SMAPEFunc>);
m.def("smlinear", ®ression<SMAPEFunc>);
}
#else
#ifdef CF_MAIN
int main(int args, char **argv) {
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
size_t n_obj_train{};
size_t n_features{};
std::cin >> n_obj_train;
std::cin >> n_features;
double step = 0.1; // 0.0001; // 0.01;
double tau = 0.1;// 1e-6;
double b = 1;
double alpha = 1 - 1e03;
Matrix d_train = readMatrix(n_obj_train, n_features);
auto coeffs = normalized_regression<SMAPEFunc>(d_train, 5e5, step, 1.0, tau, b, alpha);
std::cout << std::setprecision(20) << std::fixed;
for (double coeff : coeffs) {
std::cout << coeff << std::endl;
}
std::cout << std::endl;
}
#endif
#ifdef CF_TEST_FIND_PARAMS
int main() {
std::cout << "!!#@#!" << std::endl;
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
size_t n_obj_train{};
size_t n_obj_test{};
size_t n_features{};
std::cin >> n_features;
std::cin >> n_obj_train;
Matrix d_train = readMatrix(n_obj_train, n_features);
NormalizationCoefficients ncoeffs = normalize(d_train);
std::cin >> n_obj_test;
Matrix d_test = readMatrix(n_obj_test, n_features);
for (auto &test_case : d_test) {
test_case.first.push_back(1);
}
std::vector<double> best_ws;
double best_step{0};
double best_error{1000};
double best_tau{0};
double best_b{0};
std::vector<double> taus = {0.3, 0.2, 1e-1, 1e-2, 1e-4, 1e-6, 1e-8, 1e-9};
size_t i = taus.size();
for (size_t j = 0; j < i; ++j) {
taus.push_back(1.0 - taus[j]);
}
for (double step : {1e-1, 1e-3, 1e-4, 1e-5, 1e-6}) {
for (double tau : taus) {
for (size_t b : {1, 25, 100, 1000}) {
//step = 1e-08;
//tau = 0.01;
//b = 100;
RegressionCoefficients coeffs = regression<SMAPEFunc>(d_train, 1e5, step, tau, 1.0, b, 1 - 1e03);
for (size_t i = 0; i < n_features; ++i) {
coeffs.back() -= ncoeffs[i].first / ncoeffs[i].second * coeffs[i];
if (ncoeffs[i].second != 0) {
coeffs[i] = coeffs[i] / ncoeffs[i].second;
}
}
for (size_t i = 0; i < n_features + 1; ++i) {
coeffs[i] *= ncoeffs.back().second;
}
coeffs.back() += ncoeffs.back().first;
double error{0};
for (auto &test_case : d_test) {
double pred = applyLinear(coeffs, test_case.first);
double e = SMAPE(pred, test_case.second);
error += e;
}
error = error / d_test.size() * 100;
if (best_error > error) {
best_error = std::min(best_error, error);
best_step = step;
best_tau = tau;
best_b = b;
best_ws = coeffs;
}
std::cout << step << " " << tau << " " << b << ": " << error << "%" << " " << step << std::endl;
}
}
}
std::cout << best_error << "%" << " " << best_step << " " << best_tau << " " << best_b << std::endl;
std::cout << best_ws << std::endl;
for (size_t i = 0; i < n_features; ++i) {
best_ws.back() -= ncoeffs[i].first / ncoeffs[i].second * best_ws[i];
best_ws[i] = best_ws[i] / ncoeffs[i].second;
}
for (size_t i = 0; i < n_features + 1; ++i) {
best_ws[i] *= ncoeffs.back().second;
}
best_ws.back() += ncoeffs.back().first;
std::cout << best_ws << std::endl;
return 0;
}
#endif
#ifdef CF_TEST_SOME_TESTS
int main() {
std::vector<double> c = {1, 2, 3, 4, 1};
std::vector<std::pair<double, double>> n = {{1.0, 1.5}, {2.0, 0.5}, {0.5, 3.0}, {0.0, 4.0}, {-1.0, 5.0}};
auto v = denormalize(c, n);
std::cout << v << std::endl;
}
#endif
#endif
| true |
6b78170b1ea08ca25adf60a81c8e2fb608b0bd40 | C++ | rvthak/OOP_Assignments_3rd_Semester | /2_forum++/thread.cpp | UTF-8 | 2,178 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include "namespace.h"
#include "thread.h"
#include "random.h"
using namespace std;
Thread::Thread(const string sb, const string cr, Date& dt)
:subject(sb), creator(cr), creation_date(dt){
postnum=0;
// basic setup done
// add some posts
Post tmp;
for(int i=0; i<Values::Number_Of_Posts; i++){
dt.random(); // get a random gate
tmp.set(dt, Post::getCurIDInc(), randomPhrase(), randomName(), randomText()); // set the post data
tmp.print(); // print the post data
list.push(tmp); // push it on the list
postnum++;
}
tmp.set(dt, -1, "", "", ""); // set id to -1 to disable destructor output
cout << endl << " ------------------------------------------------------------------------------------------------------ " << endl;
cout << "> Thread with subject: " << subject << " has just been created!" << endl;
cout << " ------------------------------------------------------------------------------------------------------ " << endl << endl << endl;
return;
}
Thread::~Thread(){
cout << " ------------------------------------------------------------------------------------------------------ " << endl;
cout << "> Thread with subject: " << subject << " is about to be destroyed" << endl;
cout << " ------------------------------------------------------------------------------------------------------ " << endl;
return;
}
void Thread::print()const{ // Print the thread
cout << subject << endl;
cout << creator << endl;
creation_date.print();
list.print();
return;
}
string Thread::getSubject()const{ return subject; } // Return the Thread's subject
int Thread::getPostCount()const{ return postnum; } // Return the Thread's subject
bool Thread::findAndPrint(int id)const{ // Search the Thread for a Post with id and print it if it exists
Post *ls;
for(int i=1; i<=postnum; i++){
ls=list.popN(i);
if(ls->getID()==id){
ls->print();
return 1;
}
}
return 0;
}
Post *Thread::getNpost(int n){ return list.popN(n); } // return pointer to list's nth post
PostList *Thread::getPostList(){ return &list; } // Return a pointer to thread's postlist
| true |
63b7765ec2e8b5ea5b7e11672316cdcef2e551e0 | C++ | Cmdeew/r-type | /serveur/inc/UMonsterOne.h | UTF-8 | 314 | 2.5625 | 3 | [] | no_license | #ifndef _MONSTERONE_H_
# define _MONSTERONE_H_
#include "../Object.h"
class MonsterOne : public Object
{
public:
MonsterOne(char id, char x, char y, char type = 11);
void move();
~MonsterOne();
char getType();
};
typedef MonsterOne *(*maker_monster)(char id, char x, char y);
#endif // _MONSTERONE_H_
| true |
aeeae321cbb4546f7f041866a3c36bb971a8c403 | C++ | TeodorDimitrovGH/SmartApplication | /HashTable.cpp | UTF-8 | 2,890 | 3.765625 | 4 | [] | no_license | #include "HashTable.h"
HashTable::HashTable()
{
for(int i = 0; i < tableSize; i++){
hashTable[i] = new item;
hashTable[i]->name = "empty";
hashTable[i]->drink = "empty";
hashTable[i]->next = NULL;
}
}
int HashTable::hashFunction(string key){
int hashValue = 0;
int index;
index = key.length();
for(int i = 0; i < key.length(); i++){
hashValue = hashValue + (int)key[i];
}
index = hashValue % tableSize;
return index;
}
void HashTable::addItem(string name, string drink){
int index = hashFunction(name);
cout<<"debugging here with index " << index << " and name " + name<< endl;
if(hashTable[index]->name == "empty"){
hashTable[index]->name = name;
hashTable[index]->drink = drink;
}
else{
item* ptr = hashTable[index];
item* n = new item;
n->name = name;
n->drink = drink;
n->next = NULL;
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = n;
}
}
int HashTable::numberOfItemsInABucket(int index){
int count = 0;
if(hashTable[index]->name == "empty"){
return count;
}
else{
item* ptr = hashTable[index];
while(ptr->next != NULL){
count++;
ptr = ptr->next;
}
}
return count;
}
void HashTable::printTable(){
int number;
for(int i = 0; i < tableSize; i++){
number = numberOfItemsInABucket(i);
cout<< "--------------------\n";
cout<< "index : ";
cout<< i << endl;
cout<<hashTable[i]->name << endl;
cout<<hashTable[i]->drink << endl;
cout<<"# of items in the bucket " << number <<endl;
cout<< "--------------------\n";
}
}
void HashTable::printItemsInIndex(int index){
item* ptr = hashTable[index];
if(ptr->name == "empty"){
cout<< "index = " << index << " is emptty."<<endl;
} else {
cout<< "index = " << index << " contains the following items\n";
while(ptr != NULL){
cout<< "----------------\n";
cout<< "Name: " << ptr->name << endl;
cout<< "Drink: " << ptr->drink << endl;
cout<< "----------------\n";
ptr = ptr->next;
}
}
}
void HashTable::findDrink(string name){
int index = hashFunction(name);
item* ptr = hashTable[index];
string drink;
bool isNameFounded = false;
while(ptr!= NULL){
if(ptr->name == name){
isNameFounded = true;
drink = ptr->drink;
}
ptr = ptr->next;
}
if(isNameFounded){
cout<<"FavouriteDrink: " << drink << endl;
} else {
cout << name << "'s info was not found in the table." << endl;
}
}
| true |
6477be6dd475af8bc889597989f2781206215f7e | C++ | erachelson/hanabi-ai | /simulator/hanabi_game.hpp | UTF-8 | 6,290 | 3.46875 | 3 | [] | no_license | #ifndef HANABI_GAME_HPP_
#define HANABI_GAME_HPP_
#include <array>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
#include <iostream>
enum color_t {red, green, blue, white, yellow, null};
struct card{
color_t color;
int value;
card() : color(null), value(0) {}
card(color_t c, int v) : color(c), value(v) {}
card(const card& c) : color(c.color), value(c.value) {}
//card& operator=(const card& c) { //TODO }
~card() {}
bool is_null() const {return color==null || value==0;}
std::string print() const {
std::stringstream ss;
switch(color) {
case null : ss << "N"; break;
case red : ss << "R"; break;
case green : ss << "G"; break;
case blue : ss << "B"; break;
case white : ss << "W"; break;
case yellow : ss << "Y"; break;
default : ss << "?";
}
ss << value;
return ss.str();
}
std::string print_color() const {
std::stringstream ss;
switch(color) {
case null : ss << "N"; break;
case red : ss << "R"; break;
case green : ss << "G"; break;
case blue : ss << "B"; break;
case white : ss << "W"; break;
case yellow : ss << "Y"; break;
default : ss << "?";
}
return ss.str();
}
};
class hanabi_game {
std::array<color_t,5> colors;
/* attributes */
/** Number of players */
int nb_players;
/** Number of cards per player */
int nb_cards_per_player;
/** Current state of the deck */
std::vector<card> deck;
/** Current hand for each player */
std::vector<std::vector<card> > players_hands;
/** Value of the biggest card in each color */
std::vector<int> stacks;
/** Current state of the discard stack */
std::vector<card> discard_stack;
/** Number of remaining blue tokens */
int blue_tokens;
/** Number of remaining red tokens */
int red_tokens;
/* methods */
public:
/** Constructor (default = 2 players) */
hanabi_game(int nb_players_=2);
/** Copy constructor */
hanabi_game(const hanabi_game& g);
/** Destructor */
virtual ~hanabi_game();
// /** Initialize game from observation */
// void init_from_observation(/* defausse, mains opposées, piles */);
/** Play a card from a player's hand */
int play(int player, int card_number);
/** Discard a card from a player's hand */
void discard(int player, int card_number);
/** Spend a blue token to give an information */
int give_info();
/** Computes the current score of the board's stacks */
int score() const;
/** Returns true if all players have empty hands */
bool all_hands_empty() const;
/** Returns true if one of the termination conditions for the game is met */
bool game_over() const;
/** Get number of players */
int get_number_of_players() const { return nb_players; }
/** Get number of cards per player (depends on the number of players) */
int get_nb_cards_per_player() const {return nb_cards_per_player; }
/** Gets a (const) reference on player p's hand */
const std::vector<card>& get_player_hand(int p) const {
if(p>=0 && p<=nb_players) { return players_hands.at(p); }
}
/** Gets a (const) reference on the board's stacks */
const std::vector<int>& get_stacks() const { return stacks; }
/** Gets a (const) reference on the discard stack */
const std::vector<card>& get_discard_stack() const {return discard_stack;}
/** Gets array of colors */
const std::array<color_t,5>& get_colors() const {return colors;}
/** Gets the number of remaining blue tokens */
int get_blue_tokens() const {return blue_tokens;}
/** Gets the number of remaining red tokens */
int get_red_tokens() const {return red_tokens;}
/** Gets a (const) reference on the deck */
const std::vector<card>& get_deck() const {return deck;}
};
hanabi_game::hanabi_game(int nb_players_)
: colors {red, green, blue, white, yellow},
nb_players(nb_players_),
nb_cards_per_player(5),
deck(),
players_hands(nb_players_),
stacks(5,0),
discard_stack(),
blue_tokens(8),
red_tokens(3) {
/* populate deck */
deck.reserve(50);
for(int col=0; col<colors.size(); ++col) {
for (int i=0; i<3; ++i) { deck.push_back(card(colors.at(col),1)); }
for (int i=0; i<2; ++i) { deck.push_back(card(colors.at(col),2)); }
for (int i=0; i<2; ++i) { deck.push_back(card(colors.at(col),3)); }
for (int i=0; i<2; ++i) { deck.push_back(card(colors.at(col),4)); }
for (int i=0; i<1; ++i) { deck.push_back(card(colors.at(col),5)); }
}
std::random_shuffle(deck.begin(), deck.end());
/* deal cards */
if(nb_players>=4) {nb_cards_per_player=4;}
players_hands = std::vector<std::vector<card> >(nb_players_, std::vector<card>(nb_cards_per_player));
for(int p=0; p<nb_players_; ++p) {
for(int c=0; c<nb_cards_per_player; ++c) {
players_hands.at(p).at(c) = deck.back();
deck.pop_back();
}
}
}
hanabi_game::~hanabi_game() {}
int hanabi_game::play(int player, int card_number) {
int val=1;
card& c=players_hands.at(player).at(card_number);
// check card is real
if(c.is_null()) {std::cout << "card is null" << std::endl;/* throw */}
// play (legal move)
if(stacks.at(c.color) == c.value-1) {++(stacks.at(c.color)); val=0;}
// play (illegal move)
else {
discard_stack.push_back(c);
--red_tokens;
val = 1;
}
// draw card (if possible)
if(deck.empty()) {
c.color=null;
c.value=0;
}
else {
c = deck.back();
deck.pop_back();
}
return val;
}
void hanabi_game::discard(int player, int card_number) {
card& c=players_hands.at(player).at(card_number);
// check card is real
if(c.is_null()) {/* throw */}
// discard card
discard_stack.push_back(c);
// draw card (if possible)
if(deck.empty()) {
c.color=null;
c.value=0;
}
else {
c = deck.back();
deck.pop_back();
}
// get token (if possible)
if(blue_tokens<8) { ++blue_tokens; }
}
int hanabi_game::give_info() {
if(blue_tokens > 0) {
--blue_tokens;
return 0;
}
else { return 1; }
}
int hanabi_game::score() const {
int sum=0;
for(int col=0; col<5; ++col) { sum += stacks.at(col); }
return sum;
}
bool hanabi_game::all_hands_empty() const {
bool all_hands_empty = true;
for(int p=0; p<nb_players; ++p) {
all_hands_empty = all_hands_empty && players_hands.at(p).empty();
}
return all_hands_empty;
}
bool hanabi_game::game_over() const {
if(red_tokens == 0) {return true;}
if(score()==25) {return true;}
if(all_hands_empty()) {return true;}
return false;
}
#endif
| true |
9b98ef4c47ade0253fd3c2502e54c87d8553fa92 | C++ | kazma89/Arduino | /Angie/boton/boton.ino | UTF-8 | 290 | 2.6875 | 3 | [] | no_license |
void setup() {
// put your setup code here, to run once:
pinMode(12,OUTPUT);
pinMode(2,INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
int estado = digitalRead(2);
if(estado==LOW){
digitalWrite(12,HIGH);
}
else{
digitalWrite(12,LOW);
}
}
| true |
2beafef2d4b7fbd4b395de40b0dd6cbec62f2a68 | C++ | yujunsen/qt_study | /qt_create_03_03_5_0/widget.cpp | UTF-8 | 1,715 | 3.28125 | 3 | [] | no_license | #include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
/*
* 先看两个Scroll Bar的属性:
* maximum属性用来设置最大值,minimum属性用来设置最小值;
* singleStep属性是每步的步长,默认是1,就是按下方向键后其数值增加或者减少1;
* pageStep是每页的步长,默认是10,就是按下PageUp或者PageDown按键后,其数值增加或者减少10;
* value与sliderPosition是当前值;tracking设置是否跟踪,默认为是,就是在拖动滑块时,每移动一个刻度,
* 都会发射valueChanged()信号,如果选择否,则只有拖动滑块释放时才发射该信号;
* orientation设置部件的方向,有水平和垂直两种选择;
* invertedAppearance属性设置滑块所在的位置,
* 比如默认滑块开始在最左端,选中这个属性后,滑块默认就会在最右端。
* invertedControls设置反向控制,比如默认是向上方向键是增大,向下方向键是减小,如果选中这个属性,那么控制就会正好反过来。
* 另外,为了使部件可以获得焦点,需要将focusPolicy设置为StrongFocus。
* 再来看两个Slider,它们有了自己的两个属性tickPosition和ticklnterval,前者用来设置显示刻度的位置,默认是不显示刻度;
* 后者是设置刻度的间隔。
* 而Dial有自己的属性wrapping,用来设置是否首尾相连,默认开始与结束是分开的;
* 属性notchTarget用来设置刻度之间的间隔;属性notchesVisible用来设置是否显示刻度。
*/
| true |
9dc335b5dd15e21f7516183b73e1e4d718052bbc | C++ | Fu-Qingchen/LearnCS | /LearnCPP/temp.cpp | UTF-8 | 1,323 | 3.53125 | 4 | [] | no_license | /*
* @lc app=leetcode.cn id=705 lang=cpp
*
* [705] 设计哈希集合
*/
// @lc code=start
#include<array>
using namespace std;
class MyHashSet {
public:
/** Initialize your data structure here. */
MyHashSet() { for (auto &i : datas) { i = -1; } }
void add(int key) { datas.at(search(key)) = key; }
void remove(int key) { datas.at(search(key)) = -1; }
/** Returns true if this set contains the specified element */
bool contains(int key) {
if (datas.at(search(key)) == -1) { return false; }
else { return true; }
}
private:
array<int, 10007> datas;
int length = 10007;
int hash(int key) { return ((key * 3 + 2 + length) % length); }
int search(int key) {
int hash_value = hash(key), flag = 1, mul = 1, index = hash_value;
while (datas.at(index) != -1) {
if(datas.at(index) == key) { return index; }
index = (hash_value + flag * mul) % length;
if (flag == -1) { ++mul; }
flag *= -1;
}
return index;
} // 查找失败返回下一个空位置的 index
};
/**
* Your MyHashSet object will be instantiated and called as such:
* MyHashSet* obj = new MyHashSet();
* obj->add(key);
* obj->remove(key);
* bool param_3 = obj->contains(key);
*/
// @lc code=end | true |
bad12dedcf3d3a6207008edc6a9662eb7af97ca3 | C++ | bitspill/node-multi-hashing | /axh.cc | UTF-8 | 2,027 | 2.578125 | 3 | [] | no_license | #include "axh.h"
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <vector>
#include "uint256.h"
#include "sha3/sph_shabal.h"
void axh_hash(const char* input, char* output, uint32_t len)
{
// Axiom Proof of Work Hash
// based on RandMemoHash https://bitslog.files.wordpress.com/2013/12/memohash-v0-3.pdf
/* RandMemoHash(s, R, N)
(1) Set M[0] := s
(2) For i := 1 to N − 1 do set M[i] := H(M[i − 1])
(3) For r := 1 to R do
(a) For b := 0 to N − 1 do
(i) p := (b − 1 + N) mod N
(ii) q :=AsInteger(M[p]) mod (N − 1)
(iii) j := (b + q) mod N
(iv) M[b] :=H(M[p] || M[j])
*/
int R = 2;
int N = 65536;
std::vector<uint256> M(N);
sph_shabal256_context ctx_shabal;
uint256 hash1;
sph_shabal256_init(&ctx_shabal);
sph_shabal256 (&ctx_shabal, input, len);
sph_shabal256_close(&ctx_shabal, static_cast<void*>(&hash1));
M[0] = hash1;
for(int i = 1; i < N; i++)
{
//HashShabal((unsigned char*)&M[i - 1], sizeof(M[i - 1]), (unsigned char*)&M[i]);
sph_shabal256_init(&ctx_shabal);
sph_shabal256 (&ctx_shabal, (unsigned char*)&M[i - 1], sizeof(M[i - 1]));
sph_shabal256_close(&ctx_shabal, static_cast<void*>((unsigned char*)&M[i]));
}
for(int r = 1; r < R; r ++)
{
for(int b = 0; b < N; b++)
{
int p = (b - 1 + N) % N;
int q = M[p].GetInt() % (N - 1);
int j = (b + q) % N;
std::vector<uint256> pj(2);
pj[0] = M[p];
pj[1] = M[j];
//HashShabal((unsigned char*)&pj[0], 2 * sizeof(pj[0]), (unsigned char*)&M[b]);
sph_shabal256_init(&ctx_shabal);
sph_shabal256 (&ctx_shabal, (unsigned char*)&pj[0], 2 * sizeof(pj[0]));
sph_shabal256_close(&ctx_shabal, static_cast<void*>((unsigned char*)&M[b]));
}
}
memcpy(output, M[N - 1].begin(), 32);
}
| true |
adf6f2bcc44981f017a286f1a78f872dd4741c8f | C++ | Sage-Bionetworks/bfrm | /src/bfrm21/util.cpp | UTF-8 | 6,684 | 2.71875 | 3 | [] | no_license | // util.cpp: implementation of the util class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "util.h"
#include <math.h>
#pragma warning(disable : 4996)
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
util::util()
{
}
util::~util()
{
}
string util::Trim(string s)
{
if (s.empty()) return s;
string ret;
for (int i = 0; i < (int)s.length(); i++) {
if (!isspace(s.at(i)) && !iscntrl(s.at(i)))
ret.append(s.substr(i,1));
}
return ret;
}
string util::ToLower(string str)
{
//new implementation for GNU
char *newstr = strdup(str.c_str());
int i = 0;
while (newstr[i] != '\0') {
newstr[i] = tolower(newstr[i]);
i++;
}
return newstr;
//return strlwr(strdup(str.c_str()));
}
int util::ToInt(string str)
{
return atoi(str.c_str());
}
double util::ToDouble(string str)
{
return atof(str.c_str());
}
string util::ToString(int value) {
char buffer[10];
sprintf(buffer, "%d", value);
string result(buffer);
return result;
cout << result.c_str() << endl;
}
string util::ToString(double value) {
char buffer[10];
sprintf(buffer, "%4.1f", value);
string result(buffer);
return result;
}
//Multinomial sampling from cells 0,1,....,k-1 with probabilities p0,p1,....,p(k-1)
//Result is (k-1) -vector of counts of #draws in cells 0,1,2,...,k-1
void util::RandSamples(int nMC, vector<double> P, int nSize, vector<int>& result)
{
result.clear();
//int nSize = P.size();
if ((nMC > 0) && (nSize > 0)) {
double dTotal = 0;
int i;
for (i =0 ; i < nSize; i++) {
dTotal += P[i];
}
for (i = 0; i < nSize; i++) {
P[i] = P[i] /dTotal;
}
vector<double> Q;
cumsum(P,Q);
double *pRand = new double[nMC];
cmRand(nMC, pRand);
vector<int> temp = vector<int>(nMC, 0);
for (i = 0; i < nSize; i++) {
for (int j = 0; j < nMC; j++) {
if (pRand[j] >= Q[i]) temp[j]++;
}
}
result = vector<int>(nSize, 0);
for (i = 0; i < nMC; i++) {
result[temp[i]]++;
}
delete [] pRand;
}
}
//change to integer result later ????
void util::cmRandPerm(const int nSize, double* pResult ) {
vector<int> index;
cmRand(nSize,pResult);
sort(nSize, pResult, index, 1);
for (int i = 0; i < nSize; i++) {
pResult[i] = index[i];
}
}
void util::SelectCVGroup(int Total, int GroupSize, vector<int>& subject, vector<int>& current, vector<int>& train, int GroupID)
{
int nSize = subject.size();
if (GroupSize == 0) { //no cross validation
current.clear();
train = subject;
subject.clear();
return;
}
int i;
double *pRandPerm = new double[nSize];
if (GroupID == 0) {
cmRandPerm(nSize, pRandPerm);
} else {
for (int i = 0; i < nSize; i++) {
pRandPerm[i] = i + 1;
}
}
list<int> TempCurrent;
list<int> TempSubject;
int nCVSize = (nSize > GroupSize) ? GroupSize : nSize;
for (i = 0; i < nSize; i++) {
if (i < nCVSize) {
TempCurrent.push_back(subject[(int)pRandPerm[i] - 1]);
} else {
TempSubject.push_back(subject[(int)pRandPerm[i] - 1]);
}
}
subject.clear();
list<int>::iterator it;
if (!TempSubject.empty()) {
TempSubject.sort();
for (it = TempSubject.begin(); it != TempSubject.end(); it++) {
subject.push_back(*it);
}
}
train.clear();
current.clear();
if (!TempCurrent.empty()) {
i = 1;
TempCurrent.sort();
while (!TempCurrent.empty()) {
int nCurrent = TempCurrent.front();
TempCurrent.pop_front();
current.push_back(nCurrent);
while (i < nCurrent) {
train.push_back(i++);
}
i++;
}
while (i <= Total) {
train.push_back(i++);
}
}
delete [] pRandPerm;
}
vector<int>& util::colon(vector<int>& result, int start, int end, int step /*= 1 */) {
result.clear();
for (int i = start; i <= end; i+= step) {
result.push_back(i);
} return result;
}
/*
vector<int>& util::sort2(int size, double* pData, vector<int>& index, int nDirection) {
index.clear();
double *pIndex = new double[size];
cmSort(size, pData, pIndex, nDirection);
for (int i = 0; i <size; i++) {
index.push_back((int)pIndex[i]);
}
return index;
delete [] pIndex;
}
*/
vector<double>& util::cumsum(vector<double>& source, vector<double>& result)
{
result.clear();
if (!source.empty()) {
int nSize = source.size();
result.push_back(source[0]);
for (int i = 1; i < nSize; i++) {
result.push_back(result[i - 1] + source[i]);
}
}
return result;
}
//nDirection = 1 :: ascending
vector<int>& util::sort(int size, double* pData, vector<int>& index, int nDirection/* = 1*/) {
index.clear();
int *pfrom = new int[size];
int *pto = new int[size];
double *pDataCopy = new double[size];
int i;
for (i = 0; i < size; i++) {
pfrom[i] = i;
}
memcpy(pDataCopy, pData, sizeof(double) * size);
memcpy(pto, pfrom, sizeof(int) * size);
int ascending = 1;
if (nDirection != 1) ascending = 0;
shuttlesort(pData, pfrom, pto, 0, size, ascending);
for (i = 0; i <size; i++) {
index.push_back(pto[i] + 1); //convert to one based as Matlab does
pData[i] = pDataCopy[pto[i]];
}
delete [] pfrom;
delete [] pto;
delete [] pDataCopy;
return index;
}
void util::shuttlesort(double* pData, int* from, int* to, int low, int high, int asceding) {
if (high - low < 2) return;
int middle = (low + high ) / 2;
shuttlesort(pData, to, from, low, middle, asceding);
shuttlesort(pData, to, from, middle, high, asceding);
int p = low;
int q = middle;
if (high - low >= 4 && compare(pData[from[middle-1]], pData[from[middle]], asceding) <= 0) {
for (int i = low; i < high; i++) {
to[i] = from[i];
}
return;
}
// A normal merge.
for (int i = low; i < high; i++) {
if (q >= high || (p < middle && compare(pData[from[p]], pData[from[q]], asceding) <= 0)) {
to[i] = from[p++];
}
else {
to[i] = from[q++];
}
}
}
int util::compare(double d1, double d2, int ascending) {
int result;
if (d1 < d2) {
result = -1;
} else if (d1 > d2) {
result = 1;
} else {
result = 0;
}
if (result != 0) {
return ascending ? result : -result;
}
return 0;
}
void util::cmPower2(int nSize, double *px, double* py, double* pResult) {
for (int i = 0; i < nSize; i++) {
pResult[i] = pow(px[i], py[i]);
}
}
| true |
6b1f972537571e61736e3cf8cbdfb73589cf27e9 | C++ | feng1008/leetcode | /Plus one.cpp | UTF-8 | 427 | 3.21875 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
vector<int> plusOne(vector<int> &digits){
int one=1;
vector<int> temp;
for(int i=digits.size()-1;i>=0;i--){
int t=digits[i]+one;
temp.push_back(t%10);
one=t/10;
}
if(one!=0){
temp.push_back(one);
}
for(int i=0;i<temp.size()/2;i++){
swap(temp[i],temp[temp.size()-1-i]);
}
return temp;
}
int main(){
system("pause");
return 0;
} | true |
30e87127b2b2b36076558d2ae045f25e225df2f9 | C++ | null32/sem3prog2017 | /p.cpp | UTF-8 | 1,390 | 2.59375 | 3 | [] | no_license | #include <cstdio>
#include <algorithm>
#include <functional>
#include <climits>
#include <memory.h>
#include <malloc.h>
typedef long long ll;
using namespace std;
void solve()
{
int sz;
scanf("%d", &sz);
sz++;
auto dims = new ll[sz];
for (int i = 0; i < sz; i++)
scanf("%lld", &dims[i]);
auto seqCost = new ll*[sz];
for (int i = 0; i < sz; i++)
{
seqCost[i] = new ll[sz];
memset(seqCost[i], 0, sz * sizeof(ll));
}
#ifdef DEBUG
printf("seqCost:\n");
for (int i = 0; i < sz; i++)
{
for (int j = 0; j < sz - 1; j++)
printf("%10lld ", seqCost[i][j]);
printf("%10lld\n", seqCost[i][sz - 1]);
}
#endif
for (int seqLen = 2; seqLen < sz; seqLen++)
{
for (int seqStart = 1; seqStart < sz - seqLen + 1; seqStart++)
{
int seqEnd = seqLen + seqStart - 1;
seqCost[seqStart][seqEnd] = LLONG_MAX;
for (int k = seqStart; k < seqEnd; k++)
{
ll cost = seqCost[seqStart][k] + seqCost[k + 1][seqEnd] +
dims[seqStart - 1] * dims[k] * dims[seqEnd];
if (cost < seqCost[seqStart][seqEnd])
seqCost[seqStart][seqEnd] = cost;
}
}
}
#ifdef DEBUG
printf("seqCost:\n");
for (int i = 0; i < sz; i++)
{
for (int j = 0; j < sz - 1; j++)
printf("%10lld ", seqCost[i][j]);
printf("%10lld\n", seqCost[i][sz - 1]);
}
#endif
printf("%lld\n", seqCost[1][sz - 1]);
}
int main()
{
int t = 0;
scanf("%d", &t);
while (t--)
solve();
}
| true |
ef5c14f4c3043c906e8907066b2e4007a3b4718c | C++ | samueldonner/CS32Project2 | /Map.cpp | UTF-8 | 7,174 | 3.671875 | 4 | [] | no_license |
#include <iostream>
#include "Map.h"
using namespace std;
void Map::dump() const
{
Node *p = head;
while(p != nullptr)
{
cerr << "Name: " << p->key << "| Value: " << p->value << endl;
p = p->next;
}
} //print Map
bool combine(const Map& m1, const Map& m2, Map& result)
{
KeyType keyM1;
ValueType valueM1;
KeyType keyM2;
ValueType valueM2;
bool passOrFail = true;
Map resultTemp; // create temp result variable
if( m2.size() == 0 )
{
result = m1;
return true;
}
else if( m1.size() == 0 )
{
result = m2;
return true;
}
for(int i = 0; i < m1.size(); i++)
{
for( int j = 0; j < m2.size(); j++ )
{
m1.get(i, keyM1, valueM1);
m2.get(j, keyM2, valueM2);
resultTemp.insert(keyM1, valueM1);
resultTemp.insert(keyM2, valueM2);
} //insert all keys from m1 and m2 (duplicates will not be inserted)
}
for(int i = 0; i < m1.size(); i++)
{
for( int j = 0; j < m2.size(); j++ )
{
m1.get(i, keyM1, valueM1);
m2.get(j, keyM2, valueM2);
if (keyM1==keyM2 && valueM1!=valueM2)
{
resultTemp.erase(keyM1);
passOrFail = false;
} // if m1 and m2 keys equal each other and the values dont equal each other
// remove the that key from the resultTemp Map and set passOrFail = to false
}
}
result = resultTemp;
return passOrFail;
}
void subtract(const Map& m1, const Map& m2, Map& result)
{
KeyType keyM1;
ValueType valueM1;
KeyType keyM2;
ValueType valueM2;
Map resultTemp;
for( int j = 0; j < m1.size(); j++ )
{
m1.get(j, keyM1, valueM1);
resultTemp.insert(keyM1, valueM1);
} // insert all m1 keys into resultTemp
for(int j = 0; j < m2.size(); j++)
{
for( int i = 0; i < resultTemp.size(); i++ )
{
resultTemp.get(i, keyM1, valueM1);
m2.get(j, keyM2, valueM2);
if (keyM1==keyM2)
{
resultTemp.erase(keyM1);
} // if keym1 and keym2 are equal erase keym1 from result map
} // go through m2 and result temp and compaure each function
}
result = resultTemp;
}
Map::Map()
{
head = nullptr;
} // construct map and set head = to nullptr
Map::Map(const Map& other)
{
head = nullptr;
Node *pOther = other.head;
while( pOther!=nullptr )
{
if(pOther->next==nullptr)
break;
pOther = pOther->next;
} // go to end of the other Map
while( pOther!=nullptr)
{
insert(pOther->key, pOther->value);
pOther = pOther->previous;
} // go backwards through other Map and insert
// keys in right order
}
Map& Map::operator=(const Map& otherSide)
{
Node *pOtherSide = otherSide.head;
Node *p=head;
while( p!=nullptr )
{
erase(p->key);
p = p->next;
} // erase this Map
while( pOtherSide!=nullptr )
{
if(pOtherSide->next==nullptr)
break;
pOtherSide = pOtherSide->next;
} // go to end of otherSide map
while( pOtherSide!=nullptr)
{
insert(pOtherSide->key, pOtherSide->value);
pOtherSide = pOtherSide->previous;
} // go backwards through other Map and insert
// keys in right order
return (*this);
}
Map::~Map()
{
if(head == nullptr)
{
return;
} // check if Map is empty
Node *p = head;
while(p!=nullptr)
{
head = p->next;
Node* killer = p;
p = p->next;
delete killer;
} //delete all Nodes in Map
}
bool Map::empty() const
{
if( head == nullptr)
return true;
else
return false;
} // check if Map is empty
int Map::size() const
{
Node *p = head;
int sizeCounter = 0;
while( p!=nullptr )
{
sizeCounter++;
p = p->next;
} // increase size Counter while cycling through Map
return sizeCounter;
}
bool Map::insert(const KeyType& key, const ValueType& value)
{
if( contains(key) )
return false; // dont insert if key is contained
Node *p = new Node;
p->value = value;
p->key = key;
p->next = head;
p->previous = nullptr; //linke up items
if(head != nullptr)
{
head->previous = p;
} // make sure Map is not empty
head = p;
return true;
}
bool Map::update(const KeyType& key, const ValueType& value)
{
Node *p = head;
while( p!=nullptr )
{
if( p->key == key )
{
p->value = value;
return true;
} // if Map key is key then Map value equals
p = p->next;
} // go through Map
return false;
}
bool Map::insertOrUpdate(const KeyType& key, const ValueType& value)
{
if(contains(key))
{
update(key, value);
} // if map contains update it
else
{
insert(key, value);
} // otherwise insert the key
return true;
}
bool Map::erase(const KeyType& key)
{
Node *p = head;
while( p!=nullptr )
{
if(p->key == key)
{ // if Map key equals key
Node *killer = p;
Node *temp = killer->next;
if( p->previous == nullptr )
{
if(temp!=nullptr)
{
temp->previous = nullptr;
} // if only node in a list
head = temp;
delete killer;
return true;
} // if first node in a list
p = killer->previous;
p->next = temp;
if(temp!=nullptr)
{
temp->previous = p;
} // if temp is empty
delete killer;
return true;
}
p = p->next;
} // go through Map
return false;
}
bool Map::contains(const KeyType& key) const
{
Node *p = head;
while( p!=nullptr )
{ // go thorugh Map
if( p->key == key )
{ // if key is in Map return true
return true;
}
p = p->next;
}
return false;
}
bool Map::get(const KeyType& key, ValueType& value) const
{
Node *p = head;
while( p!=nullptr )
{ // go through map
if( p->key == key )
{ // Map key == key
value = p->value; // set value = to Map value
return true; //return true if key is in Map
}
p = p->next;
}
return false;
}
bool Map::get(int i, KeyType& key, ValueType& value) const
{
Node *p = head;
int getIndex = 0;
while( p!=nullptr )
{ // go through Map
if( getIndex == i )
{ // if the index equals I then set key and value to the Map's
key = p->key;
value =p->value;
return true;
}
p = p->next;
getIndex++;
}
return false;
}
void Map::swap(Map& other)
{
Map tempMap; //create tempoarty map
tempMap = other;
other = *this;
*this = tempMap;
} //swamp maps
| true |
8764a0c7c0e27cdde70598060c308ef4e50f6d5e | C++ | MorleyDev/UnitTest11 | /UnitTest11/Will/Throw.hpp | UTF-8 | 2,720 | 3.359375 | 3 | [
"MIT"
] | permissive | #ifndef UNITTEST11_WILL_THROW_HPP
#define UNITTEST11_WILL_THROW_HPP
#include "../detail/BaseOperand.hpp"
#include <exception>
#include <string>
#include <sstream>
#include <functional>
namespace ut11
{
namespace Operands
{
template<typename Exception> struct WillThrow : public detail::BaseOperand < WillThrow<Exception> >
{
inline explicit WillThrow(std::string exceptionName = typeid(Exception).name())
: m_exceptionName(exceptionName),
m_errorMessage("Expected " + exceptionName + " to be thrown, but no exception was thrown")
{
}
inline std::string GetErrorMessage(std::function<void (void)>) const { return m_errorMessage; }
inline bool operator()(std::function<void (void)> function) const
{
try
{
function();
}
catch(const Exception&)
{
return true;
}
catch(const std::exception& ex)
{
std::stringstream stream;
stream << "Expected " << m_exceptionName << " to be thrown, but std::exception was thrown instead (what: " << ex.what() << ")";
m_errorMessage = stream.str();
}
catch(...)
{
std::stringstream stream;
stream << "Expected " << m_exceptionName << " to be thrown, but an unknown exception was thrown instead";
m_errorMessage = stream.str();
}
return false;
}
private:
std::string m_exceptionName;
mutable std::string m_errorMessage;
};
template<> struct WillThrow<std::exception> : public detail::BaseOperand<WillThrow<std::exception>>
{
inline explicit WillThrow()
: m_exceptionName("std::exception"),
m_errorMessage("Expected std::exception to be thrown, but no exception was thrown")
{
}
inline std::string GetErrorMessage(std::function<void (void)>) const { return m_errorMessage; }
inline bool operator()(std::function<void (void)> function) const
{
try
{
function();
}
catch(const std::exception&)
{
return true;
}
catch(...)
{
std::stringstream stream;
stream << "Expected " << m_exceptionName << " to be thrown, but an unknown exception was thrown instead";
m_errorMessage = stream.str();
}
return false;
}
private:
std::string m_exceptionName;
mutable std::string m_errorMessage;
};
}
namespace Will
{
/*! \brief Operand will return true if the passed predicate throws an exception of type Exception (or a child of type Exception), otherwise returns false */
template<typename Exception> inline Operands::WillThrow<Exception> Throw()
{
return Operands::WillThrow<Exception>();
}
}
}
#endif // UNITTEST11_WILL_THROW_HPP
| true |
bb10796751f258d1c37e6c05c7e9f91b1909f8bd | C++ | Sukora-Stas/Cpp-task-for-the-university-study | /poiskk.cpp | WINDOWS-1251 | 7,700 | 2.875 | 3 | [] | no_license | #include "poiskk.h"
#include "kursach.cpp"
#include <string>
//;_CRT_SECURE_NO_WARNINGS
void poiskk()
{
string value;
cout << "|______________________________________________________________________________|\n" << endl;
printf("%-1c%-1c%-4s%-74s%-1c", '\n', '|', "", " ?", '|');
printf("%-1c%-1c%-4s%-74s%-1c", '\n', '|', "", "", '|');
printf("%-1c%-1c%-4s%-74s%-1c", '\n', '|', "1.", " id", '|');
printf("%-1c%-1c%-4s%-74s%-1c", '\n', '|', "2.", " ", '|');
printf("%-1c%-1c%-4s%-74s%-1c", '\n', '|', "3.", " ", '|');
printf("%-1c%-1c%-4s%-74s%-1c", '\n', '|', "4.", " ", '|');
printf("%-1c%-1c%-4s%-74s%-1c%-1c", '\n', '|', "", "", '|', '\n');
int i;
cin >> i;
if (i == 1) // ID
{
int number = 0;
printf("%-1c%-1c%-4s%-74s%-1c", '\n', '|', "", " id", '|');
printf("%-1c%-1c%-4s%-74s%-1c%-1c", '\n', '|', "", " ", '|', '\n');
cin >> number;
int sum = 0;
proverka();
nst = 0;
TStudent std;
cout << "\n|-----------------------------------------------------------------|\n" << endl;
printf("%-3c%-7s%-18s%-10s%-10s%-6s%-12s%-1c%-1c", '|', "", "", "", "", ".", "", '|', '\n');
printf("%-3c%-7s%-18s%-10s%-10s%-6s%-12s%-1c%-1c", '|', "", "", "", "", "", " ", '|', '\n');
cout << "|-----------------------------------------------------------------|\n" << endl;
while (true)
{
int nwrt = fread(&std, sizeof(TStudent), 1, fl);
if (nwrt != 1) break;
stud[nst] = std;
int month = atoi(stud[nst].month);
int id = stud[nst].id;
string month2 = _switch(month);
if (number == id){
sum += (atoi(stud[nst].stoimost))*(atoi(stud[nst].day));
printf("%-3c%-5i%-20s%-10s%-10s%-6s%-3s%-9s%-1c%-1c", '|',
stud[nst].id,
stud[nst].FIO,
stud[nst].year,
month2.c_str(),
stud[nst].day,
stud[nst].stoimost,
".",
'|',
'\n');
printf("%-3c%-25s%-10s%-10s%-6s%-12s%-1c%-1c", '|', "", "", "", "", "", '|', '\n');
nst++;
}
}
cout << "|-----------------------------------------------------------------|\n" << endl;
printf("%-3c%-25s%-10s%-10s%-6s%-4i%-8s%-1c%-1c", '|', "", "", "", ":", sum, ".", '|', '\n');
cout << "|-----------------------------------------------------------------|\n" << endl;
fclose(fl);
}
if (i == 2) //
{
string name;
printf("%-1c%-1c%-4s%-74s%-1c", '\n', '|', "", " ", '|');
printf("%-1c%-1c%-4s%-74s%-1c%-1c", '\n', '|', "", " ", '|', '\n');
//getline(cin,name);
cin >> name;
int sum = 0;
proverka();
nst = 0;
TStudent std;
cout << "\n|-----------------------------------------------------------------|\n" << endl;
printf("%-3c%-7s%-18s%-10s%-10s%-6s%-12s%-1c%-1c", '|', "", "", "", "", ".", "", '|', '\n');
printf("%-3c%-7s%-18s%-10s%-10s%-6s%-12s%-1c%-1c", '|', "", "", "", "", "", " ", '|', '\n');
cout << "|-----------------------------------------------------------------|\n" << endl;
while (true)
{
int nwrt = fread(&std, sizeof(TStudent), 1, fl);
if (nwrt != 1) break;
stud[nst] = std;
int month = atoi(stud[nst].month);
string fio = stud[nst].FIO;
string month2 = _switch(month);
if (name == fio){
sum += (atoi(stud[nst].stoimost))*(atoi(stud[nst].day));
printf("%-3c%-5i%-20s%-10s%-10s%-6s%-3s%-9s%-1c%-1c", '|',
stud[nst].id,
stud[nst].FIO,
stud[nst].year,
month2.c_str(),
stud[nst].day,
stud[nst].stoimost,
".",
'|',
'\n');
printf("%-3c%-25s%-10s%-10s%-6s%-12s%-1c%-1c", '|', "", "", "", "", "", '|', '\n');
nst++;
}
}
cout << "|-----------------------------------------------------------------|\n" << endl;
printf("%-3c%-25s%-10s%-10s%-6s%-4i%-8s%-1c%-1c", '|', "", "", "", ":", sum, ".", '|', '\n');
cout << "|-----------------------------------------------------------------|\n" << endl;
fclose(fl);
}
if (i == 3) //
{
int year = 0;
printf("%-1c%-1c%-4s%-74s%-1c", '\n', '|', "", " ", '|');
printf("%-1c%-1c%-4s%-74s%-1c%-1c", '\n', '|', "", " ", '|', '\n');
cin >> year;
int sum = 0;
proverka();
nst = 0;
TStudent std;
cout << "\n|-----------------------------------------------------------------|\n" << endl;
printf("%-3c%-7s%-18s%-10s%-10s%-6s%-12s%-1c%-1c", '|', "", "", "", "", ".", "", '|', '\n');
printf("%-3c%-7s%-18s%-10s%-10s%-6s%-12s%-1c%-1c", '|', "", "", "", "", "", " ", '|', '\n');
cout << "|-----------------------------------------------------------------|\n" << endl;
while (true)
{
int nwrt = fread(&std, sizeof(TStudent), 1, fl);
if (nwrt != 1) break;
stud[nst] = std;
int month = atoi(stud[nst].month);
int yea = atoi(stud[nst].year);
string month2 = _switch(month);
if (year == yea){
sum += (atoi(stud[nst].stoimost))*(atoi(stud[nst].day));
printf("%-3c%-5i%-20s%-10s%-10s%-6s%-3s%-9s%-1c%-1c", '|',
stud[nst].id,
stud[nst].FIO,
stud[nst].year,
month2.c_str(),
stud[nst].day,
stud[nst].stoimost,
".",
'|',
'\n');
printf("%-3c%-25s%-10s%-10s%-6s%-12s%-1c%-1c", '|', "", "", "", "", "", '|', '\n');
nst++;
}
}
cout << "|-----------------------------------------------------------------|\n" << endl;
printf("%-3c%-25s%-10s%-10s%-6s%-4i%-8s%-1c%-1c", '|', "", "", "", ":", sum, ".", '|', '\n');
cout << "|-----------------------------------------------------------------|\n" << endl;
fclose(fl);
}
if (i == 4) //
{
int monthe = 0;
printf("%-1c%-1c%-4s%-74s%-1c", '\n', '|', "", " ", '|');
printf("%-1c%-1c%-4s%-74s%-1c%-1c", '\n', '|', "", " ", '|', '\n');
cin >> monthe;
int sum = 0;
proverka();
nst = 0;
TStudent std;
cout << "\n|-----------------------------------------------------------------|\n" << endl;
printf("%-3c%-7s%-18s%-10s%-10s%-6s%-12s%-1c%-1c", '|', "", "", "", "", ".", "", '|', '\n');
printf("%-3c%-7s%-18s%-10s%-10s%-6s%-12s%-1c%-1c", '|', "", "", "", "", "", " ", '|', '\n');
cout << "|-----------------------------------------------------------------|\n" << endl;
while (true)
{
int nwrt = fread(&std, sizeof(TStudent), 1, fl);
if (nwrt != 1) break;
stud[nst] = std;
int month = atoi(stud[nst].month);
string month2 = _switch(month);
if (monthe == month){
sum += (atoi(stud[nst].stoimost))*(atoi(stud[nst].day));
printf("%-3c%-5i%-20s%-10s%-10s%-6s%-3s%-9s%-1c%-1c", '|',
stud[nst].id,
stud[nst].FIO,
stud[nst].year,
month2.c_str(),
stud[nst].day,
stud[nst].stoimost,
".",
'|',
'\n');
printf("%-3c%-25s%-10s%-10s%-6s%-12s%-1c%-1c", '|', "", "", "", "", "", '|', '\n');
nst++;
}
}
cout << "|-----------------------------------------------------------------|\n" << endl;
printf("%-3c%-25s%-10s%-10s%-6s%-4i%-8s%-1c%-1c", '|', "", "", "", ":", sum, ".", '|', '\n');
cout << "|-----------------------------------------------------------------|\n" << endl;
fclose(fl);
}
}
| true |
2fbbe78a8c68748647fdc410c9370fd6b6ff333f | C++ | MrOctopus/misc-projects | /c++/vtablefun.cpp | UTF-8 | 1,322 | 3.71875 | 4 | [] | no_license | /*-------------------------------------------------------
@author NeverLost
Virtual table fun.
Let's call VirtualTableHack::Print() directly from the vtable.
---------------------------------------------------------*/
#include <iostream>
#include <cstdint>
using std::cout;
using std::endl;
using std::uintptr_t;
class VirtualTableHack
{
public:
VirtualTableHack(int ctor_param) { param = ctor_param; }
virtual void Print() { cout << "Object value: " << param << endl; }
private:
int param;
};
int main()
{
VirtualTableHack obj(1);
// Print object value, result = 1
obj.Print();
// Virtual table pointer
uintptr_t* vPointer = (uintptr_t*) &obj;
vPointer = (uintptr_t*) *vPointer;
// Call first function located in vTable, result = ??? undefined
((void (*)()) *vPointer)();
// Why was the result undefined? The cast should work for normal functions.
// True, but in this case we are dealing with a function that is associated with an object.
// C++ hides this logic, but for every non-static function we have to pass a "this" variable.
// This, so we can actually set the object's variables.
// Call first function located in vTable and send obj as first param, result = 1
((void (*)(VirtualTableHack)) *vPointer)(obj);
return 0;
} | true |
d5decd96351998618180c3b8bf5daacb6b3b22fd | C++ | proxict/cpplibcrypto | /lib/include/cpplibcrypto/cipher/CbcMode.h | UTF-8 | 2,023 | 2.8125 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef CPPLIBCRYPTO_CIPHER_CBCMODE_H_
#define CPPLIBCRYPTO_CIPHER_CBCMODE_H_
#include "cpplibcrypto/buffer/BufferSlice.h"
#include "cpplibcrypto/buffer/DynamicBuffer.h"
#include "cpplibcrypto/cipher/CbcDecrypt.h"
#include "cpplibcrypto/cipher/CbcEncrypt.h"
#include "cpplibcrypto/common/Key.h"
namespace crypto {
/// Convenience class for constructing block cipher encryptors/decryptors
///
/// For more details, see \ref CbcEncrypt and \ref CbcDecrypt
template <typename CipherT>
class CbcMode final {
public:
using CipherType = CipherT;
CbcMode() = default;
struct Encryption {
using CipherType = CipherT;
template <typename TKey>
Encryption(const TKey& key, const InitializationVector& iv)
: mCipher(key)
, mEncryptor(mCipher, iv) {}
template <typename TBuffer>
Size update(BufferSlice<const Byte> input, TBuffer& output) {
return mEncryptor.update(input, output);
}
template <typename TBuffer>
void finalize(TBuffer& output, const Padding& padder) {
mEncryptor.finalize(output, padder);
}
Size getBlockSize() const { return mCipher.getBlockSize(); }
private:
CipherT mCipher;
CbcEncrypt mEncryptor;
};
struct Decryption {
using CipherType = CipherT;
template <typename TKey>
Decryption(const TKey& key, const InitializationVector& iv)
: mCipher(key)
, mDecryptor(mCipher, iv) {}
template <typename TBuffer>
Size update(BufferSlice<const Byte> input, TBuffer& output) {
return mDecryptor.update(input, output);
}
template <typename TBuffer>
void finalize(TBuffer& output, const Padding& padder) {
mDecryptor.finalize(output, padder);
}
Size getBlockSize() const { return mCipher.getBlockSize(); }
private:
CipherT mCipher;
CbcDecrypt mDecryptor;
};
};
} // namespace crypto
#endif
| true |
6789bd0f85ddcf557227f9236299aac4dc47bfe5 | C++ | DivanshiGupta/DataStructuresAndAlgorithms | /strongly_connected_components.cpp | UTF-8 | 2,622 | 2.546875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int v, E, cur;
vector<vector<int>> g;
vector<vector<int>> h;
int no;
stack<int> s;
stack<int> s1;
vector<int> vis(300000, 0);
vector<int> ans(300000, 0);
int count1;
int dfs()
{
int p = cur;
if (no == 0)
{
for (int j = 0; j < g[cur].size(); j++)
{
int k = g[cur][j];
if (vis[k] == 0)
{
s.push(cur);
cur = k;
vis[k] = 1;
dfs();
}
}
}
else if (no == 1)
{
for (int j = 0; j < h[cur].size(); j++)
{
int k = h[cur][j];
if (vis[k] == 0)
{
s.push(cur);
cur = k;
vis[k] = 1;
count1++;
ans[cur] = 1;
dfs();
}
}
}
if (cur == p)
{
if (s.empty() == 1)
{
return 0;
}
else
{
if (no == 1)
cout << cur << " ";
vis[cur] = 2;
s1.push(cur);
int t = s.top();
s.pop();
cur = t;
dfs();
}
}
}
int call_dfs()
{
for (int i = 1; i <= v; i++)
{
if (vis[i] == 0)
{
//cout << "for" << i << " ";
cur = i;
vis[i] = 1;
no = 0;
dfs();
//cout << i << " ";
vis[cur] = 2;
s1.push(cur);
}
}
}
int call_scp()
{
while (!s.empty())
{
s.pop();
}
for (int i = 1; i <= v; i++)
{
vis[i] = 0;
}
while (!s1.empty())
{
int r = s1.top();
if (vis[r] == 0)
{
count1 = 0;
//cout << "for" << r <<" ";
cur = r;
vis[r] = 1;
count1++;
ans[cur] = 1;
no = 1;
dfs();
cout << r << " ";
if (count1 == 1)
{
ans[cur] = 0;
}
vis[cur] = 2;
}
s1.pop();
}
}
int main()
{
cin >> v >> E;
g.resize(v + 1);
h.resize(v + 1);
vis.resize(v + 1);
ans.resize(v + 1);
for (int i = 0; i < E; i++)
{
int v1, v2;
cin >> v1 >> v2;
g[v1].push_back(v2);
h[v2].push_back(v1);
}
call_dfs();
//cout << endl ;
//cout << s1.top();
//cout << endl;
call_scp();
cout << endl;
// for(int i=1;i<=v;i++)
// {
// cout << ans[i] << " ";
// }
// cout << endl;
}
| true |
956f86ba27f1bd36c9153a4bee6b755d4241dbb3 | C++ | albertomila/continous-formation | /MoreIdioms/MoreIdioms/samples/MI27_EraseRemove.h | UTF-8 | 967 | 2.9375 | 3 | [] | no_license | #pragma once
#include "stdafx.h"
namespace nsEraseRemove
{
class CTest
{
public:
CTest()
: m_x( 10 )
{
}
~CTest()
{
m_x = 0;
}
int GetValue() const{ return m_x; }
private:
int m_x;
};
bool RemovePredicate ( const CTest& value )
{
return value.GetValue() == 10;
}
}
BEGIN_TEST(EraseRemove)
using namespace nsEraseRemove;
std::vector<CTest> list;
list.push_back( CTest() );
list.push_back( CTest() );
list.push_back( CTest() );
list.push_back( CTest() );
list.push_back( CTest() );
list.push_back( CTest() );
list.push_back( CTest() );
list.push_back( CTest() );
list.push_back( CTest() );
list.push_back( CTest() );
list.push_back( CTest() );
list.push_back( CTest() );
list.push_back( CTest() );
list.push_back( CTest() );
list.erase( std::remove_if( list.begin(), list.end(), RemovePredicate ) //returns iterator
, list.end() );
END_TEST() | true |
997679597ab275162741e42919af24fe1ec71cc1 | C++ | PulakMajumdar81/Daily-DSA-prep | /topKFreqWords.cpp | UTF-8 | 1,698 | 3.296875 | 3 | [] | no_license | #include <bits/stdc++.h>
#include <stdio.h>
using namespace std;
class Solution
{
public:
struct Compare
{
bool operator()(pair<int, string> &p1, pair<int, string> &p2)
{
int p1Count = p1.first;
string p1Word = p1.second;
int p2Count = p2.first;
string p2Word = p2.second;
if (p1Count < p2Count)
{
return true;
}
else if (p1Count == p2Count)
{
return p1Word > p2Word;
}
else
return false;
return false;
}
};
vector<string> topKFrequent(vector<string> &words, int k)
{
unordered_map<string, int> hashmap;
for (auto word : words)
{
hashmap[word]++;
}
priority_queue<pair<int, string>, vector<pair<int,string>>, Compare > maxHeap;
for (auto it = hashmap.begin(); it != hashmap.end(); it++)
{
maxHeap.push({it->second, it->first});
}
vector<string> out;
int prevCount = -1;
while (!maxHeap.empty() and k--)
{
auto top = maxHeap.top();
int currCount = top.first;
string currWord = top.second;
out.push_back(currWord);
maxHeap.pop();
}
return out;
}
};
int main()
{
vector<string> arr{"i", "love", "leetcode", "i", "love", "coding"};
int k = 2;
Solution ob;
auto out = ob.topKFrequent(arr, k);
for (auto x : out)
{
cout << x << endl;
}
return 1;
} | true |
4322a24ee9adad416f9cccd8e6d53d7637bed11c | C++ | hsmtknj/coding-interview | /5. Miscellaneous Coding Interview Questions/q5-1.cpp | UTF-8 | 1,409 | 3.9375 | 4 | [
"MIT"
] | permissive | /**
* [Question]
* - Bucket Sort (Bin sort) のアルゴリズムを実装するにはどうすればよいですか?
*
* [Solution]
* - バケット配列を用意する
* - データを対応するバケットに入れる
* - バケットから順に取り出す
*
* <計算量>
* - O(n + A)
* <特徴>
* - 小さい値までのソートならめちゃめちゃ速い
* - 重複に対応していない
*
* [Reference]
* - <https://www.codereading.com/algo_and_ds/algo/bucket_sort.html>
* - <https://qiita.com/drken/items/44c60118ab3703f7727f#8-1-%E8%A8%88%E6%95%B0%E3%82%BD%E3%83%BC%E3%83%88>
*/
#include <iostream>
#include <vector>
// ソートで対象の数字は 100000 を最大とする
const int N_MAX = 100000;
void bucket_sort(std::vector<int> &v)
{
// バケツを用意
std::vector<bool> bucket(N_MAX+1, false);
// バケツに入れる
for (int i = 0; i < v.size(); i++)
bucket[v[i]] = true;
// バケツから順に取り出す
std::vector<int> sorted;
for (int i = 0; i < bucket.size(); i++)
{
if (bucket[i] == true)
sorted.push_back(i);
}
v = sorted;
}
int main()
{
/* INPUT */
std::vector<int> v = {30, 88, 100, 1, 25, 20};
/* SOLVE */
bucket_sort(v);
for (int i = 0; i < v.size(); i++)
std::cout << v[i] << " ";
std::cout << std::endl;
return 0;
} | true |
60ba086dca27cce34cba0db0219c91bba7e5b6f9 | C++ | git-vivek29/Data-Structure-And-Algorithm | /SourceCode/BitManipulation/Power2.cpp | UTF-8 | 230 | 3.09375 | 3 | [
"MIT"
] | permissive | /*
Problem Statement: Write a program to check if a given number is power of 2
*/
#include<iostream>
using namespace std;
bool isPower2(int n)
{
return (n && !(n & n-1));
}
int main()
{
cout<<isPower2(128);
return 0;
} | true |
ae74b891d3fe8519d1c4f8c73a7d144956be9e82 | C++ | kch1285/Algorithms | /SWEA/D3/SWEA10200.cpp | UTF-8 | 360 | 2.578125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(int argc, char** argv)
{
int test_case;
int T, n, a, b;
cin>>T;
for(test_case = 1; test_case <= T; ++test_case)
{
cin >> n >> a >> b;
cout << "#" << test_case << ' ' << min(a, b) << ' ';
if(a + b - n > 0) cout << a + b - n << '\n';
else cout << 0 << '\n';
}
return 0;
} | true |
80c670060b5425e94f75b7e30fad106c5c683fbe | C++ | SeanStarkey/torrent-file-reader | /Element.h | UTF-8 | 553 | 2.609375 | 3 | [] | no_license |
#ifndef ELEMENT_H
#define ELEMENT_H
#include <boost/shared_ptr.hpp>
namespace Bencoding
{
enum Type
{
DICTIONARY,
LIST,
INTEGER,
STRING
};
class Element
{
public:
static boost::shared_ptr<Element> factory(const char* const buffer, unsigned& offset);
virtual Type getType() = 0;
protected:
int intValue(const char* const buffer, unsigned& offset);
};
}
std::ostream& operator<< (std::ostream& aStream, boost::shared_ptr<Bencoding::Element> element);
#endif
| true |
53bc1a0362721c7ecff2ff935f97f90be8bb5cca | C++ | gbyy422990/Leetcode_cpp | /code/1.Two Sum.cpp | UTF-8 | 1,380 | 3.65625 | 4 | [] | no_license | /* 使用一个HashMap,来建立数字和其坐标位置之间的映射,我们都知道HashMap是常数级的查找效率,这样,我们在遍历数组的时候,
用target减去遍历到的数字,就是另一个需要的数字了 */
# 方法一
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
# 定义一个哈希表
unordered_map<int, int> indies;
# 遍历一下整个数组,然后存到哈希表里,哈希表的key为nums, value为其索引
for (int i=0;i<nums.size();i++){
indies[nums[i]] = i;
}
for (int i=0;i<nums.size();i++){
int res = target - nums[i];
# 判断一下res是否存在在哈希表里面 and 这个res在indies里面不存在
if (indies.count(res) && indies[res] != i){
# 返回其索引
return {i, indies[res]};
}
}
return {};
}
};
# 方法二
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int res = 0, left = -1, n = s.size();
unordered_map<int, int> m;
for (int i = 0; i < n; ++i) {
if (m.count(s[i]) && m[s[i]] > left) {
left = m[s[i]];
}
m[s[i]] = i;
res = max(res, i - left);
}
return res;
}
};
| true |
71024a0bf98fe1819f25cf71925955564f133401 | C++ | WebAssembly/binaryen | /src/ir/match.h | UTF-8 | 33,461 | 2.984375 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2020 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// match.h - Provides an easily extensible layered API for matching expression
// patterns and extracting their components. The low-level API provides modular
// building blocks for creating matchers for any data type and the high-level
// API provides a succinct and flexible interface for matching expressions and
// extracting useful information from them.
#ifndef wasm_ir_match_h
#define wasm_ir_match_h
#include "ir/abstract.h"
#include "wasm.h"
namespace wasm::Match {
// The available matchers are:
//
// i32, i64, f32, f64
//
// Match constants of the corresponding type. Takes zero or one argument. The
// argument can be a specific value to match or it can be a pointer to a
// value, Literal, or Const* at which to store the matched entity.
//
// bval, ival, fval
//
// Match any boolean, any integer or any floating point constant. Takes
// neither, either, or both of two possible arguments: first, a pointer to a
// value, Literal, or Const* at which to store the matched entity and second,
// a specific value to match.
//
// constant
//
// Matches any numeric Const expression. Takes neither, either, or both of
// two possible arguments: first, a pointer to either Literal or Const* at
// which to store the matched entity and second, a specific value (given as
// an int32_t) to match..
//
// any
//
// Matches any Expression. Optionally takes as an argument a pointer to
// Expression* at which to store the matched Expression*.
//
// unary
//
// Matches Unary expressions. Takes an optional pointer to Unary* at which to
// store the matched Unary*, followed by either a UnaryOp or an Abstract::Op
// describing which unary expressions to match, followed by a matcher to
// apply to the unary expression's operand.
//
// binary
//
// Matches Binary expressions. Takes an optional pointer to Binary* at which
// to store the matched Binary*, followed by either a BinaryOp or an
// Abstract::Op describing which binary expresions to match, followed by
// matchers to apply to the binary expression's left and right operands.
//
// select
//
// Matches Select expressions. Takes an optional pointer to Select* at which
// to store the matched Select*, followed by matchers to apply to the ifTrue,
// ifFalse, and condition operands.
//
//
// How to create new matchers:
//
// Lets add a matcher for an expression type that is declared in wasm.h:
//
// class Frozzle : public SpecificExpression<Expression::FrozzleId> {
// public:
// Expression* foo;
// Expression* bar;
// Expression* baz;
// };
//
// This expression is very simple; in order to match it, all we need to do is
// apply other matchers to its subexpressions. The matcher infrastructure will
// handle this automatically once we tell it how to access the subexpressions.
// To tell the matcher infrastructure how many subexpressions there are we need
// to specialize `NumComponents`.
//
// template<> struct NumComponents<Frozzle*> {
// static constexpr size_t value = 3;
// };
//
// And to tell the matcher infrastructure how to access those three
// subexpressions, we need to specialize `GetComponent` three times.
//
// template<> struct GetComponent<Frozzle*, 0> {
// Expression* operator()(Frozzle* curr) { return curr->foo; }
// };
// template<> struct GetComponent<Frozzle*, 1> {
// Expression* operator()(Frozzle* curr) { return curr->bar; }
// };
// template<> struct GetComponent<Frozzle*, 2> {
// Expression* operator()(Frozzle* curr) { return curr->baz; }
// };
//
// For simple expressions, that's all we need to do to get a fully functional
// matcher that we can construct and use like this, where S1, S2, and S3 are
// the types of the submatchers to use and s1, s2, and s3 are instances of
// those types:
//
// Frozzle* extracted;
// auto matcher = Matcher<Frozzle*, S1, S2, S3>(&extracted, {}, s1, s2, s3);
// if (matches(expr, matcher)) {
// // `extracted` set to `expr` here
// }
//
// It's annoying to have to write out the types S1, S2, and S3 and we don't get
// class template argument deduction (CTAD) until C++17, so it's useful to
// create a wrapper function so can take advantage of function template
// argument deduction. We can also take this opportunity to make the interface
// more compact.
//
// template<class S1, class S2, class S3>
// inline decltype(auto) frozzle(Frozzle** binder,
// S1&& s1, S2&& s2, S3&& s3) {
// return Matcher<Frozzle*, S1, S2, S3>(binder, {}, s1, s2, s3);
// }
// template<class S1, class S2, class S3>
// inline decltype(auto) frozzle(S1&& s1, S2&& s2, S3&& s3) {
// return Matcher<Frozzle*, S1, S2, S3>(nullptr, {}, s1, s2, s3);
// }
//
// Notice that we make the interface more compact by providing overloads with
// and without the binder. Here is the final matcher usage:
//
// Frozzle* extracted;
// if (matches(expr, frozzle(&extracted, s1, s2, s3))) {
// // `extracted` set to `expr` here
// }
//
// Some matchers are more complicated, though, because they need to do
// something besides just applying submatchers to the components of an
// expression. These matchers require slightly more work.
//
//
// Complex matchers:
//
// Lets add a matcher that will match calls to functions whose names start with
// certain prefixes. Since this is not a normal matcher for Call expressions,
// we can't identify it by the Call* type. Instead, we have to create a new
// identifier type, called a "Kind" for it.
//
// struct PrefixCallKind {};
//
// Next, since we're not in the common case of using a specific expression
// pointer as our kind, we have to tell the matcher infrastructure what type of
// thing this matcher matches. Since we want this matcher to be able to match
// any given prefix, we also need the matcher to contain the given prefix as
// state, and we need to tell the matcher infrastructure what type that state
// is as well. To specify these types, we need to specialize
// `KindTypeRegistry` for `PrefixCallKind`.
//
// template<> struct KindTypeRegistry<PrefixCallKind> {
// using matched_t = Call*;
// using data_t = Name;
// };
//
// Note that because `matched_t` is set to a specific expression pointer, this
// matcher will automatically be able to be applied to any `Expression*`, not
// just `Call*`. If `matched_t` were not a specific expression pointer, this
// matcher would only be able to be applied to types compatible with
// `matched_t`. Also note that if a matcher does not need to store any state,
// its `data_t` should be set to `unused_t`.
//
// Now we need to tell the matcher infrastructure what custom logic to apply
// for this matcher. We do this by specializing `MatchSelf`.
//
// template<> struct MatchSelf<PrefixCallKind> {
// bool operator()(Call* curr, Name prefix) {
// return curr->name.startsWith(prefix);
// }
// };
//
// Note that the first parameter to `MatchSelf<Kind>::operator()` will be that
// kind's `matched_t` and the second parameter will be that kind's `data_t`,
// which may be `unused_t`. (TODO: detect if `data_t` is `unused_t` and don't
// expose it in the Matcher interface if so.)
//
// After this, everything is the same as in the simple matcher case. This
// particular matcher doesn't need to recurse into any subcomponents, so we can
// skip straight to creating the wrapper function.
//
// decltype(auto) prefixCall(Call** binder, Name prefix) {
// return Matcher<PrefixCallKind>(binder, prefix);
// }
//
// Now we can use the new matcher:
//
// Call* call;
// if (matches(expr, prefixCall(&call, "__foo"))) {
// // `call` set to `expr` here
// }
//
// The main entrypoint for matching. If the match succeeds, all variables bound
// in the matcher will be set to their corresponding matched values. Otherwise,
// the value of the bound variables is unspecified and may have changed.
template<class Matcher> inline bool matches(Expression* expr, Matcher matcher) {
return matcher.matches(expr);
}
namespace Internal {
struct unused_t {};
// Each matcher has a `Kind`, which controls how candidate values are
// destructured and inspected. For most matchers, `Kind` is a pointer to the
// matched subtype of Expression, but when there are multiple matchers for the
// same kind of expression, they are disambiguated by having different `Kind`s.
// In this case, or if the matcher matches something besides a pointer to a
// subtype of Expression, or if the matcher requires additional state, the
// matched type and the type of additional state must be associated with the
// `Kind` via a specialization of `KindTypeRegistry`.
template<class Kind> struct KindTypeRegistry {
// The matched type
using matched_t = void;
// The type of additional state needed to perform a match. Can be set to
// `unused_t` if it's not needed.
using data_t = unused_t;
};
// Given a `Kind`, produce the type `matched_t` that is matched by that Kind and
// the type `candidate_t` that is the type of the parameter of the `matches`
// method. These types are only different if `matched_t` is a pointer to a
// subtype of Expression, in which case `candidate_t` is Expression*.
template<class Kind> struct MatchTypes {
using matched_t = typename std::conditional_t<
std::is_base_of<Expression, std::remove_pointer_t<Kind>>::value,
Kind,
typename KindTypeRegistry<Kind>::matched_t>;
static constexpr bool isExpr =
std::is_base_of<Expression, std::remove_pointer_t<matched_t>>::value;
using candidate_t =
typename std::conditional_t<isExpr, Expression*, matched_t>;
};
template<class Kind> using matched_t = typename MatchTypes<Kind>::matched_t;
template<class Kind> using candidate_t = typename MatchTypes<Kind>::candidate_t;
template<class Kind> using data_t = typename KindTypeRegistry<Kind>::data_t;
// Defined if the matched type is a specific expression pointer, so can be
// `dynCast`ed to from Expression*.
template<class Kind>
using enable_if_castable_t = typename std::enable_if<
std::is_base_of<Expression, std::remove_pointer_t<matched_t<Kind>>>::value &&
!std::is_same<Expression*, matched_t<Kind>>::value,
int>::type;
// Opposite of above
template<class Kind>
using enable_if_not_castable_t = typename std::enable_if<
!std::is_base_of<Expression, std::remove_pointer_t<matched_t<Kind>>>::value ||
std::is_same<Expression*, matched_t<Kind>>::value,
int>::type;
// Do a normal dynCast from Expression* to the subtype, storing the result in
// `out` and returning `true` iff the cast succeeded.
template<class Kind, enable_if_castable_t<Kind> = 0>
inline bool dynCastCandidate(candidate_t<Kind> candidate,
matched_t<Kind>& out) {
out = candidate->template dynCast<std::remove_pointer_t<matched_t<Kind>>>();
return out != nullptr;
}
// Otherwise we are not matching an Expression, so this is infallible.
template<class Kind, enable_if_not_castable_t<Kind> = 0>
inline bool dynCastCandidate(candidate_t<Kind> candidate,
matched_t<Kind>& out) {
out = candidate;
return true;
}
// Matchers can optionally specialize this to perform custom matching logic
// before recursing into submatchers, potentially short-circuiting the match.
// Uses a struct because partial specialization of functions is not allowed.
template<class Kind> struct MatchSelf {
bool operator()(matched_t<Kind>, data_t<Kind>) { return true; }
};
// Used to statically ensure that each matcher has the correct number of
// submatchers. This needs to be specialized for each kind of matcher that has
// submatchers.
template<class Kind> struct NumComponents {
static constexpr size_t value = 0;
};
// Every kind of matcher needs to partially specialize this for each of its
// components. Each specialization should define
//
// T operator()(matched_t<Kind>)
//
// where T is the component's type. Components will be matched from first to
// last. Uses a struct instead of a function because partial specialization of
// functions is not allowed.
template<class Kind, int pos> struct GetComponent;
// A type-level linked list to hold an arbitrary number of matchers.
template<class...> struct SubMatchers {};
template<class CurrMatcher, class... NextMatchers>
struct SubMatchers<CurrMatcher, NextMatchers...> {
CurrMatcher curr;
SubMatchers<NextMatchers...> next;
SubMatchers(CurrMatcher curr, NextMatchers... next)
: curr(curr), next(next...){};
};
// Iterates through the components of the candidate, applying a submatcher to
// each component. Uses a struct instead of a function because partial
// specialization of functions is not allowed.
template<class Kind, int pos, class CurrMatcher = void, class... NextMatchers>
struct Components {
static inline bool
match(matched_t<Kind> candidate,
SubMatchers<CurrMatcher, NextMatchers...>& matchers) {
return matchers.curr.matches(GetComponent<Kind, pos>{}(candidate)) &&
Components<Kind, pos + 1, NextMatchers...>::match(candidate,
matchers.next);
}
};
template<class Kind, int pos> struct Components<Kind, pos> {
static_assert(pos == NumComponents<Kind>::value,
"Unexpected number of submatchers");
static inline bool match(matched_t<Kind>, SubMatchers<>) {
// Base case when there are no components left; trivially true.
return true;
}
};
template<class Kind, class... Matchers> struct Matcher {
matched_t<Kind>* binder;
data_t<Kind> data;
SubMatchers<Matchers...> submatchers;
Matcher(matched_t<Kind>* binder, data_t<Kind> data, Matchers... submatchers)
: binder(binder), data(data), submatchers(submatchers...) {}
inline bool matches(candidate_t<Kind> candidate) {
matched_t<Kind> casted;
if (dynCastCandidate<Kind>(candidate, casted)) {
if (binder != nullptr) {
*binder = casted;
}
return MatchSelf<Kind>{}(casted, data) &&
Components<Kind, 0, Matchers...>::match(casted, submatchers);
}
return false;
}
};
// Concrete low-level matcher implementations. Not intended for direct external
// use.
// Any<T>: matches any value of the expected type
template<class T> struct AnyKind {};
template<class T> struct KindTypeRegistry<AnyKind<T>> {
using matched_t = T;
using data_t = unused_t;
};
template<class T> inline decltype(auto) Any(T* binder) {
return Matcher<AnyKind<T>>(binder, {});
}
// Exact<T>: matches exact values of the expected type
template<class T> struct ExactKind {};
template<class T> struct KindTypeRegistry<ExactKind<T>> {
using matched_t = T;
using data_t = T;
};
template<class T> struct MatchSelf<ExactKind<T>> {
bool operator()(T self, T expected) { return self == expected; }
};
template<class T> inline decltype(auto) Exact(T* binder, T data) {
return Matcher<ExactKind<T>>(binder, data);
}
// {Bool,I32,I64,Int,F32,F64,Float,Number}Lit:
// match `Literal` of the expected `Type`
struct BoolLK {
static bool matchType(Literal lit) {
return lit.type == Type::i32 && (uint32_t)lit.geti32() <= 1U;
}
static int32_t getVal(Literal lit) { return lit.geti32(); }
};
struct I32LK {
static bool matchType(Literal lit) { return lit.type == Type::i32; }
static int32_t getVal(Literal lit) { return lit.geti32(); }
};
struct I64LK {
static bool matchType(Literal lit) { return lit.type == Type::i64; }
static int64_t getVal(Literal lit) { return lit.geti64(); }
};
struct IntLK {
static bool matchType(Literal lit) { return lit.type.isInteger(); }
static int64_t getVal(Literal lit) { return lit.getInteger(); }
};
struct F32LK {
static bool matchType(Literal lit) { return lit.type == Type::f32; }
static float getVal(Literal lit) { return lit.getf32(); }
};
struct F64LK {
static bool matchType(Literal lit) { return lit.type == Type::f64; }
static double getVal(Literal lit) { return lit.getf64(); }
};
struct FloatLK {
static bool matchType(Literal lit) { return lit.type.isFloat(); }
static double getVal(Literal lit) { return lit.getFloat(); }
};
template<class T> struct LitKind {};
template<class T> struct KindTypeRegistry<LitKind<T>> {
using matched_t = Literal;
using data_t = unused_t;
};
template<class T> struct MatchSelf<LitKind<T>> {
bool operator()(Literal lit, unused_t) { return T::matchType(lit); }
};
template<class T> struct NumComponents<LitKind<T>> {
static constexpr size_t value = 1;
};
template<class T> struct GetComponent<LitKind<T>, 0> {
decltype(auto) operator()(Literal lit) { return T::getVal(lit); }
};
template<class S> inline decltype(auto) BoolLit(Literal* binder, S&& s) {
return Matcher<LitKind<BoolLK>, S>(binder, {}, s);
}
template<class S> inline decltype(auto) I32Lit(Literal* binder, S&& s) {
return Matcher<LitKind<I32LK>, S>(binder, {}, s);
}
template<class S> inline decltype(auto) I64Lit(Literal* binder, S&& s) {
return Matcher<LitKind<I64LK>, S>(binder, {}, s);
}
template<class S> inline decltype(auto) IntLit(Literal* binder, S&& s) {
return Matcher<LitKind<IntLK>, S>(binder, {}, s);
}
template<class S> inline decltype(auto) F32Lit(Literal* binder, S&& s) {
return Matcher<LitKind<F32LK>, S>(binder, {}, s);
}
template<class S> inline decltype(auto) F64Lit(Literal* binder, S&& s) {
return Matcher<LitKind<F64LK>, S>(binder, {}, s);
}
template<class S> inline decltype(auto) FloatLit(Literal* binder, S&& s) {
return Matcher<LitKind<FloatLK>, S>(binder, {}, s);
}
struct NumberLitKind {};
template<> struct KindTypeRegistry<NumberLitKind> {
using matched_t = Literal;
using data_t = int32_t;
};
template<> struct MatchSelf<NumberLitKind> {
bool operator()(Literal lit, int32_t expected) {
return lit.type.isNumber() &&
Literal::makeFromInt32(expected, lit.type) == lit;
}
};
inline decltype(auto) NumberLit(Literal* binder, int32_t expected) {
return Matcher<NumberLitKind>(binder, expected);
}
// Const
template<> struct NumComponents<Const*> { static constexpr size_t value = 1; };
template<> struct GetComponent<Const*, 0> {
Literal operator()(Const* c) { return c->value; }
};
template<class S> inline decltype(auto) ConstMatcher(Const** binder, S&& s) {
return Matcher<Const*, S>(binder, {}, s);
}
// Unary, UnaryOp and AbstractUnaryOp
template<> struct NumComponents<Unary*> { static constexpr size_t value = 2; };
template<> struct GetComponent<Unary*, 0> {
UnaryOp operator()(Unary* curr) { return curr->op; }
};
template<> struct GetComponent<Unary*, 1> {
Expression* operator()(Unary* curr) { return curr->value; }
};
struct UnaryOpK {
using Op = UnaryOp;
static UnaryOp getOp(Type, Op op) { return op; }
};
struct AbstractUnaryOpK {
using Op = Abstract::Op;
static UnaryOp getOp(Type type, Abstract::Op op) {
return Abstract::getUnary(type, op);
}
};
template<class T> struct UnaryOpKind {};
template<class T> struct KindTypeRegistry<UnaryOpKind<T>> {
using matched_t = Unary*;
using data_t = typename T::Op;
};
template<class T> struct MatchSelf<UnaryOpKind<T>> {
bool operator()(Unary* curr, typename T::Op op) {
return curr->op == T::getOp(curr->value->type, op);
}
};
template<class T> struct NumComponents<UnaryOpKind<T>> {
static constexpr size_t value = 1;
};
template<class T> struct GetComponent<UnaryOpKind<T>, 0> {
Expression* operator()(Unary* curr) { return curr->value; }
};
template<class S1, class S2>
inline decltype(auto) UnaryMatcher(Unary** binder, S1&& s1, S2&& s2) {
return Matcher<Unary*, S1, S2>(binder, {}, s1, s2);
}
template<class S>
inline decltype(auto) UnaryOpMatcher(Unary** binder, UnaryOp op, S&& s) {
return Matcher<UnaryOpKind<UnaryOpK>, S>(binder, op, s);
}
template<class S>
inline decltype(auto)
AbstractUnaryOpMatcher(Unary** binder, Abstract::Op op, S&& s) {
return Matcher<UnaryOpKind<AbstractUnaryOpK>, S>(binder, op, s);
}
// Binary, BinaryOp and AbstractBinaryOp
template<> struct NumComponents<Binary*> { static constexpr size_t value = 3; };
template<> struct GetComponent<Binary*, 0> {
BinaryOp operator()(Binary* curr) { return curr->op; }
};
template<> struct GetComponent<Binary*, 1> {
Expression* operator()(Binary* curr) { return curr->left; }
};
template<> struct GetComponent<Binary*, 2> {
Expression* operator()(Binary* curr) { return curr->right; }
};
struct BinaryOpK {
using Op = BinaryOp;
static BinaryOp getOp(Type, Op op) { return op; }
};
struct AbstractBinaryOpK {
using Op = Abstract::Op;
static BinaryOp getOp(Type type, Abstract::Op op) {
return Abstract::getBinary(type, op);
}
};
template<class T> struct BinaryOpKind {};
template<class T> struct KindTypeRegistry<BinaryOpKind<T>> {
using matched_t = Binary*;
using data_t = typename T::Op;
};
template<class T> struct MatchSelf<BinaryOpKind<T>> {
bool operator()(Binary* curr, typename T::Op op) {
return curr->op == T::getOp(curr->left->type, op);
}
};
template<class T> struct NumComponents<BinaryOpKind<T>> {
static constexpr size_t value = 2;
};
template<class T> struct GetComponent<BinaryOpKind<T>, 0> {
Expression* operator()(Binary* curr) { return curr->left; }
};
template<class T> struct GetComponent<BinaryOpKind<T>, 1> {
Expression* operator()(Binary* curr) { return curr->right; }
};
template<class S1, class S2, class S3>
inline decltype(auto)
BinaryMatcher(Binary** binder, S1&& s1, S2&& s2, S3&& s3) {
return Matcher<Binary*, S1, S2, S3>(binder, {}, s1, s2, s3);
}
template<class S1, class S2>
inline decltype(auto)
BinaryOpMatcher(Binary** binder, BinaryOp op, S1&& s1, S2&& s2) {
return Matcher<BinaryOpKind<BinaryOpK>, S1, S2>(binder, op, s1, s2);
}
template<class S1, class S2>
inline decltype(auto)
AbstractBinaryOpMatcher(Binary** binder, Abstract::Op op, S1&& s1, S2&& s2) {
return Matcher<BinaryOpKind<AbstractBinaryOpK>, S1, S2>(binder, op, s1, s2);
}
// Select
template<> struct NumComponents<Select*> { static constexpr size_t value = 3; };
template<> struct GetComponent<Select*, 0> {
Expression* operator()(Select* curr) { return curr->ifTrue; }
};
template<> struct GetComponent<Select*, 1> {
Expression* operator()(Select* curr) { return curr->ifFalse; }
};
template<> struct GetComponent<Select*, 2> {
Expression* operator()(Select* curr) { return curr->condition; }
};
template<class S1, class S2, class S3>
inline decltype(auto)
SelectMatcher(Select** binder, S1&& s1, S2&& s2, S3&& s3) {
return Matcher<Select*, S1, S2, S3>(binder, {}, s1, s2, s3);
}
} // namespace Internal
// Public matching API
inline decltype(auto) bval() {
return Internal::ConstMatcher(
nullptr, Internal::BoolLit(nullptr, Internal::Any<bool>(nullptr)));
}
inline decltype(auto) bval(bool x) {
return Internal::ConstMatcher(
nullptr, Internal::BoolLit(nullptr, Internal::Exact<bool>(nullptr, x)));
}
inline decltype(auto) bval(bool* binder) {
return Internal::ConstMatcher(
nullptr, Internal::BoolLit(nullptr, Internal::Any(binder)));
}
inline decltype(auto) bval(Literal* binder) {
return Internal::ConstMatcher(
nullptr, Internal::BoolLit(binder, Internal::Any<bool>(nullptr)));
}
inline decltype(auto) bval(Const** binder) {
return Internal::ConstMatcher(
binder, Internal::BoolLit(nullptr, Internal::Any<bool>(nullptr)));
}
inline decltype(auto) i32() {
return Internal::ConstMatcher(
nullptr, Internal::I32Lit(nullptr, Internal::Any<int32_t>(nullptr)));
}
// Use int rather than int32_t to disambiguate literal 0, which otherwise could
// be resolved to either the int32_t overload or any of the pointer overloads.
inline decltype(auto) i32(int x) {
return Internal::ConstMatcher(
nullptr, Internal::I32Lit(nullptr, Internal::Exact<int32_t>(nullptr, x)));
}
inline decltype(auto) i32(int32_t* binder) {
return Internal::ConstMatcher(
nullptr, Internal::I32Lit(nullptr, Internal::Any(binder)));
}
inline decltype(auto) i32(Literal* binder) {
return Internal::ConstMatcher(
nullptr, Internal::I32Lit(binder, Internal::Any<int32_t>(nullptr)));
}
inline decltype(auto) i32(Const** binder) {
return Internal::ConstMatcher(
binder, Internal::I32Lit(nullptr, Internal::Any<int32_t>(nullptr)));
}
inline decltype(auto) i64() {
return Internal::ConstMatcher(
nullptr, Internal::I64Lit(nullptr, Internal::Any<int64_t>(nullptr)));
}
inline decltype(auto) i64(int64_t x) {
return Internal::ConstMatcher(
nullptr, Internal::I64Lit(nullptr, Internal::Exact<int64_t>(nullptr, x)));
}
// Disambiguate literal 0, which could otherwise be interpreted as a pointer
inline decltype(auto) i64(int x) { return i64(int64_t(x)); }
inline decltype(auto) i64(int64_t* binder) {
return Internal::ConstMatcher(
nullptr, Internal::I64Lit(nullptr, Internal::Any(binder)));
}
inline decltype(auto) i64(Literal* binder) {
return Internal::ConstMatcher(
nullptr, Internal::I64Lit(binder, Internal::Any<int64_t>(nullptr)));
}
inline decltype(auto) i64(Const** binder) {
return Internal::ConstMatcher(
binder, Internal::I64Lit(nullptr, Internal::Any<int64_t>(nullptr)));
}
inline decltype(auto) f32() {
return Internal::ConstMatcher(
nullptr, Internal::F32Lit(nullptr, Internal::Any<float>(nullptr)));
}
inline decltype(auto) f32(float x) {
return Internal::ConstMatcher(
nullptr, Internal::F32Lit(nullptr, Internal::Exact<float>(nullptr, x)));
}
// Disambiguate literal 0, which could otherwise be interpreted as a pointer
inline decltype(auto) f32(int x) { return f32(float(x)); }
inline decltype(auto) f32(float* binder) {
return Internal::ConstMatcher(
nullptr, Internal::F32Lit(nullptr, Internal::Any(binder)));
}
inline decltype(auto) f32(Literal* binder) {
return Internal::ConstMatcher(
nullptr, Internal::F32Lit(binder, Internal::Any<float>(nullptr)));
}
inline decltype(auto) f32(Const** binder) {
return Internal::ConstMatcher(
binder, Internal::F32Lit(nullptr, Internal::Any<float>(nullptr)));
}
inline decltype(auto) f64() {
return Internal::ConstMatcher(
nullptr, Internal::F64Lit(nullptr, Internal::Any<double>(nullptr)));
}
inline decltype(auto) f64(double x) {
return Internal::ConstMatcher(
nullptr, Internal::F64Lit(nullptr, Internal::Exact<double>(nullptr, x)));
}
// Disambiguate literal 0, which could otherwise be interpreted as a pointer
inline decltype(auto) f64(int x) { return f64(double(x)); }
inline decltype(auto) f64(double* binder) {
return Internal::ConstMatcher(
nullptr, Internal::F64Lit(nullptr, Internal::Any(binder)));
}
inline decltype(auto) f64(Literal* binder) {
return Internal::ConstMatcher(
nullptr, Internal::F64Lit(binder, Internal::Any<double>(nullptr)));
}
inline decltype(auto) f64(Const** binder) {
return Internal::ConstMatcher(
binder, Internal::F64Lit(nullptr, Internal::Any<double>(nullptr)));
}
inline decltype(auto) ival() {
return Internal::ConstMatcher(
nullptr, Internal::IntLit(nullptr, Internal::Any<int64_t>(nullptr)));
}
inline decltype(auto) ival(int64_t x) {
return Internal::ConstMatcher(
nullptr, Internal::IntLit(nullptr, Internal::Exact<int64_t>(nullptr, x)));
}
// Disambiguate literal 0, which could otherwise be interpreted as a pointer
inline decltype(auto) ival(int x) { return ival(int64_t(x)); }
inline decltype(auto) ival(int64_t* binder) {
return Internal::ConstMatcher(
nullptr, Internal::IntLit(nullptr, Internal::Any(binder)));
}
inline decltype(auto) ival(Literal* binder) {
return Internal::ConstMatcher(
nullptr, Internal::IntLit(binder, Internal::Any<int64_t>(nullptr)));
}
inline decltype(auto) ival(Const** binder) {
return Internal::ConstMatcher(
binder, Internal::IntLit(nullptr, Internal::Any<int64_t>(nullptr)));
}
inline decltype(auto) ival(Literal* binder, int64_t x) {
return Internal::ConstMatcher(
nullptr, Internal::IntLit(binder, Internal::Exact<int64_t>(nullptr, x)));
}
inline decltype(auto) ival(Const** binder, int64_t x) {
return Internal::ConstMatcher(
binder, Internal::IntLit(nullptr, Internal::Exact<int64_t>(nullptr, x)));
}
inline decltype(auto) fval() {
return Internal::ConstMatcher(
nullptr, Internal::FloatLit(nullptr, Internal::Any<double>(nullptr)));
}
inline decltype(auto) fval(double x) {
return Internal::ConstMatcher(
nullptr, Internal::FloatLit(nullptr, Internal::Exact<double>(nullptr, x)));
}
// Disambiguate literal 0, which could otherwise be interpreted as a pointer
inline decltype(auto) fval(int x) { return fval(double(x)); }
inline decltype(auto) fval(double* binder) {
return Internal::ConstMatcher(
nullptr, Internal::FloatLit(nullptr, Internal::Any(binder)));
}
inline decltype(auto) fval(Literal* binder) {
return Internal::ConstMatcher(
nullptr, Internal::FloatLit(binder, Internal::Any<double>(nullptr)));
}
inline decltype(auto) fval(Const** binder) {
return Internal::ConstMatcher(
binder, Internal::FloatLit(nullptr, Internal::Any<double>(nullptr)));
}
inline decltype(auto) fval(Literal* binder, double x) {
return Internal::ConstMatcher(
nullptr, Internal::FloatLit(binder, Internal::Exact<double>(nullptr, x)));
}
inline decltype(auto) fval(Const** binder, double x) {
return Internal::ConstMatcher(
binder, Internal::FloatLit(nullptr, Internal::Exact<double>(nullptr, x)));
}
inline decltype(auto) constant() {
return Internal::ConstMatcher(nullptr, Internal::Any<Literal>(nullptr));
}
inline decltype(auto) constant(int x) {
return Internal::ConstMatcher(nullptr, Internal::NumberLit(nullptr, x));
}
inline decltype(auto) constant(Literal* binder) {
return Internal::ConstMatcher(nullptr, Internal::Any(binder));
}
inline decltype(auto) constant(Const** binder) {
return Internal::ConstMatcher(binder, Internal::Any<Literal>(nullptr));
}
inline decltype(auto) constant(Literal* binder, int32_t x) {
return Internal::ConstMatcher(nullptr, Internal::NumberLit(binder, x));
}
inline decltype(auto) constant(Const** binder, int32_t x) {
return Internal::ConstMatcher(binder, Internal::NumberLit(nullptr, x));
}
inline decltype(auto) any() { return Internal::Any<Expression*>(nullptr); }
inline decltype(auto) any(Expression** binder) { return Internal::Any(binder); }
template<class S> inline decltype(auto) unary(S&& s) {
return Internal::UnaryMatcher(nullptr, Internal::Any<UnaryOp>(nullptr), s);
}
template<class S> inline decltype(auto) unary(Unary** binder, S&& s) {
return Internal::UnaryMatcher(binder, Internal::Any<UnaryOp>(nullptr), s);
}
template<class S> inline decltype(auto) unary(UnaryOp* binder, S&& s) {
return Internal::UnaryMatcher(nullptr, Internal::Any<UnaryOp>(binder), s);
}
template<class S> inline decltype(auto) unary(UnaryOp op, S&& s) {
return Internal::UnaryOpMatcher(nullptr, op, s);
}
template<class S> inline decltype(auto) unary(Abstract::Op op, S&& s) {
return Internal::AbstractUnaryOpMatcher(nullptr, op, s);
}
template<class S>
inline decltype(auto) unary(Unary** binder, UnaryOp op, S&& s) {
return Internal::UnaryOpMatcher(binder, op, s);
}
template<class S>
inline decltype(auto) unary(Unary** binder, Abstract::Op op, S&& s) {
return Internal::AbstractUnaryOpMatcher(binder, op, s);
}
template<class S1, class S2> inline decltype(auto) binary(S1&& s1, S2&& s2) {
return Internal::BinaryMatcher(
nullptr, Internal::Any<BinaryOp>(nullptr), s1, s2);
}
template<class S1, class S2>
inline decltype(auto) binary(Binary** binder, S1&& s1, S2&& s2) {
return Internal::BinaryMatcher(
binder, Internal::Any<BinaryOp>(nullptr), s1, s2);
}
template<class S1, class S2>
inline decltype(auto) binary(BinaryOp* binder, S1&& s1, S2&& s2) {
return Internal::BinaryMatcher(
nullptr, Internal::Any<BinaryOp>(binder), s1, s2);
}
template<class S1, class S2>
inline decltype(auto) binary(BinaryOp op, S1&& s1, S2&& s2) {
return Internal::BinaryOpMatcher(nullptr, op, s1, s2);
}
template<class S1, class S2>
inline decltype(auto) binary(Abstract::Op op, S1&& s1, S2&& s2) {
return Internal::AbstractBinaryOpMatcher(nullptr, op, s1, s2);
}
template<class S1, class S2>
inline decltype(auto) binary(Binary** binder, BinaryOp op, S1&& s1, S2&& s2) {
return Internal::BinaryOpMatcher(binder, op, s1, s2);
}
template<class S1, class S2>
inline decltype(auto)
binary(Binary** binder, Abstract::Op op, S1&& s1, S2&& s2) {
return Internal::AbstractBinaryOpMatcher(binder, op, s1, s2);
}
template<class S1, class S2, class S3>
inline decltype(auto) select(S1&& s1, S2&& s2, S3&& s3) {
return Internal::SelectMatcher(nullptr, s1, s2, s3);
}
template<class S1, class S2, class S3>
inline decltype(auto) select(Select** binder, S1&& s1, S2&& s2, S3&& s3) {
return Internal::SelectMatcher(binder, s1, s2, s3);
}
} // namespace wasm::Match
#endif // wasm_ir_match_h
| true |
d1f8fe5cab7ae62ee7c521977b8ec6955b3ff763 | C++ | yangguodang0502/LeetCodeWithCpp | /labuladong/188/maxProfit.h | UTF-8 | 1,087 | 3.015625 | 3 | [] | no_license | #include <vector>
#include <limits.h>
using namespace std;
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int n = prices.size();
if (k > n / 2) {
return maxProfit_infinity(prices);
}
int dp[n][k+1][2];
for (int i = 0; i < n; i++) {
dp[i][0][0] = 0;
dp[i][0][1] = INT_MIN;
}
for (int j = 1; j < k+1; j++) {
dp[0][j][0] = 0;
dp[0][j][1] = -prices[0];
}
for (int i = 1; i < n; i++) {
for (int j = k; j >= 1; j--) {
dp[i][j][0] = max(dp[i-1][j][0], dp[i-1][j][1] + prices[i]);
dp[i][j][1] = max(dp[i-1][j][1], dp[i-1][j-1][0] - prices[i]);
}
}
return dp[n-1][k][0];
}
int maxProfit_infinity(vector<int>& prices) {
int dpi0 = 0;
int dpi1 = INT_MIN;
for (int i = 0; i < prices.size(); i++) {
dpi0 = max(dpi0, dpi1 + prices[i]);
dpi1 = max(dpi1, dpi0 - prices[i]);
}
return dpi0;
}
}; | true |
c30ca44d0aa9a301938c3f18930bbd97e59e04e0 | C++ | Bao-T/CS-172 | /HW05/11_13/11_13/Course.cpp | UTF-8 | 2,117 | 3.859375 | 4 | [] | no_license | #include <iostream>
#include "Class.h"
using namespace std;
Course::Course(const string& courseName, int capacity)
{
numberOfStudents = 0;
this->courseName = courseName;
this->capacity = capacity;
students = new string[capacity];
}
Course::~Course()
{
delete[] students;
}
string Course::getCourseName() const
{
return courseName;
}
void Course::addStudent(const string& name)
{
students[numberOfStudents] = name;
numberOfStudents++;
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ From Book example 11.16
// 11.13
if (numberOfStudents >= capacity) // once the number of students reaches the capacity or is greater
{
string *newArray = new string[capacity + 10]; // assigns address of newArray to the address of an array of strings with capacity +10
for (int i = 0; i < capacity; i++) // copies the old array students to newArray up until the last index of students
{
newArray[i] = students[i];
}
capacity += 10; // changes capacity to the new capacity amount
students = newArray; // resets student to newArray
}
}
void Course::dropStudent(const string& name)
{
// checks the entire index of the array
for (int i = 0; i < capacity; i++)
{
if (name == students[i]) // checks for a match in the strings
{
for (int j = i; j < capacity - 1; j++) // goes through the indexes after the index with the matching string.
{
students[j] = students[j + 1]; // moves all the indexes over to accomodate the dropped student
}
students[capacity -1] = ""; // sets the very last index to nothing.
numberOfStudents--; // take out one student from count
}
}
}
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv From Book example 11.16
string* Course::getStudents() const
{
return students;
}
int Course::getNumberOfStudents() const
{
return numberOfStudents;
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ From Book example 11.16
void Course::clear()
{
for (int i = 0; i < capacity; i++)
students[i] = "";
// or students = new string[0];
numberOfStudents = 0; // resets the student count
}
| true |
d56f9beb0d6a28336dd7b24a29a8d065eaf0d168 | C++ | GuillaumeDua/GCL_CPP | /includes/gcl/io/policy.hpp | UTF-8 | 5,964 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <gcl/container/concepts.hpp>
#include <gcl/io/concepts.hpp>
#include <gcl/mp/concepts.hpp>
#include <gcl/concepts.hpp>
#include <concepts>
#include <utility>
#include <type_traits>
#include <iostream>
namespace gcl::io::policy
{
template <typename policy_impl>
struct crtp_impl {
template <typename T>
// requires gcl::io::concepts::serializable<std::remove_reference_t<T>> // todo
static void read(std::istream& is, T&& value)
{
policy_impl::basic_read(is, std::forward<decltype(value)>(value));
}
template <gcl::io::concepts::has_custom_deserialize T>
static void read(std::istream& is, T&& value)
{ // policy by-pass
value.deserialize_from(is);
}
template <gcl::concepts::pointer T> // [modif]
static void read(std::istream& is, T&& value)
{
policy_impl::read(is, *value);
}
template <std::ranges::range T>
static void read(std::istream& is, T&& value)
{
using value_type = std::remove_reference_t<T>;
const auto size = [&is]() {
if constexpr (std::is_array_v<value_type>)
{
std::size_t size_value;
policy_impl::read(is, size_value);
return size_value;
}
else
{
typename value_type::size_type size_value;
policy_impl::read(is, size_value);
return size_value;
}
}();
if constexpr (gcl::container::concepts::resizable<value_type>)
value.resize(size);
else if (std::size(value) < size)
throw std::runtime_error{"gcl::io::policy::policy_impl::read : fixed-size < size"};
auto element = []() {
if constexpr (std::is_array_v<value_type>)
return std::remove_extent_t<value_type>{};
else
return typename value_type::value_type{};
}(); // Clang does not support lambdas in an unevaluated context yet ...
auto input_it = std::begin(value);
for (std::decay_t<decltype(size)> i{0}; i < size; ++i)
{
policy_impl::read(is, element);
*input_it++ = std::move(element);
}
}
template <typename... Ts, typename = std::enable_if_t<(sizeof...(Ts) not_eq 1)>>
static void read(std::istream& is, Ts&&... values)
{
(read(is, std::forward<Ts>(values)), ...);
}
template <typename T>
static void write(std::ostream& os, const T& value)
{
if constexpr (std::is_pointer_v<T>)
write(os, *value);
else if constexpr (std::ranges::range<T>)
{
write(os, std::size(value));
for (const auto& element : value)
write(os, element);
}
else
policy_impl::basic_write(os, value);
}
template <gcl::io::concepts::has_custom_serialize T>
static void write(std::ostream& os, const T& value)
{ // policy by-pass
value.serialize_to(os);
}
template <typename... Ts, typename = std::enable_if_t<(sizeof...(Ts) not_eq 1)>>
static void write(std::ostream& os, const Ts&... values)
{
(write(os, values), ...);
}
};
struct binary : crtp_impl<binary> {
using crtp_impl<binary>::read;
using crtp_impl<binary>::write;
template <typename T>
static void basic_read(std::istream& is, T&& value)
{
is.read(reinterpret_cast<char*>(&value), sizeof(T));
}
template <typename T>
static void basic_write(std::ostream& os, const T& value)
{
os.write(reinterpret_cast<const char*>(&value), sizeof(T));
}
};
template <>
void binary::basic_read<std::string>(std::istream& is, std::string&& value)
{
std::string::size_type size;
binary::basic_read(is, size);
value.resize(size, '\0');
is.read(&value[0], size);
}
template <>
void binary::basic_write<std::string>(std::ostream& os, const std::string& value)
{
std::string::size_type size = value.length();
os.write(reinterpret_cast<char*>(&size), sizeof(std::string::size_type));
os.write(&value[0], value.length());
}
struct stream : crtp_impl<stream> {
using crtp_impl<stream>::read;
using crtp_impl<stream>::write;
constexpr static char record_separator = 0x1e; // RS ASCII entry
template <typename T>
requires concepts::has_custom_deserialize<T> or
concepts::istream_shiftable<T> static void basic_read(std::istream& is, T&& value)
{
// todo : if constexpr has_custom_deserialize
// deserialize
// else
extract_RS(is >> std::forward<T>(value));
}
template <typename T>
requires concepts::has_custom_serialize<T> or
concepts::ostream_shiftable<T> static void basic_write(std::ostream& os, const T& value)
{
os << value << record_separator;
}
private:
static void extract_RS(std::istream& is)
{
decltype(record_separator) separator = is.get();
if (separator not_eq record_separator)
throw std::runtime_error{"gcl::io::policy::stream : unexpected RS"};
}
};
static_assert(sizeof(binary{}) == 1);
static_assert(sizeof(stream{}) == 1);
} | true |
18e63c72d50b0bd880be8b5d4236d0b3df7d131a | C++ | fianchi04/blockworld | /src/GameWorld.cc | UTF-8 | 7,333 | 2.8125 | 3 | [
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | #include "GameWorld.h"
/**
* Create cube and diamond assets and assign location and color
**/
GameWorld::GameWorld (ApplicationMode mode) {
srand(time(NULL));
asset_manager = std::make_shared<GameAssetManager>(mode);
//generate floor
asset_manager->AddAsset(std::make_shared<FloorAsset>(glm::vec3(10.0, -1.0, 10.0), glm::vec3(0.0, 0.0, 1 - (randomGen()/4))));
asset_manager->AddAsset(std::make_shared<FloorAsset>(glm::vec3(10.0, 5.0, 34.5), glm::vec3(0.0, 0.0, 1 - (randomGen()/4))));
//generate some stairs
for (int k = 0; k<20; k++){
for (int l = 0; l<5; l++){
asset_manager->AddAsset(std::make_shared<CubeAsset>(glm::vec3(0.5 + k, 0.0 + l, 20.0 + l), glm::vec3(0.0, 0.0, randomGen())));
}
}
//generate walls
for (int x = 0; x< 20; x++){
for(int y = 0; y<5; y++){
asset_manager->AddAsset(std::make_shared<CubeAsset>(glm::vec3(0.0 + x, 0.0 + y, 0.0), glm::vec3(1.0, randomGen()*0.2, randomGen()*0.2)));
asset_manager->AddAsset(std::make_shared<CubeAsset>(glm::vec3(0.0, 0.0 + y, 0.0 + x), glm::vec3(1.0, randomGen()*0.2, randomGen()*0.2)));
asset_manager->AddAsset(std::make_shared<CubeAsset>(glm::vec3(20.0, 0.0 + y, 0.0 + x), glm::vec3(1.0, randomGen()*0.2, randomGen()*0.2)));
asset_manager->AddAsset(std::make_shared<CubeAsset>(glm::vec3(0.0 + x, 0.0 + y, 44.0), glm::vec3(1.0, randomGen()*0.2, randomGen()*0.2)));
}
}
for(int z = 0; z< 25; z++){
for( int y = 0; y<5; y++){
asset_manager->AddAsset(std::make_shared<CubeAsset>(glm::vec3(0.0, 0.0 + y, 20.0 + z), glm::vec3(1.0, randomGen()*0.2, randomGen()*0.2)));
asset_manager->AddAsset(std::make_shared<CubeAsset>(glm::vec3(20.0, 0.0 + y, 20.0 + z), glm::vec3(1.0, randomGen()*0.2, randomGen()*0.2)));
}
}
//add cubes on lower floor
for (int a = 0; a <20; a++){
asset_manager->AddAsset(std::make_shared<CubeAsset>(glm::vec3(randomGen()*20 + 1.0, randomGen()*4, randomGen()*20),glm::vec3(1.0 - (randomGen()/2), 1.0 - (randomGen()/2), 1.0 - (randomGen()/2))));
}
//add diamonds on top floor
for (int a = 0; a<20; a++){
if(a <5){
asset_manager->AddAsset(std::make_shared<DiamondAsset>(glm::vec3(randomGen()*20.0, randomGen()*4 + 6.0, randomGen()*20 + 25),glm::vec3(1 - (randomGen()/4), 0.0, 0.0)));}
else if (a >=5 && a<10){
asset_manager->AddAsset(std::make_shared<DiamondAsset>(glm::vec3(randomGen()*20.0, randomGen()*4 + 6.0, randomGen()*20 + 25),glm::vec3(0.0, 1 - (randomGen()/4), 0.0)));}
else {
asset_manager->AddAsset(std::make_shared<DiamondAsset>(glm::vec3(randomGen()*20.0, randomGen()*4 + 6.0, randomGen()*20 + 25),glm::vec3(0.0, 0.0, 1 - (randomGen()/4))));}
}
program_token = asset_manager->returnProgram_token();
model_loc = glGetUniformLocation(program_token, "Model");
proj_loc = glGetUniformLocation(program_token, "Projection");
view_loc = glGetUniformLocation(program_token, "View");
}
/**
* generate random float between 0 and 1
**/
GLfloat GameWorld::randomGen(){
return static_cast<float>(rand())/static_cast<float>(RAND_MAX);
}
/**
* fix camera to the center of the screen and limit range
**/
void GameWorld::set_camera(GLfloat x, GLfloat y){
camerax-= x;
cameray-= y;
//limit on camera range
if (cameray > 1.5){
cameray = 1.5;}
if (cameray < -1.5){
cameray = -1.5;}
}
/**
* add cube to game space from mouse input
**/
void GameWorld::add_cube(){
glm::vec3 temp = position + direction * glm::vec3(3,3,3);
asset_manager->AddAsset(std::make_shared<PlacedCubeAsset>(temp,
glm::vec3(randomGen(), 0.0, 0.0)));
}
/**
* add diamond to game space from mouse input
**/
void GameWorld::add_diamond(){
glm::vec3 temp = position + direction * glm::vec3(3,3,3);
asset_manager->AddAsset(std::make_shared<DiamondAsset>(temp,
glm::vec3(0.0, randomGen()/2, randomGen())));
}
/**
* keyboard input for moving forwards with collision detection
**/
void GameWorld::move_forward(){
position+=mdirection*speed;
//check collision, if collides move back
if(asset_manager->checkCollision(position)){
position-=mdirection*speed;
}
}
/**
* keyboard input for moving back with collision detection
**/
void GameWorld::move_back(){
position-=mdirection*speed;
//check collision, if collides move back
if(asset_manager->checkCollision(position)){
position+=mdirection*speed;
}
}
/**
* keyboard input for moving left with collision detection
**/
void GameWorld::move_left(){
position-=vright*speed;
//check collision, if collides move back
if(asset_manager->checkCollision(position)){
position+=vright*speed;
}
}
/**
* keyboard input for moving right with collision detection
**/
void GameWorld::move_right(){
position+=vright*speed;
//check collision, if collides move back
if(asset_manager->checkCollision(position)){
position-=vright*speed;
}
}
/**
* keyboard input for jump with controlled jump speed
**/
void GameWorld::move_jump(GLfloat speed){
//if jump has lasted less than 15 updates
if(jumplength < 10){
//add passed speed to jumpspeed
jumpspeed += speed;
//counter to see how many frames jump has been on for
jumplength ++;
}
//stop jumping too fast
if(jumpspeed > 2){
jumpspeed = 2;
}
}
/**
* checks if jumping is enabled (can only jump once between player touching solid ground)
**/
bool GameWorld::canJump(){
return jump1;
}
/**
* loop to draw the world and all assets and qualities
**/
void GameWorld::Draw() {
//every update slow jump speed
jumpspeed -= 0.05;
//stop jumpspeed going below 0
if(jumpspeed < 0.0){
jumpspeed = 0.0;
}
//minus gravity + jumpspeed from position y
position.y -= (0.98-jumpspeed)*speed;
//if player collides with cube, move back and reset jump counters
if(asset_manager->checkCollision(position)){
jump1 = false;
jumplength = 0;
position.y+=(0.98-jumpspeed)*speed;
}
//where camera is looking
direction = glm::vec3(
cos(cameray) * sin(camerax),
sin(cameray),
cos(cameray) * cos(camerax)
);
mdirection = glm::vec3(
cos(cameray) * sin(camerax),
0,
cos(cameray) * cos(camerax)
);
vright = glm::vec3(
sin(camerax - 3.14f/2.0f),
0,
cos(camerax - 3.14f/2.0f)
);
//camera perspec
glm::vec3 vup = glm::cross (vright, direction);
//set up stuff to send to shader/ added 8/12
// Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f);
// Camera matrix
glm::mat4 View = glm::lookAt( //camera angle and location to send to shader
position, //location
position + direction, //location + camera angle
vup //camera perspective
);
// Model matrix : an identity matrix (model will be at the origin)
glm::mat4 Model = glm::mat4(1.0f);
// Our ModelViewProjection : multiplication of our 3 matrices
glm::mat4 MVP = Projection * View * Model; // Remember, matrix multiplication is the other way around
//send Projection, view and model to shader (new stuff)
glUniformMatrix4fv(proj_loc, 1, GL_FALSE, &Projection[0][0]);
glUniformMatrix4fv(view_loc, 1, GL_FALSE, &View[0][0]);
glUniformMatrix4fv(model_loc, 1, GL_FALSE, &Model[0][0]);
asset_manager->Draw();
}
| true |
99100ac83fb231dcad8473cee4945f3a1b09af0e | C++ | raxracks/chadOS | /userspace/libraries/libfilepicker/model/FilesystemModel.cpp | UTF-8 | 3,871 | 2.859375 | 3 | [
"MIT",
"BSD-2-Clause"
] | permissive | #include <string.h>
#include <libfilepicker/model/FilesystemModel.h>
#include <libio/File.h>
#include <libio/Format.h>
#include <libjson/Json.h>
namespace FilePicker
{
static auto get_icon_for_node(String current_directory, IO::Directory::Entry &entry)
{
if (entry.stat.type == HJ_FILE_TYPE_DIRECTORY)
{
auto manifest_path = IO::format("{}/{}/manifest.json", current_directory, entry.name);
IO::File manifest_file{manifest_path, HJ_OPEN_READ};
if (manifest_file.exist())
{
auto root = Json::parse(manifest_file);
if (root.is(Json::OBJECT))
{
auto icon_name = root.get("icon");
if (icon_name.is(Json::STRING))
{
return Graphic::Icon::get(icon_name.as_string());
}
}
}
return Graphic::Icon::get("folder");
}
else if (entry.stat.type == HJ_FILE_TYPE_PIPE ||
entry.stat.type == HJ_FILE_TYPE_DEVICE ||
entry.stat.type == HJ_FILE_TYPE_SOCKET)
{
return Graphic::Icon::get("pipe");
}
else if (entry.stat.type == HJ_FILE_TYPE_TERMINAL)
{
return Graphic::Icon::get("console-network");
}
else
{
return Graphic::Icon::get("file");
}
}
enum Column
{
COLUMN_NAME,
COLUMN_TYPE,
COLUMN_SIZE,
__COLUMN_COUNT,
};
FilesystemModel::FilesystemModel(RefPtr<Navigation> navigation, Func<bool(IO::Directory::Entry &)> filter)
: _navigation(navigation), _filter(filter)
{
_observer = navigation->observe([this](auto &) {
update();
});
update();
}
int FilesystemModel::rows()
{
return _files.count();
}
int FilesystemModel::columns()
{
return __COLUMN_COUNT;
}
String FilesystemModel::header(int column)
{
switch (column)
{
case COLUMN_NAME:
return "Name";
case COLUMN_TYPE:
return "Type";
case COLUMN_SIZE:
return "Size";
default:
ASSERT_NOT_REACHED();
}
}
Widget::Variant FilesystemModel::data(int row, int column)
{
auto &entry = _files[row];
switch (column)
{
case COLUMN_NAME:
return Widget::Variant(entry.name.cstring()).with_icon(entry.icon);
case COLUMN_TYPE:
switch (entry.type)
{
case HJ_FILE_TYPE_REGULAR:
return "Regular file";
case HJ_FILE_TYPE_DIRECTORY:
return "Directory";
case HJ_FILE_TYPE_DEVICE:
return "Device";
default:
return "Special file";
}
case COLUMN_SIZE:
if (entry.type == HJ_FILE_TYPE_DIRECTORY)
{
return Widget::Variant(IO::format("{} Items", entry.size));
}
else
{
return Widget::Variant(IO::format("{} Bytes", entry.size));
}
default:
ASSERT_NOT_REACHED();
}
}
void FilesystemModel::update()
{
_files.clear();
IO::Directory directory{_navigation->current()};
if (!directory.exist())
{
return;
}
for (auto entry : directory.entries())
{
if (_filter && !_filter(entry))
{
continue;
}
size_t size = entry.stat.size;
if (entry.stat.type == HJ_FILE_TYPE_DIRECTORY)
{
auto path = IO::Path::join(_navigation->current(), entry.name);
IO::Directory subdirectory{path};
size = subdirectory.entries().count();
}
FileInfo node{
.name = entry.name,
.type = entry.stat.type,
.icon = get_icon_for_node(_navigation->current().string(), entry),
.size = size,
};
_files.push_back(node);
}
did_update();
}
const FileInfo &FilesystemModel::info(int index) const
{
return _files[index];
}
} // namespace FilePicker | true |
e27a1e177bb96b4c1ea7704d674d9b2b8b600407 | C++ | Nada-ibrahim/Paint-Windows-API | /Filling.cpp | UTF-8 | 1,397 | 2.890625 | 3 | [] | no_license | //
// Created by hp on 4/10/2018.
//
#include "Filling.h"
#include "MyPoint.h"
#include <stack>
using namespace std;
void Filling::fillSeed(HDC hdc) {
stack<MyPoint> points;
points.push(MyPoint(xc,yc));
while(!points.empty()){
MyPoint p = points.top();
points.pop();
COLORREF c = GetPixel(hdc, p.x, p.y);
if(c == backColor){
SetPixel(hdc, p.x, p.y, fillColor);
points.push(MyPoint(p.x+1, p.y));
points.push(MyPoint(p.x, p.y+1));
points.push(MyPoint(p.x-1, p.y));
points.push(MyPoint(p.x, p.y-1));
}
}
}
Filling::Filling(int xc, int yc, COLORREF backColor, COLORREF fillColor) : xc(xc), yc(yc),
backColor(backColor), fillColor(fillColor){
}
void Filling::draw(HDC hdc) {
fillSeed(hdc);
}
void Filling::write(ofstream &out) {
out.write((char*)& xc, sizeof(int));
out.write((char*) &yc, sizeof(int));
out.write((char*) &fillColor, sizeof(fillColor));
out.write((char*) &backColor, sizeof(backColor));
}
void Filling::read(ifstream &in) {
in.read((char*)& xc, sizeof(int));
in.read((char*) &yc, sizeof(int));
in.read((char*) &fillColor, sizeof(fillColor));
in.read((char*) &backColor, sizeof(backColor));
}
Filling::Filling() {
}
| true |
a0c26e161a41afaae7bd9b55efb868ceb67558ac | C++ | ekandemir/CourseStudies | /BLG 233-Data Structures/Homeworks/HW1/main.cpp | UTF-8 | 820 | 2.5625 | 3 | [] | no_license | //
// main.cpp
// DataStrHomework1
//
// Created by Developing on 3.10.2017.
// Copyright © 2017 erdinckandemir. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main(int argc, const char * argv[]) {
//memory allocation for puzzle array
char ** puzzleArray = new char*[225];
for (int i=0; i < 15 ; i++) {
puzzleArray[i] = new char[15];
}
puzzleArray[3][5] = 'a';
cout << puzzleArray[3][5];
//open puzzle.txt to read
ifstream puzzle;
puzzle.open("puzzle.txt");
for (int i = 0; i<15; i++) {
for (int j = 0; j<15; j++) {
puzzle >> *(*(puzzleArray+i)+j);
}
}
cout<<puzzleArray[2][2];
getchar();
return 0;
}
| true |
311f667c7e5aaefc17a45184e4ec2afad807be5d | C++ | sccData/Data-structure-and-algorithm_self | /排序/快速排序/main.cpp | UTF-8 | 721 | 3.203125 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int partition(int a[], int p, int r)
{
int plot = a[r];
int i = p;
int temp = 0;
for(int j=p; j<r; ++j) {
if (a[j] < plot) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
++i;
}
}
a[r] = a[i];
a[i] = plot;
return i;
}
void quick_sort_c(int a[], int p, int r)
{
if(p >= r)
return;
int q = partition(a, p, r);
quick_sort_c(a, p, q-1);
quick_sort_c(a, q+1, r);
}
void quick_sort(int a[], int n)
{
quick_sort_c(a, 0, n-1);
}
int main()
{
int a[6] = {1, 4, 7, 3, 2, 5};
quick_sort(a, 6);
for(int i=0; i<6; ++i)
cout << a[i] << " ";
return 0;
} | true |
6e77962d06aac16061c5f3333dfc1738b93ed12c | C++ | lionkor/Volty | /include/Core/Application.h | UTF-8 | 1,703 | 2.625 | 3 | [
"MIT"
] | permissive | #ifndef APPLICATION_H
#define APPLICATION_H
#include <thread>
#include "GameWindow.h"
#include "Object.h"
#include "Rendering/GuiElement.h"
#include "Utils/DebugTools.h"
#include "Utils/Managed.h"
#include "Utils/Mutexed.h"
#include "Utils/ResourceManager.h"
#include "World.h"
namespace V {
class Application : public Object {
OBJNAME(Application)
private:
OwnPtr<GameWindow> m_window;
OwnPtr<World> m_world;
ResourceManager m_resource_manager;
std::vector<RefPtr<GuiElement>> m_gui_elements;
public:
/// \brief Application
/// \param title Title of the window
/// \param size Size of the window
/// \param res_file_path path for the res.list, empty for none
Application(const std::string& title, sf::Vector2u size, bool fullscreen = false, const std::string& res_file_path = "Data/res.list");
GameWindow& window() { return *m_window; }
const GameWindow& window() const { return *m_window; }
World& world() { return *m_world; }
const World& world() const { return *m_world; }
ResourceManager& resource_manager() { return m_resource_manager; }
const ResourceManager& resource_manager() const { return m_resource_manager; }
std::vector<RefPtr<GuiElement>>& gui_elements() { return m_gui_elements; }
template<typename... Args>
[[nodiscard]] WeakPtr<GuiElement> add_gui_element(Args&&... args);
[[nodiscard]] int run();
};
template<typename... Args>
[[nodiscard]] WeakPtr<GuiElement> Application::add_gui_element(Args&&... args) {
auto elem = make_refptr<GuiElement>(*this, std::forward<Args>(args)...);
m_gui_elements.push_back(elem);
return WeakPtr<GuiElement>(elem);
}
}
#endif // APPLICATION_H
| true |
664f34e6eaa532fb7b52b39cb2058b46653beda7 | C++ | mt1ger/LPS_SEG_SimSDM-EON | /ModulationFormats.cpp | UTF-8 | 7,079 | 2.578125 | 3 | [] | no_license | #include "ModulationFormats.h"
#include <cmath>
#include <iostream>
#include <string>
using namespace std;
/****************************************
* Options for Super Channels: 25 50 100 200 400
* Options for Modulation Formats:
* QPSK, 16QAM, 64QAM
****************************************/
unsigned int
ModulationFormats::spectralslots_computation(unsigned int bitsPerSymbol,
unsigned int bitRate)
{
unsigned int SpectralSlots;
SpectralSlots = ceil((double)bitRate / bitsPerSymbol / 12.5);
return SpectralSlots;
}
double
ModulationFormats::search_link_weight(unsigned int predecessor,
unsigned int successor)
{
return network->nodesWeight[predecessor][successor];
}
void
ModulationFormats::mf_chosen(vector<int> * shortestPath,
unsigned int *occupiedSpectralSlots,
unsigned int *bitRate, string *mF,
unsigned int *mFBitsperSignal)
{
double totalDist = 0; // distance of the lightpath
double dist = 0; // distance between two ajacent nodes
unsigned int spectralSlots_am; // SpectralSlots after modulation
/*** Compute the total distance from source to destination ***/
for(long unsigned int i = 1; i < shortestPath->size(); i++)
{
dist = search_link_weight(shortestPath->at(i - 1), shortestPath->at(i));
totalDist = totalDist + dist;
}
auto sC = *bitRate;
switch(sC)
{
case 25:
if(totalDist <= 22160)
{
this->mF = QPSK;
*mFBitsperSignal = 2;
spectralSlots_am = spectralslots_computation(*mFBitsperSignal, 25);
*mF = "QPSK";
}
else
{
this->mF = Failure;
*mFBitsperSignal = 0;
*mF = "Fail";
spectralSlots_am = 0;
}
break;
// case 50:
case 40:
if(totalDist > 4750 && totalDist <= 11080)
{
this->mF = QPSK;
*mFBitsperSignal = 2;
spectralSlots_am = spectralslots_computation(*mFBitsperSignal, 40);
*mF = "QPSK";
}
else if(totalDist > 1832 && totalDist <= 4750)
{
this->mF = QAM16;
*mFBitsperSignal = 4;
*mF = "16QAM";
spectralSlots_am = spectralslots_computation(*mFBitsperSignal, 40);
}
else if(totalDist <= 1832)
{
this->mF = QAM64;
*mFBitsperSignal = 6;
*mF = "64QAM";
spectralSlots_am = spectralslots_computation(*mFBitsperSignal, 40);
}
else
{
this->mF = Failure;
*mFBitsperSignal = 0;
*mF = "Fail";
spectralSlots_am = 0;
}
break;
case 50:
if(totalDist > 4750 && totalDist <= 11080)
{
this->mF = QPSK;
*mFBitsperSignal = 2;
spectralSlots_am = spectralslots_computation(*mFBitsperSignal, 50);
*mF = "QPSK";
}
else if(totalDist > 1832 && totalDist <= 4750)
{
this->mF = QAM16;
*mFBitsperSignal = 4;
*mF = "16QAM";
spectralSlots_am = spectralslots_computation(*mFBitsperSignal, 50);
}
else if(totalDist <= 1832)
{
this->mF = QAM64;
*mFBitsperSignal = 6;
*mF = "64QAM";
spectralSlots_am = spectralslots_computation(*mFBitsperSignal, 50);
}
else
{
this->mF = Failure;
*mFBitsperSignal = 0;
*mF = "Fail";
spectralSlots_am = 0;
}
break;
// case 75:
// if (TotalDist > 3166 && TotalDist <= 7387) {
// m_Format = QPSK;
// *mfTimes = 2;
// am_SpectralSlots = spectralslots_computation (*mfTimes, 75);
// *MF = "QPSK";
// }
// else if (TotalDist > 1221 && TotalDist <= 3166) {
// m_Format = QAM16;
// *mfTimes = 4a
// *MF = "16QAM";
// am_SpectralSlots = spectralslots_computation (*mfTimes, 75);
// }
// else if (TotalDist <= 1221) {
// m_Format = QAM64;
// *mfTimes = 6;
// *MF = "64QAM";
// am_SpectralSlots = spectralslots_computation (*mfTimes, 75);
// }
// break;
case 100:
if(totalDist > 2375 && totalDist <= 5540)
{
this->mF = QPSK;
*mFBitsperSignal = 2;
spectralSlots_am = spectralslots_computation(*mFBitsperSignal, 100);
*mF = "QPSK";
}
else if(totalDist > 916 && totalDist <= 2375)
{
this->mF = QAM16;
*mFBitsperSignal = 4;
*mF = "16QAM";
spectralSlots_am = spectralslots_computation(*mFBitsperSignal, 100);
}
else if(totalDist <= 916)
{
this->mF = QAM64;
*mFBitsperSignal = 6;
*mF = "64QAM";
spectralSlots_am = spectralslots_computation(*mFBitsperSignal, 100);
}
else
{
this->mF = Failure;
*mFBitsperSignal = 0;
*mF = "Fail";
spectralSlots_am = 0;
}
break;
case 200:
if(totalDist > 1187 && totalDist <= 2770)
{
this->mF = QPSK;
*mFBitsperSignal = 2;
spectralSlots_am = spectralslots_computation(*mFBitsperSignal, 200);
*mF = "QPSK";
}
else if(totalDist > 458 && totalDist <= 1187)
{
this->mF = QAM16;
*mFBitsperSignal = 4;
*mF = "16QAM";
spectralSlots_am = spectralslots_computation(*mFBitsperSignal, 200);
}
else if(totalDist <= 458)
{
this->mF = QAM64;
*mFBitsperSignal = 6;
*mF = "64QAM";
spectralSlots_am = spectralslots_computation(*mFBitsperSignal, 200);
}
else
{
this->mF = Failure;
*mFBitsperSignal = 0;
*mF = "Fail";
spectralSlots_am = 0;
}
break;
case 400:
if(totalDist > 594 && totalDist <= 1385)
{
this->mF = QPSK;
*mFBitsperSignal = 2;
spectralSlots_am = spectralslots_computation(*mFBitsperSignal, 400);
*mF = "QPSK";
}
else if(totalDist > 229 && totalDist <= 594)
{
this->mF = QAM16;
*mFBitsperSignal = 4;
*mF = "16QAM";
spectralSlots_am = spectralslots_computation(*mFBitsperSignal, 400);
}
else if(totalDist <= 229)
{
this->mF = QAM64;
*mFBitsperSignal = 6;
*mF = "64QAM";
spectralSlots_am = spectralslots_computation(*mFBitsperSignal, 400);
}
else
{
this->mF = Failure;
*mFBitsperSignal = 0;
*mF = "Fail";
spectralSlots_am = 0;
}
}
*occupiedSpectralSlots = spectralSlots_am;
}
| true |
8f1a9a1cd550db20e7cb412ba0fd06712ceea66d | C++ | shaocongliang/recipes | /thread/Mutex.h | UTF-8 | 532 | 2.59375 | 3 | [] | no_license | #include <pthread.h>
namespace liangsc{
class MutexLock{
public:
MutexLock():
lock_(PTHREAD_MUTEX_INITIALIZER){
}
void lock(){
pthread_mutex_lock(&lock_);
}
void unlock(){
pthread_mutex_unlock(&lock_);
}
~MutexLock(){ }
private:
pthread_mutex_t lock_;
};
class MutexLockGuard{
public:
MutexLockGuard(MutexLock &mutex):
mutex_(mutex){
mutex_.lock();
}
~MutexLockGuard(){
mutex_.unlock();
}
private:
MutexLock &mutex_;
};
#define MutexLockGuard(x) error : "missing guard object";
} | true |
d88255b7ee1ed0c36b608d6426615158bf8c2ab4 | C++ | chenghehe/C-Study | /04/03const修饰成员函数.cpp | GB18030 | 1,035 | 3.359375 | 3 | [] | no_license | //#include<iostream>
//
//using namespace std;
//
//
//class Person
//{
//public:
//
// //this ָ뱾 ָ볣 ָָDzĵ
// //const Person * const this
// //
// void showPerson() const {
// //this->m_A = 100; //
//
// this->m_B = 200; //
//
// //this = NULL; //thisָ벻ָָ
// }
//
// void func() {
// //m_A = 100;
// }
//
// int m_A;
// mutable int m_B; //ʹڳУҲֵ
//private:
//
//};
//
//int main() {
// //Person* p = NULL;
// //p->showName(); //ָԵóԱ
// //p->showAge(); //ָԵóԱóԱ
//
// const Person p;
//
// /// <summary>
// /// ֻܵó
// /// </summary>
// /// <returns></returns>
// p.showPerson();
// //p.func(); //ͨԱΪͨԱ
//
//
//
// system("pause");
//}
| true |
74ea88a4148eea8f886ce99d72bbb71d6e8c3737 | C++ | profeIMA/Exercicis-Programacio | /ExercicisT7/T7-EX1_1-assignaVector.cpp | UTF-8 | 1,003 | 3.90625 | 4 | [] | no_license | /*
1.1. Assignar a un vector d'n elements els successius nombres naturals (0, 1, 2, 3, ...). Retocar l'algorisme per tal que assigni els successius nombres naturals parells (0, 2, 4, 6, ...).
*/
#include <iostream>
using namespace std;
const unsigned N_MAX=100;
typedef int Vector_enter[N_MAX];
void assignar_vector_enter(Vector_enter vec_enter, unsigned n) {
//Pre: 0<=n<=N_MAX
//Post: vec_enter[0..n-1] conté successivament els naturals des de 0 a n-1
for(unsigned i=0; i<n; i++) vec_enter[i]=i;
}
void escriure_vector_enter(const Vector_enter vec_enter, unsigned n) {
//Pre: 0<=n<=N_MAX
//Post: s'han mostrat el n valors de vec_enter[0..n-1]
for(unsigned i=0; i<n; i++) cout<<vec_enter[i]<<" ";
}
int main() {
Vector_enter vec_enter;
int n;
cout<<"Nombre elements del vector: ";
cin>>n;
assignar_vector_enter(vec_enter,n);
cout<<"Vector obtingut: "<<endl;
escriure_vector_enter(vec_enter,n);
cout<<endl;
return 0;
} | true |
0c687c9c0093bb82c19782caa06d40f67d1b525d | C++ | rubu/AIEEE2015 | /Shared/InputFileLoader.hpp | UTF-8 | 1,779 | 2.9375 | 3 | [] | no_license | #pragma once
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
#include <Windows.h>
#include <sys/stat.h>
#include <sys/types.h>
class CInputFileLoader
{
public:
CInputFileLoader(const char* pInputFilename, unsigned int nWidth, unsigned int nHeight)
{
struct _stat64 FileStatistics;
if (_stat64(pInputFilename, &FileStatistics) != 0)
{
throw std::runtime_error(std::string("could not obtain size of the input file ").append(pInputFilename));
}
const unsigned int nFrameSize = nWidth * nHeight * 4;
if (FileStatistics.st_size % nFrameSize != 0)
{
throw std::runtime_error(std::string("the input file ").append(pInputFilename).append(" does not contain an even number of ").append(std::to_string(nWidth)).append("x").append(std::to_string(nHeight)).append(" RGB32 frames"));
}
m_nFrameCount = static_cast<unsigned int>(FileStatistics.st_size / nFrameSize);
FILE* pInputFile = nullptr;
if (fopen_s(&pInputFile, pInputFilename, "rb") == 0)
{
unsigned int nFrameIndex = 0;
while (nFrameIndex++ < m_nFrameCount)
{
std::unique_ptr<unsigned char[]> pFrame(new unsigned char[nFrameSize]);
if (fread(pFrame.get(), 1, nFrameSize, pInputFile) != nFrameSize)
{
throw std::runtime_error(std::string("could not read a full frame from the input file ").append(pInputFilename));
}
m_Frames.push_back(std::move(pFrame));
}
}
else
{
throw std::runtime_error(std::string("could not open the input file ").append(pInputFilename));
}
}
const std::vector<std::unique_ptr<unsigned char[]>>& GetFrames()
{
return m_Frames;
}
unsigned int GetFrameCount()
{
return m_nFrameCount;
}
private:
unsigned int m_nFrameCount = 0;
std::vector<std::unique_ptr<unsigned char[]>> m_Frames;
}; | true |
504cf3d4f71f5895db81fca17fedfd2fb19af606 | C++ | uwejanssen19/esp8266 | /GxEPD2_files/GxEPD2_MinimumExample/GxEPD2_MinimumExample.ino | UTF-8 | 1,367 | 2.578125 | 3 | [] | no_license | // GxEPD2_MinimumExample.ino by Jean-Marc Zingg
// purpose is e.g. to determine minimum code and ram use by this library
// see GxEPD2_wiring_examples.h of GxEPD2_Example for wiring suggestions and examples
// if you use a different wiring, you need to adapt the constructor parameters!
// uncomment next line to use class GFX of library GFX_Root instead of Adafruit_GFX, to use less code and ram
//#include <GFX.h>
#include <GxEPD2_BW.h> // including both doesn't use more code or ram
#include <GxEPD2_3C.h> // including both doesn't use more code or ram
// select the display class and display driver class in the following file (new style):
#include "GxEPD2_display_selection_new_style.h"
// alternately you can copy the constructor from GxEPD2_display_selection.h or GxEPD2_display_selection_added.h of GxEPD2_Example to here
// e.g. for Wemos D1 mini:
//GxEPD2_BW<GxEPD2_154_D67, GxEPD2_154_D67::HEIGHT> display(GxEPD2_154_D67(/*CS=D8*/ SS, /*DC=D3*/ 0, /*RST=D4*/ 2, /*BUSY=D2*/ 4)); // GDEH0154D67
void setup()
{
display.init();
// comment out next line to have no or minimal Adafruit_GFX code
display.setTextColor(GxEPD_BLACK);
display.firstPage();
do
{
display.fillScreen(GxEPD_WHITE);
// comment out next line to have no or minimal Adafruit_GFX code
display.print("Hello World!");
}
while (display.nextPage());
}
void loop() {};
| true |
baa17ccbd8504af9116e58dc8fa489185871f0de | C++ | tejasMadrewar/CPP_notes | /4_class_objects/ex_func_friendly_to_two_classes.cpp | UTF-8 | 605 | 3.796875 | 4 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
class ABC; // forward declaration
class XYZ{
int x;
public:
void setvalue(int i){x = i;}
friend void max(XYZ,ABC); // friend function is declare
};
class ABC{
int a;
public:
void setvalue(int i){a = i;}
friend void max(XYZ,ABC); // friend function is declare
};
void max(XYZ m, ABC n){ // function is friend to two classes
if (m.x >= n.a) {
cout << m.x;
}
else
cout << n.a;
}
int main()
{
ABC abc;
abc.setvalue(10);
XYZ xyz;
xyz.setvalue(20);
max(xyz,abc); // pass both objects
return 0;
}
| true |
f84343251a4c86ac5f716515f36385b2b5198283 | C++ | ibetovski/learning-cplusplus | /src/0012-03-initialization-list.cpp | UTF-8 | 826 | 3.625 | 4 | [] | no_license | // Using Initialization list for setting class private property
#include <iostream>
using namespace std;
class Foo {
public:
// this is the same as: Foo() { _blah = "dodo"; }
Foo(): _blah("dodo") {}
void getBlah();
private:
std::string _blah;
};
void Foo::getBlah() {
cout << _blah;
}
// for more fields:
class Bar {
public:
Bar(): _blah1("dodo1"), _koko("dodo2") {}
private:
std::string _koko;
std::string _blah1;
};
// Having property name which name is the same as the constructor's argument:
class Baz {
public:
Baz(std::string foo): foo(foo) {}
void getFoo();
private:
std::string foo;
};
void Baz::getFoo() {
cout << "foo is: " << foo << endl;
cout << "this->foo is: " << this->foo << endl;
}
int main() {
Foo foo;
foo.getBlah();
Bar bar;
Baz baz("shalalala");
baz.getFoo();
}
| true |
5a6bc7b4281644498bf9144c1f8c758367b412c7 | C++ | zlatkos94/adr-seminarski | /Caja/Caja/Source.cpp | WINDOWS-1250 | 2,694 | 2.984375 | 3 | [] | no_license | #include <complex>
#include <iostream>
#include <valarray>
#include<time.h>
#include<thread>
#include "../mjerenje.h"
#include "../loading.h"
using namespace std;
double PI = 3.141592653589793238460;
const int num_threads = 4;
typedef std::complex<double> Complex;
typedef std::valarray<Complex> CArray;
int redak, stupac;
// CooleyTukey FFT (in-place, divide-and-conquer)
// Higher memory requirements and redundancy although more intuitive
void fft(CArray &x)
{
const int N = x.size();
if (N <= 1) return;
// divide
CArray even = x[slice(0, N / 2, 2)];
CArray odd = x[slice(1, N / 2, 2)];
// conquer
fft(even);
fft(odd);
// combine
for (int k = 0; k < N / 2; ++k)
{
Complex t = std::polar(1.0, -2 * PI * k / N) * odd[k];
x[k] = even[k] + t;
x[k + N / 2] = even[k] - t;
}
}
void fftP(CArray &x, int poc, int kraj)
{
const int N = x.size();
if (N <= 1) return;
// divide
CArray even = x[slice(0, N / 2, 2)];
CArray odd = x[slice(1, N / 2, 2)];
// conquer
fft(even);
fft(odd);
// combine
for (int k = poc; k < kraj; ++k)
{
Complex t = std::polar(1.0, -2 * PI * k / N) * odd[k];
x[k] = even[k] + t;
x[k + N / 2] = even[k] - t;
}
}
int main()
{
Complex *test = NULL;
srand(time(NULL));
int dim;
printf("Koliko brojeva zelite ?\n");
scanf("%d",&dim);
test=(Complex*)malloc(dim*sizeof(Complex));
for (int i = 0; i < dim; i++)
{
test[i]=rand()%10;
}
double wall1 = get_wall_time();//Poetak mjerenja
CArray data(test, dim);
// forward fft
fft(data);
std::cout << "fft" << std::endl;
for (int i = 0; i < dim; ++i)
{
std::cout << data[i] << std::endl;
}
double wall2 = get_wall_time();//Zavretak mjerenja
printf("\nVrijeme izvodenja sekvencijalno %lf s\n", wall2 - wall1);
printf("-------------------------------------------------------------------------------------\n");
printf("paralelno\n");
wall1 = get_wall_time();//Poetak mjerenja
CArray data2(test, dim);
std::thread t[num_threads];
for (int i = 0;i<num_threads;i++)
{
int poc, kraj, korak;
if (i<num_threads - 1)
{
korak = redak / num_threads;
poc = i * korak;
kraj = poc + korak;
t[i] = std::thread( fftP, data2,poc,kraj);
}
else // za neparne dimenzije
{
korak = redak / num_threads;
poc = i * korak;
kraj = poc + korak + redak % num_threads;
t[i] = std::thread(fftP , data2,poc,kraj);
}
}
for (int i = 0;i<num_threads;i++)
t[i].join();
wall2 = get_wall_time();//Zavretak mjerenja
printf("\nVrijeme izvodenja paralelno %lf s\n", wall2 - wall1);
system("pause");
return 0;
} | true |
e32fa5e95c634e8b8affe68ffc1fcfdf5030628e | C++ | iesahin/TurkishMorphologicalAnalysis-CPP | /FsmMorphologicalAnalyzer.cpp | UTF-8 | 56,466 | 3.03125 | 3 | [] | no_license | //
// Created by Olcay Taner Yıldız on 2.03.2019.
//
#include <regex>
#include <iostream>
#include "FsmMorphologicalAnalyzer.h"
/**
* Another constructor of FsmMorphologicalAnalyzer class. It generates a new TxtDictionary type dictionary from
* given input dictionary, with given inputs fileName and cacheSize.
*
* @param fileName the file to read the finite state machine.
* @param dictionary the dictionary file that will be used to generate dictionaryTrie.
* @param cacheSize the size of the LRUCache.
*/
FsmMorphologicalAnalyzer::FsmMorphologicalAnalyzer(string fileName, TxtDictionary dictionary, int cacheSize) {
finiteStateMachine = FiniteStateMachine(move(fileName));
dictionaryTrie = dictionary.prepareTrie();
dictionary = move(dictionary);
cache = LRUCache<string, FsmParseList>(cacheSize);
}
/**
* Another constructor of FsmMorphologicalAnalyzer class. It generates a new TxtDictionary type dictionary from
* given input dictionary file name and by using turkish_finite_state_machine.xml file.
*
* @param fileName the file to read the finite state machine.
* @param dictionaryFileName the file to read the dictionary.
*/
FsmMorphologicalAnalyzer::FsmMorphologicalAnalyzer(string dictionaryFileName, string fileName) : FsmMorphologicalAnalyzer(move(fileName), TxtDictionary(move(dictionaryFileName), Comparator::TURKISH, "turkish_misspellings.txt")){
}
/**
* The getDictionary method is used to get TxtDictionary.
*
* @return TxtDictionary type dictionary.
*/
TxtDictionary FsmMorphologicalAnalyzer::getDictionary() {
return dictionary;
}
/**
* The getFiniteStateMachine method is used to get FiniteStateMachine.
*
* @return FiniteStateMachine type finiteStateMachine.
*/
FiniteStateMachine FsmMorphologicalAnalyzer::getFiniteStateMachine() {
return finiteStateMachine;
}
/**
* The getPossibleWords method takes {@link MorphologicalParse} and {@link MetamorphicParse} as input.
* First it determines whether the given morphologicalParse is the root verb and whether it contains a verb tag.
* Then it creates new transition with -mak and creates a new {@link HashSet} result.
* <p>
* It takes the given {@link MetamorphicParse} input as currentWord and if there is a compound word starting with the
* currentWord, it gets this compoundWord from dictionaryTrie. If there is a compoundWord and the difference of the
* currentWord and compundWords is less than 3 than compoundWord is added to the result, otherwise currentWord is added.
* <p>
* Then it gets the root from parse input as a currentRoot. If it is not null, and morphologicalParse input is verb,
* it directly adds the verb to result after making transition to currentRoot with currentWord String. Else, it creates a new
* transition with -lar and make this transition then adds to the result.
*
* @param morphologicalParse {@link MorphologicalParse} type input.
* @param parse {@link MetamorphicParse} type input.
* @return {@link HashSet} result.
*/
unordered_set<string>
FsmMorphologicalAnalyzer::getPossibleWords(MorphologicalParse morphologicalParse, MetamorphicParse parse) {
bool isRootVerb = morphologicalParse.getRootPos() == "VERB";
bool containsVerb = morphologicalParse.containsTag(MorphologicalTag::VERB);
Transition verbTransition = Transition("mAk");
TxtWord* compoundWord;
TxtWord* currentRoot;
unordered_set<string> result;
if (parse.getWord().getName().empty()) {
return result;
}
string verbWord, pluralWord, currentWord = parse.getWord().getName();
int pluralIndex = -1;
compoundWord = dictionaryTrie->getCompoundWordStartingWith(currentWord);
if (!isRootVerb) {
if (Word::size(compoundWord->getName()) - Word::size(currentWord) < 3) {
result.emplace(compoundWord->getName());
}
result.emplace(currentWord);
}
currentRoot = (TxtWord*) dictionary.getWord(parse.getWord().getName());
if (currentRoot == nullptr && compoundWord != nullptr) {
currentRoot = compoundWord;
}
if (currentRoot != nullptr) {
if (isRootVerb) {
verbWord = verbTransition.makeTransition(currentRoot, currentWord);
result.emplace(verbWord);
}
pluralWord = "";
for (int i = 1; i < parse.size(); i++) {
Transition transition = Transition(State(), parse.getMetaMorpheme(i), "");
if (parse.getMetaMorpheme(i) == "lAr") {
pluralWord = currentWord;
pluralIndex = i + 1;
}
currentWord = transition.makeTransition(currentRoot, currentWord);
result.emplace(currentWord);
if (containsVerb) {
verbWord = verbTransition.makeTransition(currentRoot, currentWord);
result.emplace(verbWord);
}
}
if (!pluralWord.empty()) {
currentWord = pluralWord;
for (int i = pluralIndex; i < parse.size(); i++) {
Transition transition = Transition(State(), parse.getMetaMorpheme(i), "");
currentWord = transition.makeTransition(currentRoot, currentWord);
result.emplace(currentWord);
if (containsVerb) {
verbWord = verbTransition.makeTransition(currentRoot, currentWord);
result.emplace(verbWord);
}
}
}
}
return result;
}
/**
* The isPossibleSubstring method first checks whether given short and long strings are equal to root word.
* Then, compares both short and long strings' chars till the last two chars of short string. In the presence of mismatch,
* false is returned. On the other hand, it counts the distance between two strings until it becomes greater than 2,
* which is the MAX_DISTANCE also finds the index of the last char.
* <p>
* If the substring is a rootWord and equals to 'ben', which is a special case or root holds the lastIdropsDuringSuffixation or
* lastIdropsDuringPassiveSuffixation conditions, then it returns true if distance is not greater than MAX_DISTANCE.
* <p>
* On the other hand, if the shortStrong ends with one of these chars 'e, a, p, ç, t, k' and 't 's a rootWord with
* the conditions of rootSoftenDuringSuffixation, vowelEChangesToIDuringYSuffixation, vowelAChangesToIDuringYSuffixation
* or endingKChangesIntoG then it returns true if the last index is not equal to 2 and distance is not greater than
* MAX_DISTANCE and false otherwise.
*
* @param shortString the possible substring.
* @param longString the long string to compare with substring.
* @param root the root of the long string.
* @return true if given substring is the actual substring of the longString, false otherwise.
*/
bool FsmMorphologicalAnalyzer::isPossibleSubstring(const string& shortString, const string& longString, TxtWord *root) {
bool rootWord = (shortString == root->getName() || longString == root->getName());
int distance = 0, j, last = 1;
for (j = 0; j < Word::size(shortString); j++) {
if (Word::charAt(shortString, j) != Word::charAt(longString, j)) {
if (j < Word::size(shortString) - 2) {
return false;
}
last = Word::size(shortString) - j;
distance++;
if (distance > MAX_DISTANCE) {
break;
}
}
}
if (rootWord && (root->getName() == "ben" || root->lastIdropsDuringSuffixation() || root->lastIdropsDuringPassiveSuffixation())) {
return (distance <= MAX_DISTANCE);
} else {
if (Word::lastChar(shortString) == "e" || Word::lastChar(shortString) == "a" || Word::lastChar(shortString) == "p" || Word::lastChar(shortString) == "ç" || Word::lastChar(shortString) == "t" || Word::lastChar(shortString) == "k" || (rootWord && (root->rootSoftenDuringSuffixation() || root->vowelEChangesToIDuringYSuffixation() || root->vowelAChangesToIDuringYSuffixation() || root->endingKChangesIntoG()))) {
return (last != 2 && distance <= MAX_DISTANCE - 1);
} else {
return (distance <= MAX_DISTANCE - 2);
}
}
}
/**
* The initializeParseList method initializes the given given fsm ArrayList with given root words by parsing them.
* <p>
* It checks many conditions;
* isPlural; if root holds the condition then it gets the state with the name of NominalRootPlural, then
* creates a new parsing and adds this to the input fsmParse Arraylist.
* Ex : Açıktohumlular
* <p>
* !isPlural and isPortmanteauEndingWithSI, if root holds the conditions then it gets the state with the
* name of NominalRootNoPossesive.
* Ex : Balarısı
* <p>
* !isPlural and isPortmanteau, if root holds the conditions then it gets the state with the name of
* CompoundNounRoot.
* Ex : Aslanağızı
* <p>
* !isPlural, !isPortmanteau and isHeader, if root holds the conditions then it gets the state with the
* name of HeaderRoot.
* Ex : </title>
* <p>
* !isPlural, !isPortmanteau and isInterjection, if root holds the conditions then it gets the state
* with the name of InterjectionRoot.
* Ex : Hey, Aa
* <p>
* !isPlural, !isPortmanteau and isDuplicate, if root holds the conditions then it gets the state
* with the name of DuplicateRoot.
* Ex : Allak,
* <p>
* !isPlural, !isPortmanteau and isNumeral, if root holds the conditions then it gets the state
* with the name of CardinalRoot.
* Ex : Yüz, bin
* <p>
* !isPlural, !isPortmanteau and isReal, if root holds the conditions then it gets the state
* with the name of RealRoot.
* Ex : 1.2
* <p>
* !isPlural, !isPortmanteau and isFraction, if root holds the conditions then it gets the state
* with the name of FractionRoot.
* Ex : 1/2
* <p>
* !isPlural, !isPortmanteau and isDate, if root holds the conditions then it gets the state
* with the name of DateRoot.
* Ex : 11/06/2018
* <p>
* !isPlural, !isPortmanteau and isPercent, if root holds the conditions then it gets the state
* with the name of PercentRoot.
* Ex : %12.5
* <p>
* !isPlural, !isPortmanteau and isRange, if root holds the conditions then it gets the state
* with the name of RangeRoot.
* Ex : 3-5
* <p>
* !isPlural, !isPortmanteau and isTime, if root holds the conditions then it gets the state
* with the name of TimeRoot.
* Ex : 13:16:08
* <p>
* !isPlural, !isPortmanteau and isOrdinal, if root holds the conditions then it gets the state
* with the name of OrdinalRoot.
* Ex : Altıncı
* <p>
* !isPlural, !isPortmanteau, and isVerb if root holds the conditions then it gets the state
* with the name of VerbalRoot. Or isPassive, then it gets the state with the name of PassiveHn.
* Ex : Anla (!isPAssive)
* Ex : Çağrıl (isPassive)
* <p>
* !isPlural, !isPortmanteau and isPronoun, if root holds the conditions then it gets the state
* with the name of PronounRoot. There are 6 different Pronoun state names, REFLEX, QUANT, QUANTPLURAL, DEMONS, PERS, QUES.
* REFLEX = Reflexive Pronouns Ex : kendi
* QUANT = Quantitative Pronouns Ex : öbür, hep, kimse, hiçbiri, bazı, kimi, biri
* QUANTPLURAL = Quantitative Plural Pronouns Ex : tümü, çoğu, hepsi
* DEMONS = Demonstrative Pronouns Ex : o, bu, şu
* PERS = Personal Pronouns Ex : ben, sen, o, biz, siz, onlar
* QUES = Interrogatıve Pronouns Ex : nere, ne, kim, hangi
* <p>
* !isPlural, !isPortmanteau and isAdjective, if root holds the conditions then it gets the state
* with the name of AdjectiveRoot.
* Ex : Absürt, Abes
* <p>
* !isPlural, !isPortmanteau and isPureAdjective, if root holds the conditions then it gets the state
* with the name of Adjective.
* Ex : Geçmiş, Cam
* <p>
* !isPlural, !isPortmanteau and isNominal, if root holds the conditions then it gets the state
* with the name of NominalRoot.
* Ex : Görüş
* <p>
* !isPlural, !isPortmanteau and isProper, if root holds the conditions then it gets the state
* with the name of ProperRoot.
* Ex : Abdi
* <p>
* !isPlural, !isPortmanteau and isQuestion, if root holds the conditions then it gets the state
* with the name of QuestionRoot.
* Ex : Mi, mü
* <p>
* !isPlural, !isPortmanteau and isDeterminer, if root holds the conditions then it gets the state
* with the name of DeterminerRoot.
* Ex : Çok, bir
* <p>
* !isPlural, !isPortmanteau and isConjunction, if root holds the conditions then it gets the state
* with the name of ConjunctionRoot.
* Ex : Ama , ancak
* <p>
* !isPlural, !isPortmanteau and isPostP, if root holds the conditions then it gets the state
* with the name of PostP.
* Ex : Ait, dair
* <p>
* !isPlural, !isPortmanteau and isAdverb, if root holds the conditions then it gets the state
* with the name of AdverbRoot.
* Ex : Acilen
*
* @param fsmParse ArrayList to initialize.
* @param root word to check properties and add to fsmParse according to them.
* @param isProper is used to check a word is proper or not.
*/
void FsmMorphologicalAnalyzer::initializeParseList(vector<FsmParse>& fsmParse, TxtWord *root, bool isProper) {
FsmParse currentFsmParse;
if (root->isPlural()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("NominalRootPlural"));
fsmParse.push_back(currentFsmParse);
} else {
if (root->isPortmanteauEndingWithSI()) {
currentFsmParse = FsmParse(Word::substringExceptLastTwoChars(root->getName()), finiteStateMachine.getState("CompoundNounRoot"));
fsmParse.push_back(currentFsmParse);
currentFsmParse = FsmParse(root, finiteStateMachine.getState("NominalRootNoPossesive"));
fsmParse.push_back(currentFsmParse);
} else {
if (root->isPortmanteau()) {
if (root->isPortmanteauFacedVowelEllipsis()){
currentFsmParse = FsmParse(root, finiteStateMachine.getState("NominalRootNoPossesive"));
fsmParse.push_back(currentFsmParse);
currentFsmParse = FsmParse(Word::substringExceptLastTwoChars(root->getName()) + Word::lastChar(root->getName()) + Word::charAt(root->getName(), Word::size(root->getName()) - 2), finiteStateMachine.getState("CompoundNounRoot"));
} else {
if (root->isPortmanteauFacedSoftening()){
currentFsmParse = FsmParse(root, finiteStateMachine.getState("NominalRootNoPossesive"));
fsmParse.push_back(currentFsmParse);
string lastBefore = Word::charAt(root->getName(), Word::size(root->getName()) - 2);
if (lastBefore == "b"){
currentFsmParse = FsmParse(Word::substringExceptLastTwoChars(root->getName()) + "p", finiteStateMachine.getState("CompoundNounRoot"));
} else {
if (lastBefore == "c"){
currentFsmParse = FsmParse(Word::substringExceptLastTwoChars(root->getName()) + "ç", finiteStateMachine.getState("CompoundNounRoot"));
} else {
if (lastBefore == "d"){
currentFsmParse = FsmParse(Word::substringExceptLastTwoChars(root->getName()) + "t", finiteStateMachine.getState("CompoundNounRoot"));
} else {
if (lastBefore == "ğ"){
currentFsmParse = FsmParse(Word::substringExceptLastTwoChars(root->getName()) + "k", finiteStateMachine.getState("CompoundNounRoot"));
} else {
currentFsmParse = FsmParse(Word::substringExceptLastChar(root->getName()), finiteStateMachine.getState("CompoundNounRoot"));
}
}
}
}
} else {
currentFsmParse = FsmParse(Word::substringExceptLastChar(root->getName()), finiteStateMachine.getState("CompoundNounRoot"));
}
}
fsmParse.push_back(currentFsmParse);
} else {
if (root->isHeader()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("HeaderRoot"));
fsmParse.push_back(currentFsmParse);
}
if (root->isInterjection()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("InterjectionRoot"));
fsmParse.push_back(currentFsmParse);
}
if (root->isDuplicate()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("DuplicateRoot"));
fsmParse.push_back(currentFsmParse);
}
if (root->isNumeral()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("CardinalRoot"));
fsmParse.push_back(currentFsmParse);
}
if (root->isReal()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("RealRoot"));
fsmParse.push_back(currentFsmParse);
}
if (root->isFraction()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("FractionRoot"));
fsmParse.push_back(currentFsmParse);
}
if (root->isDate()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("DateRoot"));
fsmParse.push_back(currentFsmParse);
}
if (root->isPercent()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("PercentRoot"));
fsmParse.push_back(currentFsmParse);
}
if (root->isRange()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("RangeRoot"));
fsmParse.push_back(currentFsmParse);
}
if (root->isTime()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("TimeRoot"));
fsmParse.push_back(currentFsmParse);
}
if (root->isOrdinal()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("OrdinalRoot"));
fsmParse.push_back(currentFsmParse);
}
if (root->isVerb() || root->isPassive()) {
if (!root->verbType().empty()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("VerbalRoot(" + root->verbType() + ")"));
} else {
if (!root->isPassive()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("VerbalRoot"));
} else {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("PassiveHn"));
}
}
fsmParse.push_back(currentFsmParse);
}
if (root->isPronoun()) {
if (root->getName() == "kendi") {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("PronounRoot(REFLEX)"));
fsmParse.push_back(currentFsmParse);
}
if (root->getName() == "öbür" || root->getName() == "öteki" || root->getName() == "hep" || root->getName() == "kimse" || root->getName() == "diğeri" || root->getName() == "hiçbiri" || root->getName() == "böylesi" || root->getName() == "birbiri" || root->getName() == "birbirleri" || root->getName() == "biri" || root->getName() == "başkası" || root->getName() == "bazı" || root->getName() == "kimi") {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("PronounRoot(QUANT)"));
fsmParse.push_back(currentFsmParse);
}
if (root->getName() == "tümü" || root->getName() == "topu" || root->getName() == "herkes" || root->getName() == "cümlesi" || root->getName() == "çoğu" || root->getName() == "birçoğu" || root->getName() == "birkaçı" || root->getName() == "birçokları" || root->getName() == "hepsi") {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("PronounRoot(QUANTPLURAL)"));
fsmParse.push_back(currentFsmParse);
}
if (root->getName() == "o" || root->getName() == "bu" || root->getName() == "şu") {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("PronounRoot(DEMONS)"));
fsmParse.push_back(currentFsmParse);
}
if (root->getName() == "ben" || root->getName() == "sen" || root->getName() == "o" || root->getName() == "biz" || root->getName() == "siz" || root->getName() == "onlar") {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("PronounRoot(PERS)"));
fsmParse.push_back(currentFsmParse);
}
if (root->getName() == "nere" || root->getName() == "ne" || root->getName() == "kaçı" || root->getName() == "kim" || root->getName() == "hangi") {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("PronounRoot(QUES)"));
fsmParse.push_back(currentFsmParse);
}
}
if (root->isAdjective()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("AdjectiveRoot"));
fsmParse.push_back(currentFsmParse);
}
if (root->isPureAdjective()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("Adjective"));
fsmParse.push_back(currentFsmParse);
}
if (root->isNominal()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("NominalRoot"));
fsmParse.push_back(currentFsmParse);
}
if (root->isAbbreviation()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("NominalRoot"));
fsmParse.push_back(currentFsmParse);
}
if (root->isProperNoun() && isProper) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("ProperRoot"));
fsmParse.push_back(currentFsmParse);
}
if (root->isQuestion()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("QuestionRoot"));
fsmParse.push_back(currentFsmParse);
}
if (root->isDeterminer()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("DeterminerRoot"));
fsmParse.push_back(currentFsmParse);
}
if (root->isConjunction()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("ConjunctionRoot"));
fsmParse.push_back(currentFsmParse);
}
if (root->isPostP()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("PostP"));
fsmParse.push_back(currentFsmParse);
}
if (root->isAdverb()) {
currentFsmParse = FsmParse(root, finiteStateMachine.getState("AdverbRoot"));
fsmParse.push_back(currentFsmParse);
}
}
}
}
}
/**
* The initializeParseListFromRoot method is used to create an {@link ArrayList} which consists of initial fsm parsings. First, traverses
* this HashSet and uses each word as a root and calls initializeParseList method with this root and ArrayList.
* <p>
*
* @param parseList ArrayList to initialize.
* @param root the root form to generate initial parse list.
* @param isProper is used to check a word is proper or not.
*/
void FsmMorphologicalAnalyzer::initializeParseListFromRoot(vector<FsmParse>& parseList, TxtWord *root, bool isProper) {
initializeParseList(parseList, root, isProper);
if (root->obeysAndNotObeysVowelHarmonyDuringAgglutination()){
TxtWord* newRoot = root->clone();
newRoot->removeFlag("IS_UU");
newRoot->removeFlag("IS_UUU");
initializeParseList(parseList, newRoot, isProper);
}
if (root->rootSoftenAndNotSoftenDuringSuffixation()){
TxtWord* newRoot = root->clone();
newRoot->removeFlag("IS_SD");
newRoot->removeFlag("IS_SDD");
initializeParseList(parseList, newRoot, isProper);
}
if (root->lastIDropsAndNotDropDuringSuffixation()){
TxtWord* newRoot = root->clone();
newRoot->removeFlag("IS_UD");
newRoot->removeFlag("IS_UDD");
initializeParseList(parseList, newRoot, isProper);
}
if (root->duplicatesAndNotDuplicatesDuringSuffixation()){
TxtWord* newRoot = root->clone();
newRoot->removeFlag("IS_ST");
newRoot->removeFlag("IS_STT");
initializeParseList(parseList, newRoot, isProper);
}
if (root->endingKChangesIntoG() && root->containsFlag("IS_OA")){
TxtWord* newRoot = root->clone();
newRoot->removeFlag("IS_OA");
initializeParseList(parseList, newRoot, isProper);
}
}
/**
* The initializeRootList method is used to create an {@link ArrayList} which consists of initial fsm parsings. First,
* it calls getWordsWithPrefix methods by using input String surfaceForm and generates a {@link HashSet}. Then, traverses
* this HashSet and uses each word as a root and calls initializeParseList method with this root and ArrayList.
* <p>
*
* @param surfaceForm the String used to generate a HashSet of words.
* @param isProper is used to check a word is proper or not.
* @return initialFsmParse ArrayList.
*/
vector<FsmParse> FsmMorphologicalAnalyzer::initializeParseListFromSurfaceForm(const string& surfaceForm, bool isProper) {
TxtWord* root;
vector<FsmParse> initialFsmParse;
if (surfaceForm.empty()) {
return initialFsmParse;
}
unordered_set<Word*> words = dictionaryTrie->getWordsWithPrefix(surfaceForm);
for (Word* word : words) {
root = (TxtWord*) word;
initializeParseListFromRoot(initialFsmParse, root, isProper);
}
return initialFsmParse;
}
/**
* The addNewParsesFromCurrentParse method initially gets the final suffixes from input currentFsmParse called as currentState,
* and by using the currentState information it gets the new analysis. Then loops through each currentState's transition.
* If the currentTransition is possible, it makes the transition
*
* @param currentFsmParse FsmParse type input.
* @param fsmParse an ArrayList of FsmParse.
* @param surfaceForm String to use during transition.
* @param root TxtWord used to make transition.
*/
void FsmMorphologicalAnalyzer::addNewParsesFromCurrentParse(FsmParse currentFsmParse, vector<FsmParse>& fsmParse,
int maxLength, TxtWord *root) {
State currentState = currentFsmParse.getFinalSuffix();
string currentSurfaceForm = currentFsmParse.getSurfaceForm();
for (Transition currentTransition : finiteStateMachine.getTransitions(currentState)) {
if (currentTransition.transitionPossible(currentFsmParse) && (currentSurfaceForm != root->getName() || (currentSurfaceForm == root->getName() && currentTransition.transitionPossible(root, currentState)))) {
string tmp = currentTransition.makeTransition(root, currentSurfaceForm, currentFsmParse.getStartState());
if (Word::size(tmp) <= maxLength) {
FsmParse newFsmParse = currentFsmParse.clone();
newFsmParse.addSuffix(currentTransition.getToState(), tmp, currentTransition.getWith(), currentTransition.to_String(), currentTransition.getToPos());
newFsmParse.setAgreement(currentTransition.getWith());
fsmParse.push_back(newFsmParse);
}
}
}
}
/**
* The addNewParsesFromCurrentParse method initially gets the final suffixes from input currentFsmParse called as currentState,
* and by using the currentState information it gets the currentSurfaceForm. Then loops through each currentState's transition.
* If the currentTransition is possible, it makes the transition
*
* @param currentFsmParse FsmParse type input.
* @param fsmParse an ArrayList of FsmParse.
* @param surfaceForm String to use during transition.
* @param root TxtWord used to make transition.
*/
void FsmMorphologicalAnalyzer::addNewParsesFromCurrentParse(FsmParse currentFsmParse, vector<FsmParse>& fsmParse,
const string& surfaceForm, TxtWord *root) {
State currentState = currentFsmParse.getFinalSuffix();
string currentSurfaceForm = currentFsmParse.getSurfaceForm();
for (Transition currentTransition : finiteStateMachine.getTransitions(currentState)) {
if (currentTransition.transitionPossible(currentFsmParse.getSurfaceForm(), surfaceForm) && currentTransition.transitionPossible(currentFsmParse) && (currentSurfaceForm != root->getName() || (currentSurfaceForm == root->getName() && currentTransition.transitionPossible(root, currentState)))) {
string tmp = currentTransition.makeTransition(root, currentSurfaceForm, currentFsmParse.getStartState());
if ((Word::size(tmp) < Word::size(surfaceForm) && isPossibleSubstring(tmp, surfaceForm, root)) || (Word::size(tmp) == Word::size(surfaceForm) && (root->lastIdropsDuringSuffixation() || (tmp == surfaceForm)))) {
FsmParse newFsmParse = currentFsmParse.clone();
newFsmParse.addSuffix(currentTransition.getToState(), tmp, currentTransition.getWith(), currentTransition.to_String(), currentTransition.getToPos());
newFsmParse.setAgreement(currentTransition.getWith());
fsmParse.push_back(newFsmParse);
}
}
}
}
/**
* The parseExists method is used to check the existence of the parse.
*
* @param fsmParse an ArrayList of FsmParse
* @param surfaceForm String to use during transition.
* @return true when the currentState is end state and input surfaceForm id equal to currentSurfaceForm, otherwise false.
*/
bool FsmMorphologicalAnalyzer::parseExists(vector<FsmParse>& fsmParse, const string& surfaceForm) {
FsmParse currentFsmParse;
TxtWord* root;
State currentState;
string currentSurfaceForm;
while (!fsmParse.empty()) {
currentFsmParse = fsmParse.at(0);
fsmParse.erase(fsmParse.begin());
root = (TxtWord*) currentFsmParse.getWord();
currentState = currentFsmParse.getFinalSuffix();
currentSurfaceForm = currentFsmParse.getSurfaceForm();
if (currentState.isEndState() && currentSurfaceForm == surfaceForm) {
return true;
}
addNewParsesFromCurrentParse(currentFsmParse, fsmParse, surfaceForm, root);
}
return false;
}
/**
* The parseWord method is used to parse a given fsmParse. It simply adds new parses to the current parse by
* using addNewParsesFromCurrentParse method.
*
* @param fsmParse an ArrayList of FsmParse
* @param maxLength maximum length of the surfaceform.
* @return result {@link ArrayList} which has the currentFsmParse.
*/
vector<FsmParse> FsmMorphologicalAnalyzer::parseWord(vector<FsmParse> fsmParse, int maxLength) {
vector<FsmParse> result;
FsmParse currentFsmParse;
TxtWord* root;
State currentState;
string currentSurfaceForm;
int i;
bool exists;
while (!fsmParse.empty()) {
currentFsmParse = fsmParse.at(0);
fsmParse.erase(fsmParse.begin());
root = (TxtWord*) currentFsmParse.getWord();
currentState = currentFsmParse.getFinalSuffix();
currentSurfaceForm = currentFsmParse.getSurfaceForm();
if (currentState.isEndState() && Word::size(currentSurfaceForm) <= maxLength) {
exists = false;
for (i = 0; i < result.size(); i++) {
if (currentFsmParse.getSuffixList() == result.at(i).getSuffixList()) {
exists = true;
break;
}
}
if (!exists) {
result.push_back(currentFsmParse);
currentFsmParse.constructInflectionalGroups();
}
}
addNewParsesFromCurrentParse(currentFsmParse, fsmParse, maxLength, root);
}
return result;
}
/**
* The parseWord method is used to parse a given fsmParse. It simply adds new parses to the current parse by
* using addNewParsesFromCurrentParse method.
*
* @param fsmParse an ArrayList of FsmParse
* @param surfaceForm String to use during transition.
* @return result {@link ArrayList} which has the currentFsmParse.
*/
vector<FsmParse> FsmMorphologicalAnalyzer::parseWord(vector<FsmParse> fsmParse, const string& surfaceForm) {
vector<FsmParse> result;
FsmParse currentFsmParse;
TxtWord* root;
State currentState;
string currentSurfaceForm;
int i;
bool exists;
while (!fsmParse.empty()) {
currentFsmParse = fsmParse.at(0);
fsmParse.erase(fsmParse.begin());
root = (TxtWord*) currentFsmParse.getWord();
currentState = currentFsmParse.getFinalSuffix();
currentSurfaceForm = currentFsmParse.getSurfaceForm();
if (currentState.isEndState() && currentSurfaceForm == surfaceForm) {
exists = false;
for (i = 0; i < result.size(); i++) {
if (currentFsmParse.getSuffixList() == result.at(i).getSuffixList()) {
exists = true;
break;
}
}
if (!exists) {
result.push_back(currentFsmParse);
currentFsmParse.constructInflectionalGroups();
}
}
addNewParsesFromCurrentParse(currentFsmParse, fsmParse, surfaceForm, root);
}
return result;
}
/**
* The morphologicalAnalysis with 3 inputs is used to initialize an {@link ArrayList} and add a new FsmParse
* with given root and state.
*
* @param root TxtWord input.
* @param surfaceForm String input to use for parsing.
* @param state String input.
* @return parseWord method with newly populated FsmParse ArrayList and input surfaceForm.
*/
vector<FsmParse> FsmMorphologicalAnalyzer::morphologicalAnalysis(TxtWord *root, const string& surfaceForm, string state) {
vector<FsmParse> initialFsmParse;
initialFsmParse.emplace_back(FsmParse(root, finiteStateMachine.getState(move(state))));
return parseWord(initialFsmParse, move(surfaceForm));
}
/**
* The generateAllParses with 2 inputs is used to generate all parses with given root. Then it calls initializeParseListFromRoot method to initialize list with newly created ArrayList, input root,
* and maximum length.
*
* @param root TxtWord input.
* @param maxLength Maximum length of the surface form.
* @return parseWord method with newly populated FsmParse ArrayList and maximum length.
*/
vector<FsmParse> FsmMorphologicalAnalyzer::generateAllParses(TxtWord *root, int maxLength) {
vector<FsmParse> initialFsmParse;
initializeParseListFromRoot(initialFsmParse, root, false);
return parseWord(initialFsmParse, maxLength);
}
/**
* The morphologicalAnalysis with 2 inputs is used to initialize an {@link ArrayList} and add a new FsmParse
* with given root. Then it calls initializeParseList method to initialize list with newly created ArrayList, input root,
* and input surfaceForm.
*
* @param root TxtWord input.
* @param surfaceForm String input to use for parsing.
* @return parseWord method with newly populated FsmParse ArrayList and input surfaceForm.
*/
vector<FsmParse> FsmMorphologicalAnalyzer::morphologicalAnalysis(TxtWord *root, const string& surfaceForm) {
vector<FsmParse> initialFsmParse;
initializeParseListFromRoot(initialFsmParse, root, isProperNoun(surfaceForm));
return parseWord(initialFsmParse, surfaceForm);
}
/**
* The analysisExists method checks several cases. If the given surfaceForm is a punctuation or double then it
* returns true. If it is not a root word, then it initializes the parse list and returns the parseExists method with
* this newly initialized list and surfaceForm.
*
* @param rootWord TxtWord root.
* @param surfaceForm String input.
* @param isProper boolean variable indicates a word is proper or not.
* @return true if surfaceForm is punctuation or double, otherwise returns parseExist method with given surfaceForm.
*/
bool FsmMorphologicalAnalyzer::analysisExists(TxtWord *rootWord, const string& surfaceForm, bool isProper) {
vector<FsmParse> initialFsmParse;
if (Word::isPunctuation(surfaceForm)) {
return true;
}
if (isDouble(surfaceForm)) {
return true;
}
if (rootWord != nullptr) {
initializeParseListFromRoot(initialFsmParse, rootWord, isProper);
} else {
initialFsmParse = initializeParseListFromSurfaceForm(surfaceForm, isProper);
}
return parseExists(initialFsmParse, surfaceForm);
}
/**
* The analysis method is used by the morphologicalAnalysis method. It gets String surfaceForm as an input and checks
* its type such as punctuation, number or compares with the regex for date, fraction, percent, time, range, hashtag,
* and mail or checks its variable type as integer or double. After finding the right case for given surfaceForm, it calls
* constructInflectionalGroups method which creates sub-word units.
*
* @param surfaceForm String to analyse.
* @param isProper is used to indicate the proper words.
* @return ArrayList type initialFsmParse which holds the analyses.
*/
vector<FsmParse> FsmMorphologicalAnalyzer::analysis(const string& surfaceForm, bool isProper) {
vector<FsmParse> initialFsmParse;
FsmParse fsmParse;
if (Word::isPunctuation(surfaceForm) && surfaceForm != "%") {
fsmParse = FsmParse(surfaceForm, State(("Punctuation"), true, true));
fsmParse.constructInflectionalGroups();
initialFsmParse.push_back(fsmParse);
return initialFsmParse;
}
if (isNumber(surfaceForm)) {
fsmParse = FsmParse(surfaceForm, State(("CardinalRoot"), true, true));
fsmParse.constructInflectionalGroups();
initialFsmParse.push_back(fsmParse);
return initialFsmParse;
}
if (patternMatches("(\\d\\d|\\d)/(\\d\\d|\\d)/\\d+", surfaceForm) || patternMatches("(\\d\\d|\\d)\\.(\\d\\d|\\d)\\.\\d+", surfaceForm)) {
fsmParse = FsmParse(surfaceForm, State(("DateRoot"), true, true));
fsmParse.constructInflectionalGroups();
initialFsmParse.push_back(fsmParse);
return initialFsmParse;
}
if (patternMatches("\\d+/\\d+", surfaceForm)) {
fsmParse = FsmParse(surfaceForm, State(("FractionRoot"), true, true));
fsmParse.constructInflectionalGroups();
initialFsmParse.push_back(fsmParse);
fsmParse = FsmParse(surfaceForm, State(("DateRoot"), true, true));
fsmParse.constructInflectionalGroups();
initialFsmParse.push_back(fsmParse);
return initialFsmParse;
}
if (patternMatches("\\d+\\\\/\\d+", surfaceForm)) {
fsmParse = FsmParse(surfaceForm, State(("FractionRoot"), true, true));
fsmParse.constructInflectionalGroups();
initialFsmParse.push_back(fsmParse);
return initialFsmParse;
}
if (surfaceForm == "%" || patternMatches("%(\\d\\d|\\d)", surfaceForm) || patternMatches("%(\\d\\d|\\d)\\.\\d+", surfaceForm)) {
fsmParse = FsmParse(surfaceForm, State(("PercentRoot"), true, true));
fsmParse.constructInflectionalGroups();
initialFsmParse.push_back(fsmParse);
return initialFsmParse;
}
if (patternMatches("(\\d\\d|\\d):(\\d\\d|\\d):(\\d\\d|\\d)", surfaceForm) || patternMatches("(\\d\\d|\\d):(\\d\\d|\\d)", surfaceForm)) {
fsmParse = FsmParse(surfaceForm, State(("TimeRoot"), true, true));
fsmParse.constructInflectionalGroups();
initialFsmParse.push_back(fsmParse);
return initialFsmParse;
}
if (patternMatches("\\d+-\\d+", surfaceForm) || patternMatches("(\\d\\d|\\d):(\\d\\d|\\d)-(\\d\\d|\\d):(\\d\\d|\\d)", surfaceForm) || patternMatches("(\\d\\d|\\d)\\.(\\d\\d|\\d)-(\\d\\d|\\d)\\.(\\d\\d|\\d)", surfaceForm)) {
fsmParse = FsmParse(surfaceForm, State(("RangeRoot"), true, true));
fsmParse.constructInflectionalGroups();
initialFsmParse.push_back(fsmParse);
return initialFsmParse;
}
if (Word::startsWith(surfaceForm, "#")) {
fsmParse = FsmParse(surfaceForm, State(("Hashtag"), true, true));
fsmParse.constructInflectionalGroups();
initialFsmParse.push_back(fsmParse);
return initialFsmParse;
}
if (surfaceForm.find('@') != string::npos) {
fsmParse = FsmParse(surfaceForm, State(("Email"), true, true));
fsmParse.constructInflectionalGroups();
initialFsmParse.push_back(fsmParse);
return initialFsmParse;
}
if (Word::lastChar(surfaceForm) == "." && isInteger(Word::substringExceptLastChar(surfaceForm))) {
fsmParse = FsmParse(stoi(Word::substringExceptLastChar(surfaceForm)), finiteStateMachine.getState("OrdinalRoot"));
fsmParse.constructInflectionalGroups();
initialFsmParse.push_back(fsmParse);
return initialFsmParse;
}
if (isInteger(surfaceForm)) {
fsmParse = FsmParse(stoi(surfaceForm), finiteStateMachine.getState("CardinalRoot"));
fsmParse.constructInflectionalGroups();
initialFsmParse.push_back(fsmParse);
return initialFsmParse;
}
if (isDouble(surfaceForm)) {
fsmParse = FsmParse(stof(surfaceForm), finiteStateMachine.getState("RealRoot"));
fsmParse.constructInflectionalGroups();
initialFsmParse.push_back(fsmParse);
return initialFsmParse;
}
initialFsmParse = initializeParseListFromSurfaceForm(surfaceForm, isProper);
vector<FsmParse> resultFsmParse = parseWord(initialFsmParse, surfaceForm);
return resultFsmParse;
}
bool FsmMorphologicalAnalyzer::patternMatches(string expr, const string& value){
regex r;
if (mostUsedPatterns.find(expr) == mostUsedPatterns.end()){
r = regex(expr);
mostUsedPatterns.emplace(expr, r);
} else {
r = mostUsedPatterns.find(expr)->second;
}
return regex_match(value, r);
}
/**
* The isProperNoun method takes surfaceForm String as input and checks its each char whether they are in the range
* of letters between A to Z or one of the Turkish letters such as İ, Ü, Ğ, Ş, Ç, and Ö.
*
* @param surfaceForm String to check for proper noun.
* @return false if surfaceForm is null or length of 0, return true if it is a letter.
*/
bool FsmMorphologicalAnalyzer::isProperNoun(const string& surfaceForm) {
if (surfaceForm.empty()) {
return false;
}
return (Word::charAt(surfaceForm, 0) >= "A" && Word::charAt(surfaceForm, 0) <= "Z") || Word::charAt(surfaceForm, 0) == "Ç" || Word::charAt(surfaceForm, 0) == "Ö" || Word::charAt(surfaceForm, 0) == "Ğ" || Word::charAt(surfaceForm, 0) == "Ü" || Word::charAt(surfaceForm, 0) == "Ş" || Word::charAt(surfaceForm, 0) == "İ"; // İ, Ü, Ğ, Ş, Ç, Ö
}
/**
* The robustMorphologicalAnalysis is used to analyse surfaceForm String. First it gets the currentParse of the surfaceForm
* then, if the size of the currentParse is 0, and given surfaceForm is a proper noun, it adds the surfaceForm
* whose state name is ProperRoot to an {@link ArrayList}, of it is not a proper noon, it adds the surfaceForm
* whose state name is NominalRoot to the {@link ArrayList}.
*
* @param surfaceForm String to analyse.
* @return FsmParseList type currentParse which holds morphological analysis of the surfaceForm.
*/
FsmParseList FsmMorphologicalAnalyzer::robustMorphologicalAnalysis(const string& surfaceForm) {
vector<FsmParse> fsmParse;
FsmParseList currentParse;
if (surfaceForm.empty()) {
return FsmParseList();
}
currentParse = morphologicalAnalysis(surfaceForm);
if (currentParse.size() == 0) {
if (isProperNoun(surfaceForm)) {
fsmParse.emplace_back(FsmParse(surfaceForm, finiteStateMachine.getState("ProperRoot")));
return FsmParseList(parseWord(fsmParse, surfaceForm));
} else {
fsmParse.emplace_back(FsmParse(surfaceForm, finiteStateMachine.getState("NominalRoot")));
return FsmParseList(parseWord(fsmParse, surfaceForm));
}
} else {
return currentParse;
}
}
/**
* The morphologicalAnalysis is used for debug purposes.
*
* @param sentence to get word from.
* @return FsmParseList type result.
*/
FsmParseList *FsmMorphologicalAnalyzer::morphologicalAnalysis(Sentence sentence) {
FsmParseList wordFsmParseList;
auto* result = new FsmParseList[sentence.wordCount()];
for (int i = 0; i < sentence.wordCount(); i++) {
string originalForm = sentence.getWord(i)->getName();
string spellCorrectedForm = dictionary.getCorrectForm(originalForm);
if (spellCorrectedForm.empty()){
spellCorrectedForm = originalForm;
}
wordFsmParseList = morphologicalAnalysis(spellCorrectedForm);
result[i] = wordFsmParseList;
}
return result;
}
/**
* The robustMorphologicalAnalysis method takes just one argument as an input. It gets the name of the words from
* input sentence then calls robustMorphologicalAnalysis with surfaceForm.
*
* @param sentence Sentence type input used to get surfaceForm.
* @return FsmParseList array which holds the result of the analysis.
*/
FsmParseList *FsmMorphologicalAnalyzer::robustMorphologicalAnalysis(Sentence sentence) {
FsmParseList fsmParseList;
auto* result = new FsmParseList[sentence.wordCount()];
for (int i = 0; i < sentence.wordCount(); i++) {
string originalForm = sentence.getWord(i)->getName();
string spellCorrectedForm = dictionary.getCorrectForm(originalForm);
if (spellCorrectedForm.empty()){
spellCorrectedForm = originalForm;
}
fsmParseList = robustMorphologicalAnalysis(spellCorrectedForm);
result[i] = fsmParseList;
}
return result;
}
/**
* The isInteger method compares input surfaceForm with regex \+?\d+ and returns the result.
* Supports positive integer checks only.
*
* @param surfaceForm String to check.
* @return true if surfaceForm matches with the regex.
*/
bool FsmMorphologicalAnalyzer::isInteger(const string& surfaceForm) {
if (!patternMatches("\\+?\\d+", surfaceForm)){
return false;
}
int len = Word::size(surfaceForm);
if (len < 10) {
return true; //Most common scenario. Return after a single check.
} else {
if (len > 10) {
return false;
} else {
try {
stoi(surfaceForm);
return true;
}
catch (invalid_argument& e){
return false;
}
}
}
}
/**
* The isDouble method compares input surfaceForm with regex \+?(\d+)?\.\d* and returns the result.
*
* @param surfaceForm String to check.
* @return true if surfaceForm matches with the regex.
*/
bool FsmMorphologicalAnalyzer::isDouble(const string& surfaceForm) {
return patternMatches("\\+?(\\d+)?\\.\\d*", surfaceForm);
}
/**
* The isNumber method compares input surfaceForm with the array of written numbers and returns the result.
*
* @param surfaceForm String to check.
* @return true if surfaceForm matches with the regex.
*/
bool FsmMorphologicalAnalyzer::isNumber(string surfaceForm) {
bool found;
int count = 0;
string numbers[] = {"bir", "iki", "üç", "dört", "beş", "altı", "yedi", "sekiz", "dokuz",
"on", "yirmi", "otuz", "kırk", "elli", "altmış", "yetmiş", "seksen", "doksan",
"yüz", "bin", "milyon", "milyar", "trilyon", "katrilyon"};
string word = move(surfaceForm);
while (!word.empty()) {
found = false;
for (const string &number : numbers) {
if (Word::startsWith(word, number)) {
found = true;
count++;
word = Word::substring(word, Word::size(number));
break;
}
}
if (!found) {
break;
}
}
return word.empty() && count > 1;
}
/**
* The morphologicalAnalysisExists method calls analysisExists to check the existence of the analysis with given
* root and surfaceForm.
*
* @param surfaceForm String to check.
* @param rootWord TxtWord input root.
* @return true an analysis exists, otherwise return false.
*/
bool FsmMorphologicalAnalyzer::morphologicalAnalysisExists(TxtWord *rootWord, string surfaceForm) {
return analysisExists(rootWord, Word::toLowerCase(move(surfaceForm)), true);
}
/**
* The morphologicalAnalysis method is used to analyse a FsmParseList by comparing with the regex.
* It creates an {@link ArrayList} fsmParse to hold the result of the analysis method. For each surfaceForm input,
* it gets a substring and considers it as a possibleRoot. Then compares with the regex.
* <p>
* If the surfaceForm input string matches with Turkish chars like Ç, Ş, İ, Ü, Ö, it adds the surfaceForm to Trie with IS_OA tag.
* If the possibleRoot contains /, then it is added to the Trie with IS_KESIR tag.
* If the possibleRoot contains \d\d|\d)/(\d\d|\d)/\d+, then it is added to the Trie with IS_DATE tag.
* If the possibleRoot contains \\d\d|\d, then it is added to the Trie with IS_PERCENT tag.
* If the possibleRoot contains \d\d|\d):(\d\d|\d):(\d\d|\d), then it is added to the Trie with IS_ZAMAN tag.
* If the possibleRoot contains \d+-\d+, then it is added to the Trie with IS_RANGE tag.
* If the possibleRoot is an Integer, then it is added to the Trie with IS_SAYI tag.
* If the possibleRoot is a Double, then it is added to the Trie with IS_REELSAYI tag.
*
* @param surfaceForm String to analyse.
* @return fsmParseList which holds the analysis.
*/
FsmParseList FsmMorphologicalAnalyzer::morphologicalAnalysis(const string& surfaceForm) {
FsmParseList fsmParseList;
if (cache.getCacheSize() > 0 && cache.contains(surfaceForm)) {
return cache.get(surfaceForm);
}
if (patternMatches("(\\w|Ç|Ş|İ|Ü|Ö)\\.", surfaceForm)) {
dictionaryTrie->addWord(Word::toLowerCase(surfaceForm), new TxtWord(Word::toLowerCase(surfaceForm), "IS_OA"));
}
vector<FsmParse> defaultFsmParse = analysis(Word::toLowerCase(surfaceForm), isProperNoun(surfaceForm));
if (!defaultFsmParse.empty()) {
fsmParseList = FsmParseList(defaultFsmParse);
if (cache.getCacheSize() > 0){
cache.add(surfaceForm, fsmParseList);
}
return fsmParseList;
}
vector<FsmParse> fsmParse;
if (surfaceForm.find('\'') != string::npos) {
string possibleRoot = surfaceForm.substr(0, surfaceForm.find('\''));
if (!possibleRoot.empty()) {
if (possibleRoot.find('/') != string::npos || possibleRoot.find("\\/") != string::npos) {
dictionaryTrie->addWord(possibleRoot, new TxtWord(possibleRoot, "IS_KESIR"));
fsmParse = analysis(Word::toLowerCase(surfaceForm), isProperNoun(surfaceForm));
} else {
if (patternMatches("(\\d\\d|\\d)/(\\d\\d|\\d)/\\d+", possibleRoot) || patternMatches("(\\d\\d|\\d)\\.(\\d\\d|\\d)\\.\\d+", possibleRoot)) {
dictionaryTrie->addWord(possibleRoot, new TxtWord(possibleRoot, "IS_DATE"));
fsmParse = analysis(Word::toLowerCase(surfaceForm), isProperNoun(surfaceForm));
} else {
if (patternMatches("\\d+/\\d+", possibleRoot)) {
dictionaryTrie->addWord(possibleRoot, new TxtWord(possibleRoot, "IS_KESIR"));
fsmParse = analysis(Word::toLowerCase(surfaceForm), isProperNoun(surfaceForm));
} else {
if (patternMatches("%(\\d\\d|\\d)", possibleRoot) || patternMatches("%(\\d\\d|\\d)\\.\\d+", possibleRoot)) {
dictionaryTrie->addWord(possibleRoot, new TxtWord(possibleRoot, "IS_PERCENT"));
fsmParse = analysis(Word::toLowerCase(surfaceForm), isProperNoun(surfaceForm));
} else {
if (patternMatches("(\\d\\d|\\d):(\\d\\d|\\d):(\\d\\d|\\d)", possibleRoot) || patternMatches("(\\d\\d|\\d):(\\d\\d|\\d)", possibleRoot)) {
dictionaryTrie->addWord(possibleRoot, new TxtWord(possibleRoot, "IS_ZAMAN"));
fsmParse = analysis(Word::toLowerCase(surfaceForm), isProperNoun(surfaceForm));
} else {
if (patternMatches("\\d+-\\d+", possibleRoot) || patternMatches("(\\d\\d|\\d):(\\d\\d|\\d)-(\\d\\d|\\d):(\\d\\d|\\d)", possibleRoot) || patternMatches("(\\d\\d|\\d)\\.(\\d\\d|\\d)-(\\d\\d|\\d)\\.(\\d\\d|\\d)", possibleRoot)) {
dictionaryTrie->addWord(possibleRoot, new TxtWord(possibleRoot, "IS_RANGE"));
fsmParse = analysis(Word::toLowerCase(surfaceForm), isProperNoun(surfaceForm));
} else {
if (isInteger(possibleRoot)) {
dictionaryTrie->addWord(possibleRoot, new TxtWord(possibleRoot, "IS_SAYI"));
fsmParse = analysis(Word::toLowerCase(surfaceForm), isProperNoun(surfaceForm));
} else {
if (isDouble(possibleRoot)) {
dictionaryTrie->addWord(possibleRoot, new TxtWord(possibleRoot, "IS_REELSAYI"));
fsmParse = analysis(Word::toLowerCase(surfaceForm), isProperNoun(surfaceForm));
} else {
if (Word::isCapital(possibleRoot)) {
TxtWord* newWord = nullptr;
if (dictionary.getWord(Word::toLowerCase(surfaceForm)) != nullptr) {
((TxtWord*) dictionary.getWord(Word::toLowerCase(surfaceForm)))->addFlag("IS_OA");
} else {
newWord = new TxtWord(Word::toLowerCase(surfaceForm), "IS_OA");
dictionaryTrie->addWord(Word::toLowerCase(surfaceForm), newWord);
}
fsmParse = analysis(Word::toLowerCase(surfaceForm), isProperNoun(surfaceForm));
if (fsmParse.empty() && newWord != nullptr) {
newWord->addFlag("IS_KIS");
fsmParse = analysis(Word::toLowerCase(surfaceForm), isProperNoun(surfaceForm));
}
}
}
}
}
}
}
}
}
}
}
}
fsmParseList = FsmParseList(fsmParse);
if (cache.getCacheSize() > 0){
cache.add(surfaceForm, fsmParseList);
}
return fsmParseList;
}
| true |
8b1a3bbb10840b83c156537f8787b1759dcd46c8 | C++ | yhf869252662/LearningQuestionBank | /test_2_28/test_3_11.cpp | UTF-8 | 1,233 | 3.46875 | 3 | [] | no_license | //#include <iostream>
//
//using namespace std;
//
//int Fibonacci[30] = { 0 };
//
//int Fibo(int n)
//{
// int n1 = 1;
// int n2 = 1;
// int n3 = 1;
//
// for (int i = 2; i <= n; i++)
// {
// n3 = n2 + n1;
// n1 = n2;
// n2 = n3;
// }
//
// return n3;
//}
//
//void makeFibo()
//{
// for (int i = 0; i < 30; i++)
// {
// Fibonacci[i] = Fibo(i);
// }
//}
//
//int main()
//{
// int n = 0;
// cin >> n;
// int i = 0;
//
// makeFibo();
//
// for (; i < 100; i++)
// {
// if (n < Fibonacci[i])
// break;
// }
//
// int less = n - Fibonacci[i - 1];
// int more = Fibonacci[i] - n;
// int ret = more < less ? more : less;
//
// cout << ret << endl;
//
// return 0;
//}
//#include <string>
//#include <stack>
//#include <iostream>
//
//using namespace std;
//
//bool chkParenthesis(string A, int n) {
// stack<char> sta;
//
// int i = 0;
//
// while (i < n)
// {
// if (A[i] == '(')
// sta.push(A[i]);
// else if (A[i] == ')')
// {
// if (sta.empty())
// {
// return false;
// }
// sta.pop();
// }
// else
// return false;
//
// i++;
// }
// if (sta.empty())
// return true;
// else
// return false;
//}
//
//int main()
//{
// string str = "(()())";
// cout << chkParenthesis(str, str.size()) << endl;
//}
| true |
2046657a92e9baea71c991ac41be3df6079f2a8f | C++ | gordonwatts/TMVATests | /TMVAStraightCutReader/main.cpp | UTF-8 | 1,218 | 2.734375 | 3 | [] | no_license | ///
/// Read in a TMVA weight file and do a few tests by hand.
///
#include "tmva/Reader.h"
#include <iostream>
using namespace std;
int main()
{
// Load up the reader
auto reader = new TMVA::Reader();
// Declare the variables
float lowestPtTrack = 0.0;
float nTracks = 0.0;
float logR = 0.0;
reader->AddVariable("logR", &logR);
reader->AddVariable("nTracks", &nTracks);
// Book it
auto s = "C:\\Users\\gordo\\Documents\\Code\\calratio2015\\JetCutStudies\\SimpleJetCutTraining\\bin\\x86\\Debug\\weights\\VerySimpleTraining_SimpleCuts.weights.xml";
reader->BookMVA("SimpleCuts", s);
// Now get some values
logR = 1.0;
nTracks = 5;
cout << "LogR: " << logR << " nTracks: " << nTracks << ": result=" << reader->EvaluateMVA("SimpleCuts", 0.22) << endl;
logR = 2.0;
nTracks = 00;
cout << "LogR: " << logR << " nTracks: " << nTracks << ": result=" << reader->EvaluateMVA("SimpleCuts", 0.22) << endl;
vector<double> stuff;
stuff.push_back(1.0);
stuff.push_back(5);
cout << "result=" << reader->EvaluateMVA(stuff, "SimpleCuts", 0.22) << endl;
stuff.clear();
stuff.push_back(2.0);
stuff.push_back(0);
cout << "result=" << reader->EvaluateMVA(stuff, "SimpleCuts", 0.22) << endl;
return 0;
} | true |
4254880f21bc5ca7b67ed26490ff1dbc69dc99a9 | C++ | georgerapeanu/c-sources | /cf1452/A.cpp | UTF-8 | 240 | 2.65625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main(){
int t;
int x,y;
cin >> t;
while(t--){
cin >> x >> y;
cout << abs(x) + abs(y) + max(abs(abs(x) - abs(y)) - 1,0) << "\n";
}
return 0;
}
| true |
21466488367cb1d3de20a4bd1812addf79904dc2 | C++ | contificate/Elfex | /disasm/exceptions/disasmexception.h | UTF-8 | 509 | 2.609375 | 3 | [] | no_license | #ifndef DISASMEXCEPTION_H
#define DISASMEXCEPTION_H
#include <exception>
namespace efx {
/**
* @brief The DisasmException class
* We can use this for all futures and promises during disassembly
* because you can set exceptions for those.
*/
class DisasmException : public std::exception {
public:
DisasmException(const char* const message) : msg_{message} {}
const char* what() const noexcept { return msg_; }
private:
const char* msg_;
};
} // namespace efx
#endif // DISASMEXCEPTION_H
| true |
d54f54eacb6b45e670e403b7d5cf04218061df6a | C++ | zellyn/project-euler | /cc/051.cc | UTF-8 | 2,517 | 3.390625 | 3 | [] | no_license | // Project Euler Problem 051
//
// Find the smallest prime which, by changing the same part of the
// number, can form eight different primes.
#include <cstdio>
#include <cstdlib>
#include <sstream>
#include <string>
#include <vector>
#include "primes1.h"
using namespace std;
int atoi_sub(const string& s, const int digit) {
string::const_iterator i;
int retval = 0;
for (i=s.begin(); i != s.end(); ++i) {
retval *= 10;
if (*i == '*') {
retval += digit;
} else {
retval += *i - '0';
}
}
return retval;
}
bool matches(const string& pattern, Primes1<int>& primes) {
int fails = 0;
int digit = 9;
do {
if ((digit==0) && pattern[0] == '*') {
fails++;
} else if (!primes.is_prime(atoi_sub(pattern, digit))) {
fails++;
}
if (fails>2) return false;
} while (--digit >= 0);
return (fails==2);
}
void choose(const string& pattern, const string& prefix, const char digit,
size_t start, int k, int n, vector<string>& v) {
if (k > n) return;
if (k == 0) {
v.push_back(prefix + pattern.substr(start));
return;
}
if (start>=pattern.size()) return;
if (pattern[start] == digit) {
choose(pattern, prefix + '*', digit, start+1, k-1, n-1, v);
choose(pattern, prefix + pattern[start], digit, start+1, k, n-1, v);
} else {
choose(pattern, prefix + pattern[start], digit, start+1, k, n, v);
}
}
vector<string> make_patterns(const string& s) {
int digits[10] = { 0 };
vector<string> v;
string::const_iterator i;
// Note the s.end() - 1: we don't include the last digit, because at
// least one of eight digit choices would leave the number divisible
// by three.
for (i=s.begin(); i != s.end() - 1; ++i) {
digits[*i - '0']++;
}
for (int j=0; j<10; j++) {
if (digits[j] >= 3) {
choose(s, "", j + '0', 0, 3, digits[j], v);
if (digits[j] >= 6) {
choose(s, "", j + '0', 0, 6, digits[j], v);
}
}
}
return v;
}
bool win(const string& s, Primes1<int>& primes) {
vector<string> patterns = make_patterns(s);
vector<string>::iterator i;
for (i = patterns.begin(); i != patterns.end(); ++i) {
if (matches(*i, primes)) return true;
}
return false;
}
int main(int argc, const char* argv[]) {
Primes1<int> primes;
int prime = 0;
stringstream ss;
while ((prime = primes.next()) < 1000);
do {
ss.str("");
ss << prime;
if (win(ss.str(), primes)) break;
prime = primes.next();
} while (true);
printf("%d\n", prime);
}
| true |
db2fe66f91ab7169803e141920c1867a2e7e4198 | C++ | JacobHornbeck/CSE-230-Lab07 | /Lab07/Projectile.h | UTF-8 | 3,613 | 3.25 | 3 | [] | no_license | #pragma once
#include <cmath>
using namespace std;
/**********************************
* PVector Class
* Auther: Jacob Hornbeck
**********************************/
class PVector {
public:
/// <summary>
/// x component
/// </summary>
double x;
/// <summary>
/// y component
/// </summary>
double y;
/// <summary>
/// Initialize a new PVector
/// </summary>
/// <param name="x">Initial horizontal position</param>
/// <param name="y">Initial vertical position</param>
PVector(double x, double y) {
this->x = x;
this->y = y;
}
/// <summary>
/// Copy PVector values to a new PVector
/// </summary>
/// <returns>A copy of the original PVector</returns>
PVector copy() {
return PVector(this->x, this->y);
}
/// <summary>
/// Adds two PVectors together
/// </summary>
/// <param name="v2">Another PVector</param>
void add(PVector v2) {
this->x += v2.x;
this->y += v2.y;
}
/// <summary>
/// Add components to original PVector
/// </summary>
/// <param name="x">x component</param>
/// <param name="y">y component</param>
void add(double x, double y) {
this->x += x;
this->y += y;
}
/// <summary>
/// Subtract a PVector from the original
/// </summary>
/// <param name="v2">Another PVector</param>
void sub(PVector v2) {
this->x -= v2.x;
this->y -= v2.y;
}
/// <summary>
/// Subtract components from original PVector
/// </summary>
/// <param name="x">x component</param>
/// <param name="y">y component</param>
void sub(double x, double y) {
this->x -= x;
this->y -= y;
}
/// <summary>
/// Multiply PVector by a scaler
/// </summary>
/// <param name="n">Scaler value</param>
void mult(double n) {
this->x *= n;
this->y *= n;
}
/// <summary>
/// Divide PVector by a divisor
/// </summary>
/// <param name="n">Divisor value</param>
void div(double n) {
this->x /= n;
this->y /= n;
}
/// <summary>
/// Set component values of PVector
/// </summary>
/// <param name="x">x component</param>
/// <param name="y">y component</param>
void set(double x, double y) {
this->x = x;
this->y = y;
}
/// <summary>
/// Get the magnitude of the PVector
/// </summary>
/// <returns>Magnitude of the PVector</returns>
double mag() {
return sqrt(pow(this->x, 2) + pow(this->y, 2));
}
};
class Projectile {
public:
Projectile();
~Projectile();
void runTest();
private:
PVector vel = PVector(0.0, 0.0);
PVector pos = PVector(0.0, 0.0);
double diameter = 0.0,
mass = 0.0,
initial_speed = 0.0,
surfaceArea = 0.0;
double getGravity(double);
double getDensity(double);
double getDragCoefficient(double);
double getDragForce(double, double, double, double);
double getAngle();
void updatePosition();
void updateVelocity();
void initialize(double);
};
| true |
76aa29785c0e6e033d3aa27e33c5cc3346586ec5 | C++ | IanusInferus/niveum | /Examples/Communication/CPP/Src/Client/Clients/IContext.h | UTF-8 | 555 | 2.5625 | 3 | [
"DOC"
] | permissive | #pragma once
#include <cstdint>
#include <vector>
namespace Client
{
class SecureContext
{
public:
std::vector<std::uint8_t> ServerToken; //服务器到客户端数据的Token
std::vector<std::uint8_t> ClientToken; //客户端到服务器数据的Token
};
class IBinaryTransformer
{
public:
virtual void Transform(std::vector<std::uint8_t> &Buffer, int Start, int Count) = 0;
virtual void Inverse(std::vector<std::uint8_t> &Buffer, int Start, int Count) = 0;
};
}
| true |
8becf762245ffda35a061ae3246bd8edb5ef2b8d | C++ | tedvalson/NovelTea | /include/NovelTea/GUI/VerbList.hpp | UTF-8 | 2,531 | 2.5625 | 3 | [
"MIT"
] | permissive | #ifndef NOVELTEA_VERBLIST_HPP
#define NOVELTEA_VERBLIST_HPP
#include <NovelTea/ContextObject.hpp>
#include <NovelTea/GUI/Scrollable.hpp>
#include <NovelTea/GUI/ScrollBar.hpp>
#include <NovelTea/GUI/Hideable.hpp>
#include <NovelTea/Utils.hpp>
#include <NovelTea/Verb.hpp>
#include <NovelTea/Object.hpp>
#include <SFML/Graphics/View.hpp>
#include <functional>
#include <vector>
namespace NovelTea
{
using VerbSelectCallback = std::function<void(const std::string&)>;
using VerbShowHideCallback = std::function<void(bool)>;
class VerbList : public ContextObject, public sf::Drawable, public Scrollable, public Hideable
{
public:
VerbList(Context *context);
bool update(float delta) override;
bool processEvent(const sf::Event& event);
void refreshItems();
void setFontSizeMultiplier(float fontSizeMultiplier);
void setScreenSize(const sf::Vector2f &size);
const sf::Vector2f &getScreenSize() const;
void show(float duration = 0.4f, int tweenType = ALPHA, HideableCallback callback = nullptr) override;
void hide(float duration = 0.4f, int tweenType = ALPHA, HideableCallback callback = nullptr) override;
void setAlpha(float alpha) override;
float getAlpha() const override;
void setVerbs(const std::vector<std::string> &verbIds);
void setVerbs(const std::string &objectId);
void setSelectCallback(VerbSelectCallback callback);
void setShowHideCallback(VerbShowHideCallback callback);
VerbSelectCallback getSelectCallback() const;
VerbShowHideCallback getShowHideCallback() const;
void setScroll(float position) override;
float getScroll() override;
const sf::Vector2f &getScrollSize() override;
void setPositionBounded(const sf::Vector2f& position);
sf::FloatRect getLocalBounds() const;
sf::FloatRect getGlobalBounds() const;
protected:
void draw(sf::RenderTarget &target, sf::RenderStates states) const override;
void repositionItems();
void addVerbOption(const std::string &verbId);
private:
struct VerbOption {
std::string verbId;
TweenText text;
};
float m_scrollPos;
float m_margin;
float m_itemHeight;
float m_fontSizeMultiplier;
sf::Vector2f m_screenSize;
sf::Vector2f m_scrollAreaSize;
TweenEngine::TweenManager m_tweenManager;
ScrollBar m_scrollBar;
TweenRectangleShape m_bg;
TweenText m_text;
sf::FloatRect m_bounds;
mutable sf::Transform m_lastTransform;
mutable sf::View m_view;
std::vector<VerbOption> m_verbs;
VerbSelectCallback m_selectCallback;
VerbShowHideCallback m_showHideCallback;
};
} // namespace NovelTea
#endif // NOVELTEA_VERBLIST_HPP
| true |
67318154cb8a05b9003fbe2e5ff20d8e48cf6a9a | C++ | intellhave/geocam | /Geometry/Edge/length.h | UTF-8 | 1,275 | 2.828125 | 3 | [] | no_license | #ifndef LENGTH_H_
#define LENGTH_H_
#include <cmath>
#include <map>
/**************************************************************
Class: Length
Author: Alex Henniges?, Dan Champion?, Dave Glickenstein
Version: January 5, 2010
**************************************************************/
#include <new>
using namespace std;
#include "geoquant.h"
#include "triposition.h"
#include "triangulation/triangulation.h"
#include "radius.h"
#include "eta.h"
#include "alpha.h"
/*
* The Length is a geoquant.
* Suppose e is an edge with vertices vi and vj.
* The length is equal to:
* length(e) = sqrt( alpha(vi)*radius(vi) ^2 + alpha(vj)*radius(vj) ^2 +2*eta(e) * radius (vi) * radius (vj) )
* Note that Alpha was added January 4, 2010, and older versions may not use it. Alpha defaults to 1.0, which
* should generally be backwards compatible.
*/
class Length : public virtual GeoQuant {
private:
Radius* radius1;
Radius* radius2;
Alpha* alpha1;
Alpha* alpha2;
Eta* eta;
protected:
Length( Edge& e );
void recalculate();
public:
~Length();
static Length* At( Edge& e );
static double valueAt( Edge& e ) {
return Length::At(e)->getValue();
}
static void CleanUp();
void remove();
static void print(FILE* out);
};
#endif /* LENGTH_H_ */
| true |
65ac63c07534f2d8c711026f225842298e4c3cd1 | C++ | eyes22/AlgoDDABres | /algoritma bresenham/main.cpp | UTF-8 | 1,380 | 2.8125 | 3 | [] | no_license | /*
Projek : Aplikasi Algoritma Bresenham
Tugas : Grafika Komputer
Kelompok : Giri Supangkat 10108423
Wanda 10108419
Muzakki Fadhi 10108414
Rizal Rismawan 10108389
Ringga Anggiat S 10107569
*/
#include <stdio.h>
#include <conio.h>
#include <graphics.h>
int main()
{
int gdriver = DETECT, gnode;
int dx, dy, p, end;
float x1, x2, y1, y2, x, y;
initgraph(&gdriver, &gnode, "");
printf("Algoritma Bresenham \n");
printf("Masukan nilai x1 : \n");
scanf("%f", &x1);
printf("Masukan nilai y1 : ");
scanf("%f", &y1);
printf("Masukin nilai x2: ");
scanf("%f", &x2);
printf("Masukan nilai y2: ");
scanf("%f", &y2);
dx = abs(x1 - x2);
dy = abs(y1 - y2);
p=2 * dy -dx;
if(x1 > x2)
{
x = x2;
y = y2;
end = x1;
}
else
{
x = x1;
y = y1;
end = x2;
}
putpixel(x, y, 10);
while(x < end)
{
x = x + 1;
if(p<0)
{
p=p + 2 * dy;
}
else
{
y=y+1;
p=p+2*(dy-dx);
}
putpixel(x,y,10);
}
getch();
closegraph();
system("PAUSE");
return EXIT_SUCCESS;
}
| true |
0837f19280b1f663c44530818a2a4434c21eb877 | C++ | maddotexe/Competitive-contest-programs | /course code/5th sem/CG/folder a/folder a/js1/A4/4_2.cpp | UTF-8 | 982 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <GL/gl.h>
#include <GL/freeglut.h>
#include <map>
#include <cmath>
#define PUSH glPushMatrix
#define POP glPopMatrix
#define inf 1000000
using namespace std;
void playit()
{
PUSH();
double t = 3;
int loop = 3;
double r = 0.5;
double dif = 0.28;
while (loop--) {
for (double x = 0; x <= 6.28; x += dif) {
t += (t*0.03);
glColor3f(r, 0, 0);
r += 0.01;
glPointSize(8-loop);
glBegin(GL_POINTS);
glVertex2f(t*sin(x), t*cos(x));
glEnd();
glFlush();
}
dif += 0.05;
}
POP();
glutSwapBuffers();
}
void graphics()
{
glOrtho(-50, 50, -50, 50, -50, 50);
glClearColor(1, 1, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0, 0, 0);
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE);
glutInitWindowSize(500, 500);
glutInitWindowPosition(50, 50);
glutCreateWindow("hello world");
graphics();
glutDisplayFunc(playit);
glutMainLoop();
return 0;
}
| true |
22fdc58a235504b1e7e199cebb8bcef98b749410 | C++ | visheshvikas/Arduino | /theVDIsensor/MMA7361.cpp | UTF-8 | 1,671 | 3 | 3 | [] | no_license | #include "Arduino.h"
#include "MMA7361.h"
// MMA7361 Accelerometer consists of 9 pins such that
// Vcc = 3.3 V, GND, XOUT, YOUT, ZOUT, SLP, etc.
// SLP (Sleep pin) should be set to high (3.3 V) for the accelerometer to be active
MMA7361::MMA7361()
{
}
//Sets the analog pins and initializes the running averages, counter
void MMA7361::setPins(int thePins[3])
{
for(int ii=0; ii<3; ii++){
_thePins[ii] = thePins[ii];
pinMode(_thePins[ii], INPUT);
}
// Serial.print("Pins set as");
// Serial.println(_thePins[0]);
resetRunningAvg();
}
//Reads Voltage from the Analog pins
void MMA7361::readVoltage()
{
for(int ii=0; ii<3; ii++){
_theVoltages[ii] = analogRead(_thePins[ii]);
}
}
//writes the Voltages to the serial port (XBee port)
//Total bytes transferred = 2X3 = 6 (as an integer is 2 bytes)
//Note: The serial is passed by reference and not value, otherwise the copy only works once
//void MMA7361::printVoltage(SoftwareSerial &theSerial, int &accelNo)
//{
// //Total integers being sent out = 3 = 3X2 bytes
// for(int ii=0; ii<3; ii++){
// // send the two bytes that comprise an integer
// theSerial.write(lowByte(_theVoltages[ii])); // send the low byte
// theSerial.write(highByte(_theVoltages[ii])); // send the high byte
// }
//}
//Updating the running average and updating the counter
void MMA7361::updateVoltage()
{
readVoltage();
// for(int ii=0;ii<3;ii++){
// rAvg[ii] = (rAvg[ii]*ravgCounter + _theVoltages[ii])/(ravgCounter+1);
// }
// ravgCounter++;
}
//Resetting the running averages and the counter to zero
void MMA7361::resetRunningAvg()
{
ravgCounter = 0;
for(int ii=0;ii<3;ii++){
rAvg[ii]=0;
}
}
| true |
56d96a16e946c17f075a23fc85a8f8eef9ba3958 | C++ | jatinarora2702/Competitive-Coding | /codeforces/749_A.cpp | UTF-8 | 232 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, i;
scanf("%d", &n);
printf("%d\n", n / 2);
for(i = 0 ; i < n/2-1 ; i++) {
printf("2 ");
}
if(n % 2 == 0)
printf("2\n");
else
printf("3\n");
return 0;
} | true |
502da2df31fb2678cbc3ef7d3c4912826c0e3adb | C++ | s-sofism/c-sharp-labs | /laba4_2/Library_4.2/Library.cpp | UTF-8 | 2,262 | 3.09375 | 3 | [] | no_license | #include "Library.h"
#include "pch.h"
using namespace std;
double MillimetersToCentimeters(double number)
{
return number / 10;
}
double MillimetersToDecimeters(double number)
{
return number / 100;
}
double MillimetersToMeters(double number)
{
return number / 1000;
}
double MillimetersToKilometers(double number)
{
return number / 1000000;
}
double CentimetersToMillimeters(double number)
{
return number * 10;
}
double CentimetersToDecimeters(double number)
{
return number / 10;
}
double CentimetersToMeters(double number)
{
return number / 100;
}
double CentimetersToKilometers(double number)
{
return number / 100000;
}
double DecimetersToMillimeters(double number)
{
return number * 100;
}
double DecimetersToCentimeters(double number)
{
return number * 10;
}
double DecimetersToMeters(double number)
{
return number / 10;
}
double DecimetersToKilometers(double number)
{
return number / 10000;
}
double MetersToMillimeters(double number)
{
return number * 1000;
}
double MetersToCentimeters(double number)
{
return number * 100;
}
double MetersToDecimeters(double number)
{
return number * 10;
}
double MetersToKilometers(double number)
{
return number / 1000;
}
double KilometersToMillimeters(double number)
{
return number * 1000000;
}
double KilometersToCentimeters(double number)
{
return number * 100000;
}
double KilometersToDecimeters(double number)
{
return number * 10000;
}
double KilometersToMeters(double number)
{
return number * 1000;
} | true |
1cf41da6927ae25564dc81aa1c49d8d296ce4623 | C++ | Zeyel/Modelisation | /gprLoader.h | UTF-8 | 1,028 | 3 | 3 | [] | no_license | #pragma once
#include"Graph.h"
#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;
class gprLoader
{
void vertexListConstructor(ifstream& doc, string& content, Graph graph)
{
vector<string> verticeBuffer;
getline(doc, content, '\n');
do{
split(content, ' ', verticeBuffer);
graph.createVertice(stoi(verticeBuffer[0]), stoi(verticeBuffer[1]), verticeBuffer[2]);
} while (!content.empty());
}
void edgesListConstructor(ifstream& doc, string& content, Graph *graph)
{
vector<string> edgeBuffer;
getline(doc, content, '\n');
do{
split(content, ' ', edgeBuffer);
graph.createEdge(edgeBuffer[0], graph.getVerticeByName(edgeBuffer[1]), graph.getVerticeByName(edgeBuffer[2]), stof(edgeBuffer[3]), stof(edgeBuffer[4]));
} while (!content.empty());
}
void split(const string& s, char delimiter, vector<string>& tokens)
{
string token;
istringstream tokenStream(s);
while (getline(tokenStream, token, delimiter))
{
tokens.push_back(token);
}
}
};
| true |
d18bd3257295311bb62c0eebd480c879b8ac4566 | C++ | wogus3602/study | /박재현/이전/세로읽기.cpp | UTF-8 | 577 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
vector<string> ve;
int maxLength = 0;
for (int i = 0; i < 5; i++)
{
string row;
cin >> row;
if (maxLength < row.size())
{
maxLength = row.size();
}
ve.push_back(row);
}
for (int i = 0; i < maxLength; i++)
{
for (int j = 0; j < 5; j++)
{
if (ve[j][i] != NULL)
{
cout << ve[j][i];
}
}
}
} | true |
497e16e0939db124656d9d5c613f55decf712778 | C++ | PandaSB/rpi_alarm | /variables.cpp | UTF-8 | 931 | 2.703125 | 3 | [] | no_license | #include "variables.h"
#include <QDebug>
Variables* Variables::instance = 0;
Variables* Variables::getInstance()
{
if(!instance) {
instance = new Variables();
qDebug() << "getInstance(): First instance\n";
return instance;
}
else {
qDebug() << "getInstance(): previous instance\n";
return instance;
}
}
Variables::Variables()
{
alarmStatus = eAlarmOff ;
KeyIds = "01-000001676e36 01-000003303aec 01-0000055c4a1a";
CodeAlarm = "1234" ;
}
tAlarmStatus Variables::GetAlarmStatus()
{
return (alarmStatus) ;
}
void Variables::SetAlarmStatus ( tAlarmStatus newAlarmStatus)
{
alarmStatus = newAlarmStatus ;
}
bool Variables::CheckKeyId ( QString id )
{
if ((KeyIds.indexOf(id) != -1) && (id.length() == 15)) return true ;
else return (false) ;
}
bool Variables::CheckCodeAlarm ( QString code )
{
if (CodeAlarm.compare(code,Qt::CaseSensitive) == 0) return true ;
else return (false) ;
} | true |
d8c1fc3f6da91eb436a87897ff6a35fee9c951d7 | C++ | Yalfoosh/NAISP | /lab/lab-2/a-star-faster/main.cpp | UTF-8 | 3,557 | 3.21875 | 3 | [
"Apache-2.0"
] | permissive | /* This is not actually faster lmao */
#include <chrono>
#include <iostream>
#include <list>
#include <queue>
#include <set>
#define M 9
#define N 9
#define range 10
#define c_t std::chrono::high_resolution_clock::now()
#define ms std::chrono::duration_cast<std::chrono::milliseconds>
void printArray(uint16_t *problem, uint width, uint height) {
for (auto i = 0; i < height; ++i) {
for (auto j = 0; j < width; ++j)
std::cout << problem[i * width + j] << " ";
std::cout << std::endl;
}
}
struct Node {
public:
uint16_t* node;
uint16_t cost;
Node* parent;
Node(uint16_t* node, const uint16_t& cost, Node* parent) {
this->node = node;
this->cost = cost;
this->parent = parent;
}
};
class NodeGreater{
public:
bool operator()(Node* lhs, Node* rhs){
return lhs->cost > rhs->cost;
}
};
void print(uint16_t* problem, const uint& width, const uint& height, Node* last) {
if(last->parent != nullptr)
print(problem, width, height, last->parent);
auto offset = last->node - problem;
std::cout << "(" << offset / width << ", " << offset % width << ")" << std::endl;
}
std::list<uint16_t*> explore(const uint16_t* problem, const uint& width, const uint& height, uint16_t* current, const std::set<uint16_t*>& closed) {
auto toExplore = std::list<uint16_t*>();
auto offset = current - problem;
auto i = offset / width;
auto j = offset % width;
if(i != 0 && closed.find(current - width) == closed.end())
toExplore.emplace_back(current - width);
if(i < (height - 1) && closed.find(current + width) == closed.end())
toExplore.emplace_back(current + width);
if(j != 0 && closed.find(current - 1) == closed.end())
toExplore.emplace_back(current - 1);
if (j < (width - 1) && closed.find(current + 1) == closed.end())
toExplore.emplace_back(current + 1);
return toExplore;
}
void solve(uint16_t *problem, const uint& width, const uint& height, const bool verbose = true) {
auto open = std::priority_queue<Node*, std::vector<Node*>, NodeGreater>();
auto closed = std::set<uint16_t*>();
auto end = problem + (width * height - 1);
open.push(new Node(problem, *problem + width + height - 2, nullptr));
while(!open.empty()) {
auto opened = open.top();
open.pop();
if(opened->node == end) {
if (verbose) {
print(problem, width, height, opened);
std::cout << opened->cost << std::endl;
}
while(!open.empty()){
delete open.top();
open.pop();
}
closed.erase(closed.begin(), closed.end());
return;
}
else {
for(const auto& x: explore(problem, width, height, opened->node, closed)) {
open.push(new Node(x, opened->cost + *x + (x < opened->node ? 1 : -1), opened));
}
closed.insert(opened->node);
}
}
}
int main() {
srand(1208);
auto printTheArray = true;
auto problem = new uint16_t[M * N];
for (auto i = 0; i < M; ++i)
for (auto j = 0; j < N; ++j)
problem[i * N + j] = rand() % range;
if (printTheArray) {
printArray(problem, N, M);
std::cout << std::endl;
}
auto start = c_t;
solve(problem, N, M);
auto end = c_t;
std::cout << "Solving took " << ms(end - start).count() << " ms." << std::endl;
delete[] problem;
return 0;
}
| true |
4cbb110cc0851691b31e26c60f26ad7ec352bbff | C++ | YouJinTou/Beginner-C-Game-Programming | /Tutorial 14/Engine/Snake.cpp | UTF-8 | 5,254 | 3.078125 | 3 | [] | no_license | #include <cmath>
#include "Snake.h"
#include "Square.h"
Snake::Snake(int borderX, int borderY) :
borderX(borderX), borderY(borderY) {
parts = new SnakePart{ nullptr, StartX, StartY, HeadDefaultDir };
}
Snake::~Snake() {
delete[] parts;
}
SnakePart* Snake::Get() const
{
return parts;
}
void Snake::IncreaseSpeed()
{
velocity += 0.5;
}
bool Snake::HasBittenTail() const {
if (size <= 3) {
return false;
}
int headX = parts[0].loc.x;
int headY = parts[0].loc.y;
for (int i = 3; i < size; i++)
{
int partX = parts[i].loc.x;
int partY = parts[i].loc.y;
bool hasBittenTail =
headX < partX + PWidth &&
headY < partY + PHeight &&
headX + PWidth > partX &&
headY + PHeight > partY;
if (hasBittenTail) {
return true;
}
}
return false;
}
int Snake::Size() const {
return size;
}
void Snake::Update(const std::string& command)
{
if (shouldGrow) {
Grow();
}
UpdateHead(command);
UpdateBody();
}
void Snake::Grow()
{
SnakePart* newSnake = new SnakePart[size + 1];
for (int i = 0; i < size; i++)
{
newSnake[i] = parts[i];
}
SnakePart currentTail = newSnake[size - 1];
int x = currentTail.loc.x;
int y = currentTail.loc.y;
Location newTailLoc =
currentTail.dir == "up" ? Location{ x, y + PHeight } :
currentTail.dir == "down" ? Location{ x, y - PHeight } :
currentTail.dir == "left" ? Location{ x + PWidth, y } :
Location{ x - PWidth, y };
SnakePart newTail{ nullptr, newTailLoc, currentTail.dir };
newSnake[size] = newTail;
for (int i = size; i > 0; i--)
{
newSnake[i].next = &newSnake[i - 1];
}
//delete[] parts;
parts = newSnake;
size++;
}
void Snake::UpdateHead(std::string command)
{
SnakePart& head = parts[0];
if (command == "up" && !(currentDir == "down" || currentDir == "up")) {
currentDir = "up";
head.dir = "up";
}
else if (command == "down" && !(currentDir == "up" || currentDir == "down")) {
currentDir = "down";
head.dir = "down";
}
else if (command == "left" && !(currentDir == "right" || currentDir == "left")) {
currentDir = "left";
head.dir = "left";
}
else if (command == "right" && !(currentDir == "left" || currentDir == "right")) {
currentDir = "right";
head.dir = "right";
}
if (currentDir == "up") {
head.loc.y = CalculateUp(head.loc.y);
}
else if (currentDir == "down") {
head.loc.y = CalculateDown(head.loc.y);
}
else if (currentDir == "left") {
head.loc.x = CalculateLeft(head.loc.x);
}
else if (currentDir == "right") {
head.loc.x = CalculateRight(head.loc.x);
}
}
void Snake::UpdateBody()
{
int headIndex = 0;
for (size_t p = size - 1; p > headIndex; p--)
{
SnakePart nextPart = *parts[p].next;
int nextX = nextPart.loc.x;
int nextY = nextPart.loc.y;
int& currX = parts[p].loc.x;
int& currY = parts[p].loc.y;
if (Shifted(currX, currY, nextX, nextY)) {
continue;
}
bool goUp = currY - PHeight >= nextY;
bool goDown = currY + PHeight <= nextY;
bool goLeft = currX >= nextX + PWidth;
bool goRight = currX + PWidth <= nextX;
if (goUp) {
currY = CalculateUp(currY);
currX = RecalculateDim(currX, nextX);
}
else if (goDown) {
currY = CalculateDown(currY);
currX = RecalculateDim(currX, nextX);
}
else if (goLeft) {
currX = CalculateLeft(currX);
currY = RecalculateDim(currY, nextY);
}
else if (goRight) {
currX = CalculateRight(currX);
currY = RecalculateDim(currY, nextY);
}
}
}
int Snake::RecalculateDim(int curr, const int& next)
{
return curr > next ? curr -= 1 :
curr < next ? curr += 1 :
curr;
}
int Snake::CalculateUp(int currY) {
int y = (currY - velocity <= 0) ?
borderY - PHeight :
currY - velocity;
return y;
}
int Snake::CalculateDown(int currY)
{
int y = (currY + velocity >= borderY - PHeight) ?
0 + PHeight :
currY + velocity;
return y;
}
int Snake::CalculateLeft(int currX)
{
int x = (currX - velocity <= 0) ?
borderX - PWidth :
currX - velocity;
return x;
}
int Snake::CalculateRight(int currX)
{
int x = (currX + velocity >= borderX - PWidth) ?
0 + PWidth :
currX + velocity;
return x;
}
bool Snake::Shifted(int& currX, int& currY, const int& nextX, const int& nextY)
{
bool shifted = false;
bool shiftUp = (std::abs(currY - nextY) >= 2 * PHeight) && (nextY >= borderY - 2 * PHeight);
bool shiftDown = (std::abs(currY - nextY) >= 2 * PHeight) && nextY <= 2 * PHeight;
bool shiftLeft = (std::abs(currX - nextX) >= 2 * PWidth) && (nextX >= borderX - 2 * PWidth);
bool shiftRight = (std::abs(currX - nextX) >= 2 * PWidth) && (nextX <= 2 * PWidth);
if (shiftUp) {
currY = CalculateUp(currY);
currX = RecalculateDim(currX, nextX);
shifted = true;
}
else if (shiftDown) {
currY = CalculateDown(currY);
currX = RecalculateDim(currX, nextX);
shifted = true;
}
else if (shiftLeft) {
currX = CalculateLeft(currX);
currY = RecalculateDim(currY, nextY);
shifted = true;
}
else if (shiftRight) {
currX = CalculateRight(currX);
currY = RecalculateDim(currY, nextY);
shifted = true;
}
return shifted;
}
| true |
9b3cb3ac6d727b6776232b349e0ace7efd3a62de | C++ | pPanda-beta/Coderudite | /server_side/coderudite_ronin/helpers.hxx | UTF-8 | 1,955 | 2.59375 | 3 | [] | no_license |
#ifndef HELPERS_HXX
#define HELPERS_HXX
#include <string>
#include <cstdio>
#include <regex>
#include <map>
#include "qhttpserver.hpp"
#include "qhttpserverresponse.hpp"
#include "qhttpserverrequest.hpp"
#define Y2X(X) #X
#define MAC2STR(Y) Y2X(Y)
namespace
{
using namespace std;
using namespace qhttp;
using namespace qhttp::server;
auto convertCRLF2LF(auto &&str)
{
int i=0, j=0;
while( i < str.size()-1)
{
if(str[i]=='\r' and str[i+1]=='\n')
i++;
str[j++] = str[i++];
}
str[j]='\0';
return str;
}
template<typename T>
T deHexFilter(const T &v)
{
T org_v;
org_v.reserve(v.size());
for(size_t i=0; i<v.size(); i++)
if(v[i]!='%')
org_v+=v[i];
else
{
int c;
sscanf(v.data()+i+1,"%2x",&c);
org_v+=c;
i+=2;
}
return org_v;
}
map<string,string> parsePOST(auto &&req)
{
string requestString(req);
const static regex reg("[&]+");
replace(requestString.begin(), requestString.end(), '+', ' ');
map<string,string> parsed_req;
for(sregex_token_iterator iter(begin(requestString),end(requestString),reg,-1),end ; iter!=end; ++iter)
{
string &&t=*iter;
auto m=t.find_first_of('=');
if(m==string::npos || m>=t.size()-1)
parsed_req[t.substr(0,m)]="";
else
parsed_req[t.substr(0,m)]=deHexFilter(t.substr(m+1));
}
return parsed_req;
}
}
void inline writeDataOn(QHttpResponse *resp, const QByteArray &doc)
{
resp->end(doc);
}
void inline writeDataOn(QHttpResponse *resp, auto &&doc)
{
resp->end(QByteArray(doc.data()));
}
template<typename T>
void replyWith(QHttpResponse *resp, const T& doc, TStatusCode code)
{
resp->addHeader("Content-Length", QByteArray::number(doc.size()));
resp->addHeader("Access-Control-Allow-Origin"," * ");
resp->addHeader("Access-Control-Allow-Headers","GET,POST,PUT");
resp->setStatusCode(code);
writeDataOn(resp,doc);
}
template<typename T>
void replyWith(QHttpResponse *resp, const T& doc)
{
replyWith(resp,doc,ESTATUS_OK);
}
#endif // HELPERS_HXX
| true |
47d96b6fedce527f60401d9e32d0bc78642b94d4 | C++ | sust18023/ACM | /KuangBin/专题四 最短路练习(AK)/Til the Cows Come Home.cpp | UTF-8 | 1,484 | 3.125 | 3 | [] | no_license | /*
Til the Cows Come Home
POJ - 2387
https://cn.vjudge.net/problem/POJ-2387
题意:最短路裸题
输入:点 边
u -> v w
样例输入:
5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100
样例输出:
90
解法:
SPFA
*/
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<iostream>
using namespace std;
#define INF 0x3f3f3f
#define maxn 10010
struct node{
int u;
int v;
int w;
int next;
}edge[maxn],uedge[maxn];
int cnt,ucnt;
int t,n;
int head[maxn],uhead[maxn];
int dis[maxn], udis[maxn];
void init(){
memset(head,0,sizeof head);
memset(dis,INF,sizeof dis);
cnt=1;
}
void add(int u, int v, int w, node edge[], int &cnt,int *head){
edge[cnt].w=w;
edge[cnt].u=u;
edge[cnt].v=v;
edge[cnt].next=head[u];
head[u]=cnt++;
}
void spfa(int st,int dis[],int head[],node edge[]) {
dis[st] = 0;
queue<int>q;
q.push(st);
while (!q.empty()) {
int u = q.front();
q.pop();
for (int i = head[u]; i!=0; i = edge[i].next) {
int v = edge[i].v;
if (dis[v] > dis[u] + edge[i].w) {
dis[v] = dis[u] + edge[i].w;
q.push(v);
}
}
}
return;
}
int main(){
while(~scanf("%d %d", &t, &n)){
init();
int u,v,w;
for(int i=0;i<t;i++){
scanf("%d %d %d", &u, &v, &w);
add(u, v, w, edge, cnt, head);
add(v, u, w, edge, cnt, head);
//add(v, u, w, uedge, ucnt, uhead);
}
spfa(1, dis, head, edge);
cout<<dis[n]<<endl;
}
return 0;
}
| true |
b1fb8ce5910876dfbc8b00d0e87b30102ba49706 | C++ | danyfang/SourceCode | /cpp/leetcode/MinimumRectangle.cpp | UTF-8 | 1,320 | 3.15625 | 3 | [
"MIT"
] | permissive | //Leetcode Problem No 939 Minimum Area Rectangle
//Solution written by Xuqiang Fang on 12 Nov, 2018
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <stack>
#include <queue>
using namespace std;
class Solution{
public:
int minAreaRect(vector<vector<int>>& points) {
for(auto&p : points){
m[p[0]].insert(p[1]);
}
int ans = INT_MAX;
const int n = points.size();
for(int i=0; i<n; ++i){
for(int j=i+1; j<n; ++j){
auto& a = points[i];
auto& b = points[j];
if(a[0]!= b[0] && a[1]!=b[1]){
if(m[a[0]].count(b[1]) != 0 && m[b[0]].count(a[1])!= 0){
ans = min(ans, abs((a[0]-b[0])*(a[1]-b[1])));
//cout << a[0] <<"," << a[1] << "), (" << b[0] << "," << b[1] << endl;
//cout << abs((a[0]-b[0])*(a[1]-b[1])) << endl;
}
}
}
}
return ans == INT_MAX ? 0 : ans;
}
private:
unordered_map<int, unordered_set<int>> m;
};
int main(){
Solution s;
vector<vector<int>> points = {{1,1},{1,3},{3,1},{3,3},{2,2}};
cout << s.minAreaRect(points) << endl;
return 0;
}
| true |
8746436c3d148e020f5a07876d5af78cb16a7b55 | C++ | KhunJahad/String | /CountAndSay/main.cpp | UTF-8 | 576 | 2.578125 | 3 | [] | no_license | # include <bits/stdc++.h>
using namespace std;
void read_input(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
}
int main(){
read_input();
int n;
cin>>n;
string a[n+1];
a[1]="1";
for (int j=2;j<n+1;j++){
string prev_ans=a[j-1];
string ans="";
for (int i=0;i<prev_ans.size();i++){
char start=prev_ans[i];
int count=1;
while (i<prev_ans.size()-1 && prev_ans[i+1]==start){
count++;
i++;
}
ans+=to_string(count);
ans+=start;
}
a[j]=ans;
}
cout<<a[n]<<"\n";
return 0;
} | true |
60e3dd091712d7d2dc3978cf9d0a4f1e8a7ee806 | C++ | adityachirania/LEETCODE_PREP | /Construct Binary Tree from Preorder and Inorder Traversal Solution.cpp | UTF-8 | 2,025 | 3.421875 | 3 | [] | no_license | //https://leetcode.com/explore/interview/card/top-interview-questions-medium/108/trees-and-graphs/788/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder,int ind = 0,int in_start=0,int in_end=0)
{
// return NULL if vector is empty
if(inorder.size()==0)
return NULL;
// only while beginning the funtion call made from main will rely on default values initially and we need to set end as size of vector - 1
if(ind==0)
{
int p;
p = (int)inorder.size();
in_end = p-1;
}
// the value to be assigned to current node
int value = preorder[ind];
// variable that saves index where current value is inorder
int index;
for(int i = in_start;i<=in_end;i++)
{
if(inorder[i]==value)
{
index = i;
break;
}
}
// finding no. of elements in left and right subtrees
int left_no = index-in_start;
int right_no = in_end-index;
TreeNode *node;
// value assigned with the help of the constructor
node = new TreeNode(value);
// repeating same for both subtrees on the left and right
if(left_no>0)
node->left = buildTree(preorder,inorder,ind+1,in_start,index-1);
if(right_no>0)
node->right = buildTree(preorder,inorder,ind+left_no+1,index+1,in_end);
// return the pointer to subtree's root
return node;
}
};
| true |
00e2ada96d1afee4211ca0ac017f402fe57ff008 | C++ | cloudcalvin/vcd_assert | /src/sdf/types/delayfile.cpp | UTF-8 | 2,989 | 2.546875 | 3 | [] | no_license | #include "sdf/types/delayfile.hpp"
#include "sdf/types/cell.hpp"
#include <cassert>
using namespace SDF;
// DelayFile::DelayFile(DelayFileView dfw){
// }
std::string_view DelayFile::get_sdf_version() const noexcept
{
return sdf_version_;
}
std::optional<std::string_view> DelayFile::get_design_name() const noexcept
{
return design_name_;
}
bool DelayFile::has_design_name() const noexcept
{
return design_name_.has_value();
}
std::optional<std::string_view> DelayFile::get_date() const noexcept
{
return date_;
}
bool DelayFile::has_date() const noexcept
{
return date_.has_value();
}
std::optional<std::string_view> DelayFile::get_vendor() const noexcept
{
return vendor_;
}
bool DelayFile::has_vendor() const noexcept
{
return vendor_.has_value();
}
std::optional<std::string_view> DelayFile::get_program_name() const noexcept
{
return program_name_;
}
bool DelayFile::has_program_name() const noexcept
{
return program_name_.has_value();
}
std::optional<std::string_view> DelayFile::get_program_version() const noexcept
{
return program_version_;
}
bool DelayFile::has_program_version() const noexcept
{
return program_version_.has_value();
}
std::optional<std::string_view> DelayFile::get_process() const noexcept
{
return process_;
}
bool DelayFile::has_process() const noexcept
{
return process_.has_value();
}
std::optional<HChar> DelayFile::get_hierarchy_divider() const noexcept
{
return hierarchy_divider_;
}
bool DelayFile::has_hierarchy_divider() const noexcept
{
return hierarchy_divider_.has_value();
}
std::optional<Triple> DelayFile::get_voltage() const noexcept
{
return voltage_;
}
bool DelayFile::has_voltage() const noexcept
{
return voltage_.has_value();
}
std::optional<Triple> DelayFile::get_temperature() const noexcept
{
return temperature_;
}
bool DelayFile::has_temperature() const noexcept
{
return temperature_.has_value();
}
std::optional<TimeScale> DelayFile::get_timescale() const noexcept
{
return timescale_;
}
bool DelayFile::has_timescale() const noexcept
{
return timescale_.has_value();
}
std::vector<Cell> DelayFile::get_cells() const noexcept
{
return move(cells_);
}
std::size_t DelayFile::num_cells() const noexcept
{
return cells_.size();
}
Cell& DelayFile::get_cell(std::size_t index)
{
assert(index < num_cells());
return cells_.at(index);
}
std::vector<std::size_t> DelayFile::get_cell_indices_by_type(std::string &cell_type) const noexcept
{
std::vector<std::size_t> result;
std::size_t i = 0;
for(auto&& cell : cells_){
if(cell_type == cell.cell_type){
result.emplace_back(i);
}
i++;
}
return result;
}
std::vector<std::size_t> DelayFile::get_cell_indices_by_instance(CellInstance &cell_instance) const noexcept
{
std::vector<std::size_t> result;
std::size_t i = 0;
for(auto&& cell : cells_){
if(cell_instance == cell.cell_instance){
result.emplace_back(i);
}
i++;
}
return result;
}
| true |
5a6400b3fba1bf0a3c84263dff5468bd244d8e54 | C++ | Calasada/C-programming | /Chapter 16/Homework 6/Main.cpp | UTF-8 | 399 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cmath>
using namespace std;
double tol = 0.01;
double newtons(double, double);
int main() {
int num;
cout << "Number: ";
cin >> num;
cout << newtons(num, num);
return 0;
}
double newtons(double x, double a) {
if(abs(pow(a, 2) - x) <= tol) {
return a;
} else {
return newtons(x, (pow(a, 2) + x) / (2 * a));
}
} | true |
85932dc3219f572699121d77464d165f8c2c5089 | C++ | lishulongVI/leetcode | /cpp/206.Reverse Linked List(反转链表).cpp | UTF-8 | 1,220 | 3.5625 | 4 | [
"MIT"
] | permissive | /*
<p>Reverse a singly linked list.</p>
<p><strong>Example:</strong></p>
<pre>
<strong>Input:</strong> 1->2->3->4->5->NULL
<strong>Output:</strong> 5->4->3->2->1->NULL
</pre>
<p><b>Follow up:</b></p>
<p>A linked list can be reversed either iteratively or recursively. Could you implement both?</p>
<p>反转一个单链表。</p>
<p><strong>示例:</strong></p>
<pre><strong>输入:</strong> 1->2->3->4->5->NULL
<strong>输出:</strong> 5->4->3->2->1->NULL</pre>
<p><strong>进阶:</strong><br>
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?</p>
<p>反转一个单链表。</p>
<p><strong>示例:</strong></p>
<pre><strong>输入:</strong> 1->2->3->4->5->NULL
<strong>输出:</strong> 5->4->3->2->1->NULL</pre>
<p><strong>进阶:</strong><br>
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?</p>
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
}
}; | true |
6a748acd4a1ab5bebdefd9274bc7fd713b47d9f1 | C++ | Codinator29/InterviewBit | /TwoPointers/ClosestPairFromSortedArrays.cpp | UTF-8 | 1,943 | 3.765625 | 4 | [] | no_license | /*
Closest pair from sorted arrays
Problem Description
Given two sorted arrays of distinct integers, A and B, and an integer C, find and return the pair whose sum is closest to C and the pair has one element from each array.
More formally, find A[i] and B[j] such that abs((A[i] + B[j]) - C) has minimum value.
If there are multiple solutions find the one with minimum i and even if there are multiple values of j for the same i then return the one with minimum j.
Return an array with two elements {A[i], B[j]}.
*/
vector<int> Solution::solve(vector<int> &ar1, vector<int> &ar2, int x)
{
// Initialize the diff between pair sum and x.
int diff = INT_MAX;
int m = ar1.size();
int n = ar2.size();
// res_l and res_r are result indexes from ar1[] and ar2[]
// respectively
int res_l, res_r;
// Start from left side of ar1[] and right side of ar2[]
int l = 0, r = n-1;
while (l < m && r >= 0)
{
// If this pair is closer to x than the previously
// found closest, then update res_l, res_r and diff
if (abs(ar1[l] + ar2[r] - x) < diff)
{
res_l = l;
res_r = r;
diff = abs(ar1[l] + ar2[r] - x);
}
else if(abs(ar1[l] + ar2[r] - x) == diff)
{
if(l < res_l)
{
res_l = l;
res_r = r;
}
else if(l == res_l)
{
if(r < res_r)
{
res_r = r;
}
}
}
// If sum of this pair is more than x, move to smaller
// side
if (ar1[l] + ar2[r] > x)
r--;
else // move to the greater side
l++;
}
vector<int> ans;
ans.push_back(ar1[res_l]);
ans.push_back(ar2[res_r]);
return ans;
}
| true |
84b514f5861afc32def1f073758ac900e0c07785 | C++ | matmarczuk/micromouse | /logic/Board/src/boardgenerator.cpp | UTF-8 | 3,490 | 3.265625 | 3 | [] | no_license | #include "logic/Board/include/boardgenerator.h"
#include <vector>
#include <memory>
#include <stdlib.h>
#include <ctime>
BoardGenerator::BoardGenerator()
{
}
/*!
* \brief Generates now board. Allocates memory for it
* \param size - size choosen by user
*/
void BoardGenerator::generateNewBoard(int size)
{
srand( time( NULL ) );
std::vector<Cell> stack;
Cell** cellBoard = new Cell*[size];
for(int i = 0; i < size; ++i)
cellBoard[i] = new Cell[size];
for(int i = 0;i<size;i++)
{
for(int j = 0;j<size;j++)
{
cellBoard[i][j].pos_x = i;
cellBoard[i][j].pos_y = j;
}
}
// put square cell 2x2 inside the board
cellBoard[size/2][size/2].isVisited=true;
cellBoard[size/2][size/2].walls[0]=false;
cellBoard[size/2][size/2].walls[1]=false;
cellBoard[size/2-1][size/2].isVisited=true;
cellBoard[size/2-1][size/2].walls[1]=false;
cellBoard[size/2-1][size/2].walls[2]=false;
cellBoard[size/2-1][size/2-1].isVisited=true;
cellBoard[size/2-1][size/2-1].walls[2]=false;
cellBoard[size/2-1][size/2-1].walls[3]=false;
cellBoard[size/2][size/2-1].isVisited=true;
cellBoard[size/2][size/2-1].walls[0]=false;
cellBoard[size/2][size/2-1].walls[3]=false;
int x_index = size/2;
int y_index = size/2;
//int check
cellBoard[x_index][y_index].isVisited = true;
stack.push_back(cellBoard[x_index][y_index]);
while(1)
{
std::vector<int> rand_index;
x_index = stack.back().pos_x;
y_index = stack.back().pos_y;
int tmp_index = x_index - 1;
if (tmp_index > -1)
{
if(!cellBoard[x_index-1][y_index].isVisited)
rand_index.push_back(0);
}
tmp_index=y_index - 1;
if (tmp_index > -1)
{
if(!cellBoard[x_index][y_index-1].isVisited)
rand_index.push_back(1);
}
tmp_index = x_index + 1;
if (tmp_index < size)
{
if(!cellBoard[x_index+1][y_index].isVisited)
rand_index.push_back(2);
}
tmp_index = y_index + 1;
if(tmp_index < size)
{
if(!cellBoard[x_index][y_index+1].isVisited)
rand_index.push_back(3);
}
if (rand_index.empty())
{
stack.pop_back();
if(stack.empty())
break;
continue;
}
int rand_res = rand() % rand_index.size();
switch(rand_index[rand_res])
{
case 0:
cellBoard[x_index][y_index].walls[0]=false;
x_index--;
cellBoard[x_index][y_index].walls[2]=false;
break;
case 1:
cellBoard[x_index][y_index].walls[1]=false;
y_index--;
cellBoard[x_index][y_index].walls[3]=false;
break;
case 2:
cellBoard[x_index][y_index].walls[2]=false;
x_index++;
cellBoard[x_index][y_index].walls[0]=false;
break;
case 3:
cellBoard[x_index][y_index].walls[3]=false;
y_index++;
cellBoard[x_index][y_index].walls[1]=false;
break;
}
cellBoard[x_index][y_index].isVisited = true;
stack.push_back(cellBoard[x_index][y_index]);
}
emit setNewBoard(cellBoard, size);
}
| true |
e822fab77f8c3e8cbb1f099a96cf7b59a5ffb2ea | C++ | Klyta/12 | /Cavalry.cpp | UTF-8 | 852 | 2.84375 | 3 | [] | no_license | #include "Cavalry.h"
#include "Cell.h"
#include "iostream"
#include "string"
#include <map>
#include "LandScape.h"
#include "Bonus.h"
std::map<std::string, int> Cavalry::CBonus = { {"forest",10}, {"pound",-10} };
Cavalry::Cavalry(int Health, int Demage, const Cell *cell, Player& player) : Unit(Health, Demage, cell, player)
{
std::cout << "Cavalry(int,int)" << std::endl;
}
Cavalry::Cavalry(int Health, int Demage, const Cell* cell, Player* player) : Unit(Health, Demage, cell, *player)
{
std::cout << "Cavalry(int,int)*" << std::endl;
}
std::map<std::string, int>Cavalry::getMap()
{
return Cavalry::CBonus;
}
std::string Cavalry::getName()
{
std::string Name;
Name = "C";
std::cout << "getName-C" << std::endl;
return Name;
}
Cavalry::~Cavalry()
{
std::cout << "~Cavalry::Cavalry()" << std::endl;
} | true |
5adca2faf35c160cee496802cdf7ca6826ef5fd8 | C++ | NightRoadIx/Curso-C | /009A.CPP | WINDOWS-1252 | 1,514 | 3.375 | 3 | [] | no_license | /*
Curso de Programacin en C
Leccion 9
Archivos Binarios (escritura)
*/
#include <stdio.h>
/*
size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);
*/
#include <conio.h>
#include <stdlib.h>
/*
Manejo de archivos binarios en C
Para abrir un archivo en modo binario hay que especificar la opcin "b"
en el modo de apertura. Una de las caracterisitcas de los archivos binarios
es que optimizan la memoria ocupada por un archivo, sobre todo con campos
numricos. El problema con ellos es que solo pueden ser leidos en modo
binario dentro del entorno de C.
*/
/*Estrucutura para manejo de puntos*/
typedef struct punto
{
int x,y;
}PUNTO;
void main()
{
PUNTO p;
FILE *pp;
clrscr();
if( (pp=fopen("Puntos.txt","wb"))==NULL )
{
puts("\nError en la apertura de archivo"); getch(); exit(-1);
}
printf("\nIntroduce coordenadas de puntos [para acabar (0,0)]:\n");
do
{
scanf("%d %d",&p.x,&p.y);
//Checar que sea mayor que cero
while(p.x<0 || p.y<0)
{
printf("Coordenadas deben ser >=0 :\n");
scanf("%d %d",&p.x,&p.y);
}
//Cuando sean mayores a cero
if(p.x>0 || p.y>0)
{
/*
fwrite(direccin del buffer,tamao,num_elementos,puntero_archivo);
Escribe en un buffer de cualquier tipo de dato en un archivo binario
*/
fwrite(&p,sizeof(PUNTO),1,pp);
}
}
while(p.x>0 || p.y>0);
getch();
/*Cerrar archivo*/
fclose(pp);
} | true |
dca7744c858a11ab25547992848ea28fa695bd5a | C++ | ihalemi/Object-Oriented-Software-Development-C- | /Lab2/Text.cpp | UTF-8 | 1,902 | 3.4375 | 3 | [] | no_license | #include "Text.h"
namespace sict {
Text::Text() {
m_text = nullptr;
m_records = 0;
}
Text::Text(const std::string file) : m_records(0) {
std::ifstream f(file);
if (f.is_open()) {
// variables to count records
int counter = 0;
std::string newLine;
// do while loop to count the number of records
do {
std::getline(f, newLine, '\n');
counter++;
} while (!f.fail());
// allocate memory for the number of records in file
m_text = new std::string[counter];
f.clear();
f.seekg(0);
// copy records to newly allocated memory
for (int i = 0; i < m_records; i++) {
std::getline(f, m_text[i], '\n');
}
}
else {
// set to safe empty state
*this = Text();
}
}
Text::Text(const Text& src) {
init(src);
}
Text& Text::operator=(const Text& src) {
// check for self-assigment
if (this != &src) {
delete[] m_text;
init(src);
}
return *this;
}
Text::Text(Text&& src) {
*this = std::move(src);
}
Text& Text::operator=(Text&& src) {
delete[] m_text;
init(src);
return *this;
}
Text::~Text() {
delete[] m_text;
m_text = nullptr;
}
// logic for copy constructor and operator
void Text::init(const Text& src) {
// shallow copy
m_records = src.m_records;
// deep copy
if (src.m_text) {
// allocate memory
m_text = new std::string[m_records];
for (int i = 0; i < m_records; i++) {
m_text[i] = src.m_text[i];
}
}
}
// logic for move operator
void Text::init(Text&& src) {
if (this != &src) {
// exchange ownership by assigning memory
m_text = src.m_text;
m_records = src.m_records;
// delete RValue
src.m_text = nullptr;
src.m_records = 0;
}
}
size_t Text::size() const {
return m_records;
}
} // end of namespace sict | true |
e67ec8876eaccceeb400ed41d0f7791aebb0141e | C++ | pgmaginot/DARK_ARTS | /src/materials/Source_I_Constant.cc | UTF-8 | 860 | 2.609375 | 3 | [
"MIT"
] | permissive | /** @file Source_I_Constant.cc
* @author pmaginot
* @brief Implement the Source_I_Constant class
* \f$ Source_I_Constant = constant\f$
*/
#include "Source_I_Constant.h"
Source_I_Constant::Source_I_Constant(
const Input_Reader& input_reader, const int mat_num) :
VSource_I(),
m_t_start( input_reader.get_rad_source_start(mat_num) ),
m_t_end( input_reader.get_rad_source_end(mat_num) ),
m_isotropic_output(input_reader.get_rad_source_output(mat_num) )
{
}
double Source_I_Constant::get_intensity_source(const double position,
const int group, const int dir, const double time)
{
double val=0.;
if( ( (time > m_t_start) && (time < m_t_end)) || ( fabs( (time-m_t_end)/(m_t_end - m_t_start)) < 0.000) )
{
val = m_isotropic_output;
}
else
{
val =0.;
}
return val;
}
| true |
00bc05e36bd2c6224eb2e991e33be5e42d287c73 | C++ | pjshort/tachyon | /tachyon/io/bcf/BCFReader.h | UTF-8 | 5,674 | 2.78125 | 3 | [
"MIT"
] | permissive | #ifndef BCF_BCFREADER_H_
#define BCF_BCFREADER_H_
#include <cassert>
#include "BCFEntry.h"
#include "../compression/BGZFController.h"
namespace tachyon {
namespace bcf {
class BCFReader{
typedef BCFReader self_type;
typedef BCFEntry value_type;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef std::ptrdiff_t difference_type;
typedef std::size_t size_type;
typedef io::BasicBuffer buffer_type;
typedef io::BGZFController bgzf_controller_type;
typedef vcf::VCFHeader header_type;
typedef core::HeaderContig contig_type;
public:
enum bcf_reader_state{BCF_INIT, BCF_OK, BCF_ERROR, BCF_EOF, BCF_STREAM_ERROR};
public:
BCFReader();
BCFReader(const std::string& file_name);
~BCFReader();
class iterator{
private:
typedef iterator self_type;
typedef std::forward_iterator_tag iterator_category;
public:
iterator(pointer ptr) : ptr_(ptr) { }
void operator++() { ptr_++; }
void operator++(int junk) { ptr_++; }
reference operator*() const{ return *ptr_; }
pointer operator->() const{ return ptr_; }
bool operator==(const self_type& rhs) const{ return ptr_ == rhs.ptr_; }
bool operator!=(const self_type& rhs) const{ return ptr_ != rhs.ptr_; }
private:
pointer ptr_;
};
class const_iterator{
private:
typedef const_iterator self_type;
typedef std::forward_iterator_tag iterator_category;
public:
const_iterator(pointer ptr) : ptr_(ptr) { }
void operator++() { ptr_++; }
void operator++(int junk) { ptr_++; }
const_reference operator*() const{ return *ptr_; }
const_pointer operator->() const{ return ptr_; }
bool operator==(const self_type& rhs) const{ return ptr_ == rhs.ptr_; }
bool operator!=(const self_type& rhs) const{ return ptr_ != rhs.ptr_; }
private:
pointer ptr_;
};
// Element access
inline reference at(const size_type& position){ return(this->entries[position]); }
inline const_reference at(const size_type& position) const{ return(this->entries[position]); }
inline reference operator[](const size_type& position){ return(this->entries[position]); }
inline const_reference operator[](const size_type& position) const{ return(this->entries[position]); }
inline pointer data(void){ return(this->entries); }
inline const_pointer data(void) const{ return(this->entries); }
inline reference front(void){ return(this->entries[0]); }
inline const_reference front(void) const{ return(this->entries[0]); }
inline reference back(void){ return(this->entries[this->n_entries - 1]); }
inline const_reference back(void) const{ return(this->entries[this->n_entries - 1]); }
// Capacity
inline const bool empty(void) const{ return(this->n_entries == 0); }
inline const size_type& size(void) const{ return(this->n_entries); }
inline const size_type& capacity(void) const{ return(this->n_capacity); }
// Iterator
inline iterator begin(){ return iterator(&this->entries[0]); }
inline iterator end() { return iterator(&this->entries[this->n_entries]); }
inline const_iterator begin() const{ return const_iterator(&this->entries[0]); }
inline const_iterator end() const{ return const_iterator(&this->entries[this->n_entries]); }
inline const_iterator cbegin() const{ return const_iterator(&this->entries[0]); }
inline const_iterator cend() const{ return const_iterator(&this->entries[this->n_entries]); }
/**<
* Attempts to open a target input file. Internally
* checks if the input file is an actual BCF file and
* the first TGZF can be opened and the BCF header is
* valid.
* @param input Input target BCF file
* @return Returns TRUE upon success or FALSE otherwise
*/
bool open(const std::string input);
bool open(void);
/**<
* Loads another TGZF block into memory
* @return Returns TRUE upon success or FALSE otherwise
*/
bool nextBlock(void);
/**<
* Attempts to overload `entry` input BCFEntry with
* data
* @param entry Input BCFEntry that will be overloaded
* @return Returns TRUE upon success or FALSE otherwise
*/
bool nextVariant(reference entry);
/**<
* Attempts to load either `n_variants` number of variants or
* variants covering >= `bp_window` base pairs. The function
* is successful whenever n_variants or bp_window is satisfied
* or if there is no more variants to load.
* @param n_variants Number of variants
* @param bp_window Non-overlapping window size in base-pairs
* @param across_contigs Allow the algorithm to span over two or more different chromosomes
* @return Returns TRUE upon success or FALSE otherwise
*/
bool getVariants(const U32 n_variants, const double bp_window, bool across_contigs = false); // get N number of variants into buffer
inline const bool hasCarryOver(void) const{ return(this->n_carry_over); }
private:
/**<
* Parse the TGZF header of a block given
* the current buffer data loaded.
* Internal use only
* @return Returns TRUE on success or FALSE otherwise
*/
bool parseHeader(void);
public:
std::string file_name;
std::ifstream stream;
U64 filesize;
U32 current_pointer;
S32 map_gt_id;
buffer_type buffer;
buffer_type header_buffer;
bgzf_controller_type bgzf_controller;
header_type header;
bcf_reader_state state;
size_type n_entries;
size_type n_capacity;
size_type n_carry_over;
pointer entries;
U64 b_data_read;
};
}
}
#endif /* BCF_BCFREADER_H_ */
| true |
09298b7ca3813b78c89f3279a490505d654f3c69 | C++ | zhe13/Pettern | /第09章 人脸的检测与定位/人脸定位实例/HairFace.cpp | GB18030 | 2,153 | 2.640625 | 3 | [] | no_license | //////////////////////////////////////////////////////////////////////
// HairFace.cpp: CHairFaceӿ
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "FaceDetect.h"
#include "HairFace.h"
//////////////////////////////////////////////////////////////////////
// 캯/
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// 캯
// sourceԭʼ
// widthͼ
// heightͼ߶
//////////////////////////////////////////////////////////////////////
CHairFace::CHairFace(RGBQUAD ** source,int width,int height)
{
m_nWidth = width;
m_nHeight= height;
m_bBinaryOK = false;
m_pSourceData = source;
m_pBinaryArray = new BYTE*[height];
for(int i=0;i <height; i++)
m_pBinaryArray[i] = new BYTE[width];
}
//////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////
CHairFace::~CHairFace()
{
if(m_pBinaryArray!=NULL)
{
for(int i=0;i<m_nHeight;i++)
if(m_pBinaryArray[i]!=NULL) delete m_pBinaryArray[i];
delete m_pBinaryArray;
}
}
//////////////////////////////////////////////////////////////////////
// ͷλ
//////////////////////////////////////////////////////////////////////
void CHairFace::MarkHairFace()
{
int i,j;
for(i=0;i<m_nHeight;i++)
for(j=0;j<m_nWidth ;j++)
{
double r,g,Y,temp;
temp = m_pSourceData[i][j].rgbGreen
+m_pSourceData[i][j].rgbRed
+m_pSourceData[i][j].rgbBlue;
r = (double)m_pSourceData[i][j].rgbRed/temp;
g = (double)m_pSourceData[i][j].rgbGreen/temp;
Y = 0.30*m_pSourceData[i][j].rgbRed+0.59*m_pSourceData[i][j].rgbGreen
+0.11*m_pSourceData[i][j].rgbBlue;
if(g<0.398 && g > 0.246 && r<0.664 && r>0.333 && r>g && g>=0.5*(1-r))
{
m_pBinaryArray[i][j] = 0; //λ
}
else if(Y<40)
{
m_pBinaryArray[i][j] = 1; //ͷλ
}
else
{
m_pBinaryArray[i][j] = 2; //ʲôҲ
}
}
m_bBinaryOK = true;
}
| true |
5917b0c7e21c3a019e2455e361625060a5ebbba8 | C++ | xukunn1226/VRI3 | /Development/Src/Core/Src/Color.cpp | UTF-8 | 1,120 | 2.921875 | 3 | [] | no_license | #include "CorePCH.h"
#include "Color.h"
const FColor FColor::White(1.0f, 1.0f, 1.0f);
const FColor FColor::Black(0.0f, 0.0f, 0.0f);
FColor FColor::Desaturate(FLOAT Desaturation) const
{
FLOAT L = R * 0.3f + G * 0.59f + B * 0.11f;
return Lerp(*this, FColor(L, L, L, 0.0f), Desaturation);
}
FLinearColor FColor::ConvertToLinear() const
{
return FLinearColor(Clamp( (INT)(appPow(R, 1.0f/2.2f)), 0, 255 ),
Clamp( (INT)(appPow(G, 1.0f/2.2f)), 0, 255 ),
Clamp( (INT)(appPow(B, 1.0f/2.2f)), 0, 255 ),
Clamp( (INT)(A * 255.0f), 0, 255 ));
}
FColor FColor::ConvertToColor(const FLinearColor &C)
{
return FColor(C.R/255.0f, C.G/255.0f, C.B/255.0f, C.A/255.0f);
}
FLinearColor::FLinearColor(const FColor& C)
: A(Clamp((INT)(C.A * 255.0f), 0, 255)),
R(Clamp((INT)(appPow(C.R, 1.0f/2.2f) * 255.0f), 0, 255)),
G(Clamp((INT)(appPow(C.G, 1.0f/2.2f) * 255.0f), 0, 255)),
B(Clamp((INT)(appPow(C.B, 1.0f/2.2f) * 255.0f), 0, 255))
{}
FLinearColor FLinearColor::MakeRandomColor()
{
FLinearColor C;
C.B = appRand() % 255;
C.G = appRand() % 255;
C.G = appRand() % 255;
C.A = appRand() % 255;
return C;
} | true |
4e1b5ef48a2369e8c314b58d085217127211b6d3 | C++ | wanname777/demo | /main.cpp | UTF-8 | 276 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include "Book.h"
using namespace std;
int main() {
cout << "Hello, World!" << endl;
Book book(12.5);
cout << book.getPrice() << endl;
book.setPrice(35);
cout << book.getPrice() << endl;
cout << Book::num << endl;
return 0;
}
| true |
feb988a08b791fd59c4ab031fbad949439e7892c | C++ | Harry-Li/leetcode | /047. Permutations II/solution.h | UTF-8 | 757 | 2.9375 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<vector<int>>res;
vector<int>tnums;
vector<bool>used(nums.size(),false);
sort(nums.begin(),nums.end());
search(res, tnums, nums,used);
return res;
}
void search(vector<vector<int>>&res, vector<int>&tnums, vector<int>&nums,vector<bool>&used) {
if (tnums.size() == nums.size()) {
res.push_back(tnums);
//return;
}
else {
for (int i = 0; i<nums.size(); i++) {
if (used[i]||i>0&&nums[i]==nums[i-1]&&!used[i-1]) continue;
used[i] = true;
tnums.push_back(nums[i]);
search(res, tnums, nums,used);
used[i] = false;
tnums.pop_back();
}
}
}
};
| true |
9a9861453532d89b47754e61845017ac006fb4fc | C++ | yasminalvx/Uri-cplusplus | /1066.cpp | UTF-8 | 644 | 3.109375 | 3 | [] | no_license | //Yasmin Alves
//29.06.2020
#include <iostream>
using namespace std;
int main() {
int x; int pos = 0, i = 0, neg = 0, par = 0, impar = 0;
while (i < 5) {
cin >> x;
if (x > 0) {
pos ++;
} else if (x != 0) {
neg++;
}
if (x%2 == 0) {
par++;
} else {
impar++;
}
i ++;
}
cout << par << " valor(es) par(es)" << endl;
cout << impar << " valor(es) impar(es)" << endl;
cout << pos << " valor(es) positivo(s)" << endl;
cout << neg << " valor(es) negativo(s)" << endl;
return 0;
}
| true |
8cc0b96ef1c7d265de601423a7c0f4b5e54d6d64 | C++ | wwydmanski/Neural-network | /includes/Network.h | UTF-8 | 6,004 | 3.140625 | 3 | [] | no_license | #ifndef Network_H
#define Network_H
#include <iostream>
#include <vector>
#include <cmath>
#include "Layer.h"
#define E 2.71828182845904523536
using namespace std;
class Network
{
private:
vector<Layer> layers;
int inputSize;
int outputSize;
bool bias;
double* multiplyLayers(vector<double> in1, double** in2, int lay1Neurons, int lay2Neurons);
double* multiplyLayers(double* in1, double **in2, int lay1Neurons, int lay2Neurons);
double activation(double value);
double derivative(double value);
public:
Network(int inputSize, int outputSize, bool bias);
void importData(double* data);
double* calculate(vector<double> input);
void train(vector<vector<double>> input, vector<vector<double>> output, int times, int dataSize);
};
Network::Network(int iSize, int oSize, bool bis)
{
inputSize = iSize;
outputSize = oSize;
bias = bis;
Layer input(4, inputSize);
layers.push_back(input);
Layer output(outputSize, 4);
layers.push_back(output);
}
double* Network::calculate(vector<double> input)
{
double* answ = multiplyLayers(input, layers[0].toMatrix(), inputSize, layers[0].neuronNumber);
layers[0].values = answ;
// for(int i=1; i<layers.size();i++)
// {
// answ = multiplyLayers(answ, layers[i].toMatrix(), layers[i-1].neuronNumber, layers[i].neuronNumber);
// layers[i].values = answ;
// }
answ = multiplyLayers(answ, layers[1].toMatrix(), layers[0].neuronNumber, layers[1].neuronNumber);
return answ;
}
double* Network::multiplyLayers(double* in1, double **in2, int lay1Neurons, int lay2Neurons)
{
vector<double> temp;
for(int i=0;i<lay1Neurons;i++)
temp.push_back(in1[i]);
return multiplyLayers(temp, in2, lay1Neurons, lay2Neurons);
}
double* Network::multiplyLayers(vector<double> in1, double **in2, int lay1Neurons, int lay2Neurons)
{
//input is a horizontal array
//[--1] (bias)
//each layer will have to be a x*y array, x=neuron number, y=weights number + 1 (bias)
//[----] w1
//[----] w2
//[----] b
double* answer = new double[lay2Neurons];
for(int i=0;i<lay2Neurons; i++)
{
double cell=0;
for(int j=0; j<lay1Neurons; j++)
cell+=in1[j]*in2[i][j];
if(bias)
cell+=in2[i][lay1Neurons]; //Include bias
answer[i] = activation(cell);
}
return answer;
}
void Network::train(vector<vector<double>> input, vector<vector<double>> output, int times, int dataSize)
{
double** l2calculated = new double*[dataSize];
double** l2Error = new double*[dataSize];
double** l2Delta = new double*[dataSize];
double** l1calculated = new double*[dataSize];
double** l1Error = new double*[dataSize];
double** l1Delta = new double*[dataSize];
for(int t=0; t<times; t++)
{
//Calculate our response
for(int i=0;i<dataSize;i++)
{
l2calculated[i] = calculate(input[i]);
l1calculated[i] = layers[0].values;
l2Error[i] = new double[layers[1].neuronNumber];
l2Delta[i] = new double[layers[1].neuronNumber];
l1Error[i] = new double[layers[0].neuronNumber];
l1Delta[i] = new double[layers[0].neuronNumber];
}
//Calculate error
for(int i=0;i<dataSize;i++)
for(int j=0;j<layers[1].neuronNumber;j++)
l2Error[i][j] = output[i][j] - l2calculated[i][j];
//Weight error by derivative
for(int i=0;i<dataSize;i++)
for(int j=0;j<layers[1].neuronNumber;j++)
l2Delta[i][j] = l2Error[i][j]*derivative(l2calculated[i][j]);
//Calculate hidden layer error
for(int i=0;i<dataSize;i++)
for(int j=0;j<layers[0].neuronNumber;j++)
for(int k=0; k<layers[1].neuronNumber; k++)
l1Error[i][j] = l2Delta[i][k]*layers[1].weights[k][j];
//Weight it by derivative
for(int i=0;i<dataSize;i++)
for(int j=0;j<layers[0].neuronNumber;j++)
l1Delta[i][j] = l1Error[i][j]*derivative(l1calculated[i][j]);
//Update weights
for(int i=0;i<dataSize;i++)
for(int j=0;j<layers[1].neuronNumber;j++)
for(int k=0;k<layers[1].weightsPerNeuron;k++)
{
if(k==layers[0].neuronNumber) //Bias
layers[1].weights[j][k]+=l2Delta[i][j];
else
layers[1].weights[j][k]+=l2Delta[i][j]*l1calculated[i][k];
}
for(int i=0;i<dataSize;i++)
for(int j=0;j<layers[0].neuronNumber;j++)
for(int k=0;k<layers[0].weightsPerNeuron;k++)
{
if(k==inputSize) //Bias
layers[0].weights[j][k]+=l1Delta[i][j];
else
layers[0].weights[j][k]+=l1Delta[i][j]*input[i][k];
}
if(t==times-1)
{
double err=0;
for(int i=0;i<dataSize;i++)
for(int j=0;j<layers[1].neuronNumber;j++)
err+=abs(l2Error[i][j]);
err/=(layers[1].neuronNumber*dataSize);
cout<<"Error: "<<err<<endl;
}
for(int i=0;i<dataSize;i++)
{
delete []l2Error[i];
delete []l2Delta[i];
delete []l1Error[i];
delete []l1Delta[i];
delete []l2calculated[i];
delete []l1calculated[i];
}
}
delete []l2Error;
delete []l2Delta;
delete []l1Error;
delete []l1Delta;
delete []l2calculated;
delete []l1calculated;
}
double Network::activation(double value)
{
double answ = 1/(1+pow(E, -value));
return answ;
}
double Network::derivative(double value)
{
double answ = pow(E, -value)/pow(1+pow(E,-value), 2);
return answ;
}
#endif | true |
a5a3a29aecfa8426f5401173bc84ce3c94c07ab3 | C++ | vikaskbm/pepcoding | /foundation/cpp/2_recursion_and_backtracking/5_recursion_backtracking/3.cpp | UTF-8 | 1,520 | 3.78125 | 4 | [
"MIT"
] | permissive | // N Queens
// 1. You are given a number n, the size of a chess board.
// 2. You are required to place n number of queens in the n * n cells of board such that no queen can kill another.
// Note - Queens kill at distance in all 8 directions
// 3. Complete the body of printNQueens function - without changing signature - to calculate and print all safe configurations of n-queens. Use sample input and output to get more idea.
// n=4
// 0-1, 1-3, 2-0, 3-2, .
// 0-2, 1-0, 2-3, 3-1, .
#include<iostream>
#include<vector>
using namespace std;
bool isQueenSafe(vector <vector <int>> board, int row, int col) {
for(int r=row-1, c=col; r >=0; r--){
if(board[r][c]==1){
return false;
}
}
for(int r=row-1, c=col-1; r>=0 && c>=0; r--, c--){
if(board[r][c]==1){
return false;
}
}
for(int r=row-1, c=col+1; c<board.size() && r>=0; c++, r--){
if(board[r][c]==1){
return false;
}
}
return true;
}
void printNQueen(vector <vector <int>> board, int r, string psf){
if(r==board.size()){
cout << psf+"." << endl;
return;
}
for(int c=0; c < board.size(); c++){
if(isQueenSafe(board, r, c)==true){
board[r][c] = 1;
printNQueen(board, r+1, psf+to_string(r)+"-"+to_string(c)+", ");
board[r][c] = 0;
}
}
}
int main() {
int n {};
cin >> n;
vector <vector <int>> board(n, vector <int> (n, 0));
printNQueen(board, 0, "");
} | true |
eaa1fdefbb9ff153f91ed1a5e2260595a041d9f7 | C++ | Kejie-Wang/lsh | /util/random.h | UTF-8 | 1,399 | 3.375 | 3 | [] | no_license | #ifndef _LSH_RAMDOM_H_
#define _LSH_RAMDOM_H_
#include <cstdlib>
#include <cmath>
#include <cassert>
namespace lsh
{
/**
* Generate a uniform random variable between min and max
* @param min: The lower bound
* @param max: The upper bound
*/
double genUniformRandom(double min, double max)
{
assert(min < max);
double f = (double)rand() / RAND_MAX;
return min + f*(max-min);
}
/**
* Generate a standard gaussiam random varible
* Use Box–Muller method X = sqrt(-2*ln(U))*cos(2*PI*V) where U, V are distributed uniformly on (0,1)
*/
double genGaussianRandom()
{
double x1, x2;
do
{
x1 = genUniformRandom(0.0, 1.0);
}while(x1==0); //log(0) is not allowed
x2 = genUniformRandom(0.0, 1.0);
const double PI = asin(1)*2;
return sqrt(-2*log(x1))*cos(2*PI*x2);
}
/**
* Generate a random fixed random vector
*/
std::vector<double> genGaussianRandVec(int veclen)
{
std::vector<double> vec;
vec.reserve(veclen);
while(veclen--)
vec.push_back(genGaussianRandom());
return vec;
}
int getRandInt(int min, int max)
{
assert(min <= max);
int r;
r = min + (int)((max - min + 1.0) * rand() / (RAND_MAX + 1.0));
assert(r >= min && r <= max);
return r;
}
std::vector<int> genUniformRandIntVec(int min, int max, int veclen)
{
std::vector<int> vec;
vec.reserve(veclen);
for(int i=0;i<veclen;++i)
vec.push_back(getRandInt(min, max));
return vec;
}
}
#endif //_LSH_RAMDOM_H_ | true |
55926bc4b83301fa9cdba52393679b49434d72b1 | C++ | kkogoro/OI | /Luogu/P3765/P3765.cpp | UTF-8 | 6,916 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <ctime>
#include <cstdlib>
#include <cstdio>
inline int read() {
int x = 0;
char ch = getchar();
while (ch < '0' || ch > '9') {
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = x * 10 + ch - '0';
ch = getchar();
}
return x;
}
const int MAXN = 500007;
typedef std::pair<int, int> PII;
namespace SegmentTree {
struct Node {
int lc, rc, cnt, num;
} node[MAXN * 2];
int cntNode, root;
#define L(x) node[x].lc
#define R(x) node[x].rc
#define V(x) node[x].num
#define C(x) node[x].cnt
inline void pushUP(const int &x) {
if (V(L(x)) == V(R(x))) {
C(x) = C(L(x)) + C(R(x));
V(x) = V(L(x));
}
else {
if (C(L(x)) == C(R(x))) {
C(x) = V(x) = 0;
}
else if (C(L(x)) < C(R(x))) {
C(x) = C(R(x)) - C(L(x));
V(x) = V(R(x));
}
else {
C(x) = C(L(x)) - C(R(x));
V(x) = V(L(x));
}
}
return;
}
void modify(int &x, int l, int r, int pos, int val) {
if (x == 0) x = ++cntNode;
if (l == r) {
C(x) = 1;
V(x) = val;
return;
}
int mid = (l + r) >> 1;
if (pos <= mid) modify(L(x), l, mid, pos, val);
else modify(R(x), mid + 1, r, pos, val);
pushUP(x);
return;
}
PII query(int cur, int l, int r, int x, int y) {
if (x <= l && r <= y) {
return PII(V(cur), C(cur));
}
int mid = (l + r) >> 1;
PII L_ans = PII(0, 0), R_ans = PII(0, 0), ret = PII(0, 0);
if (x <= mid) {
L_ans = query(L(cur), l, mid, x, y);
}
if (y > mid) {
R_ans = query(R(cur), mid + 1, r, x, y);
}
if (L_ans.first == R_ans.first) {
ret = PII(L_ans.first, L_ans.second + R_ans.second);
}
else {
if (L_ans.second == R_ans.second) {
ret = PII(0, 0);
}
else if (L_ans.second < R_ans.second) {
ret = PII(R_ans.first, R_ans.second - L_ans.second);
}
else {
ret = PII(L_ans.first, L_ans.second - R_ans.second);
}
}
return ret;
}
#undef L
#undef R
#undef V
#undef C
}
namespace Treap {
const int INF = 100000000;
struct Node {
int lc, rc, num, sum, dat;
} node[MAXN * 10];
int cntNode, root[MAXN];
#define L(x) node[x].lc
#define R(x) node[x].rc
#define V(x) node[x].num
#define S(x) node[x].sum
#define D(x) node[x].dat
inline int newNode(int val) {
++cntNode;
V(cntNode) = val;
D(cntNode) = std::rand();
S(cntNode) = 1;
return cntNode;
}
inline void pushUP(int x) {
if (x != 0) {
S(x) = S(L(x)) + S(R(x)) + 1;
}
return;
}
inline void build(int n) {
for (int i = 1; i <= n; ++i) {
root[i] = newNode(-INF);
R(root[i]) = newNode(INF);
pushUP(root[i]);
}
return;
}
inline void zig(int &p) {
int q = L(p);
L(p) = R(q), R(q) = p, p = q;
pushUP(R(p));
pushUP(p);
return;
}
inline void zag(int &p) {
int q = R(p);
R(p) = L(q), L(q) = p, p = q;
pushUP(L(p));
pushUP(p);
return;
}
void insert(int &p, int val) {
if (!p) {
p = newNode(val);
return;
}
/* no use
if (val == V(p)) {
++C(p);
pushUP(p);
return;
}
*/
if (val < V(p)) {
insert(L(p), val);
if (D(L(p)) > D(p)) {
zig(p);
}
}
else {
insert(R(p), val);
if (D(R(p)) > D(p)) {
zag(p);
}
}
pushUP(p);
return;
}
void erase(int &p, int val) {
if (!p) {
return;
}
if (val == V(p)) {
/* no use
if (C(p) > 1) {
--C(p);
}
*/
if (L(p) || R(p)) {
if (!R(p) || D(L(p)) > D(R(p))) {
zig(p);
erase(R(p), val);
}
else {
zag(p);
erase(L(p), val);
}
}
else {
p = 0;
}
}
else {
val < V(p) ? erase(L(p), val) : erase(R(p), val);
}
pushUP(p);
return;
}
int getRank(int &p, int val) {
if (!p) {
return 0;
}
if (val == V(p)) {
return S(L(p)) + 1;
}
if (val < V(p)) {
return getRank(L(p), val);
}
return S(L(p)) + 1 + getRank(R(p), val);
}
#undef L
#undef R
#undef V
#undef S
#undef D
}
namespace BST {
inline void init(int n) {
Treap::build(n);
return;
}
inline bool query(int val, int l, int r) {
return (Treap::getRank(Treap::root[val], r) - Treap::getRank(Treap::root[val], l - 1) > ((r - l + 1) >> 1));
}
inline void insert(int val, int pos) {
Treap::insert(Treap::root[val], pos);
return;
}
inline void erase (int val, int pos) {
Treap::erase(Treap::root[val], pos);
return;
}
}
int org_data[MAXN];
inline void data_init(int n) {
BST::init(n);
for (int i = 1; i <= n; ++i) {
org_data[i] = read();
SegmentTree::modify(SegmentTree::root, 1, n, i, org_data[i]);
BST::insert(org_data[i], i);
}
return;
}
inline void solve(int n, int m) {
for (int i = 1; i <= m; ++i) {
int l = read();
int r = read();
int s = read();
int k = read();
PII ans = SegmentTree::query(SegmentTree::root, 1, n, l, r);
if (ans.first != 0) {
if (BST::query(ans.first, l, r) == true) {
s = ans.first;
}
}
printf("%d\n", s);
for (int i = 1; i <= k; ++i) {
int pos = read();
BST::erase(org_data[pos], pos);
BST::insert(s, pos);
SegmentTree::modify(SegmentTree::root, 1, n, pos, s);
org_data[pos] = s;
}
}
PII ans = SegmentTree::query(SegmentTree::root, 1, n, 1, n);
if (ans.first != 0 && BST::query(ans.first, 1, n) == true) {
printf("%d\n", ans.first);
}
else {
printf("-1\n");
}
}
int main() {
srand(time(NULL));
int n = read();
int m = read();
data_init(n);
solve(n, m);
return 0;
}
| true |
452f72c3d57623c58d9e07be0200944a10379565 | C++ | bonopi07/backjoon_practice | /9095_2.cpp | UTF-8 | 390 | 3.140625 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
using namespace std;
int go(int sum, int goal) {
if (sum > goal)
return 0;
if (sum == goal)
return 1;
int now = 0;
for (int i = 1; i <= 3; ++i) {
now += go(sum + i, goal);
}
return now;
}
int main()
{
freopen("input.txt", "r", stdin);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
cout << go(0, n) << '\n';
}
return 0;
} | true |
dfa75ec4b1794aab901daba62019e202f6a82996 | C++ | Pandamonium-san/Resim | /ResimBuffer.h | UTF-8 | 1,281 | 3.375 | 3 | [] | no_license | #pragma once
#include <vector>
namespace Resim
{
class Buffer
{
public:
Buffer(size_t aBytes);
size_t Write(void* aData, size_t aBytes);
template<class T>
size_t Write(const T& aData);
template<class T>
size_t Write(T&& aData);
void* Read(size_t aOffset, size_t aBytes);
template<class T>
T& Read(size_t aOffset);
void Set(size_t aOffset, void* aData, size_t aBytes);
void Remove(size_t aOffset, size_t aBytes);
void Clear();
size_t Size() const;
private:
size_t mySize;
size_t myMaxSize;
std::vector<char> myBuffer;
};
template<class T>
inline size_t Buffer::Write(const T& aData)
{
assert(myMaxSize >= mySize + sizeof(T) && "Buffer is out of memory");
size_t offset = mySize;
char* ptr = myBuffer.data() + offset;
new(ptr) T(aData);
mySize += sizeof(T);
return offset;
}
template<class T>
inline size_t Buffer::Write(T&& aData)
{
assert(myMaxSize >= mySize + sizeof(T) && "Buffer is out of memory");
size_t offset = mySize;
char* ptr = myBuffer.data() + offset;
new(ptr) T(std::forward<T>(aData));
mySize += sizeof(T);
return offset;
}
template<class T>
inline T& Buffer::Read(size_t aOffset)
{
void* data = Read(aOffset, sizeof(T));
T* tptr = reinterpret_cast<T*>(data);
return *tptr;
}
} | true |
e114a5cc520ea5699a39bff060a9594531ee16e5 | C++ | goswami-rahul/competitive-coding | /CompetitiveProgramming/codeforces/CF305-D2-E.cpp | UTF-8 | 2,868 | 2.734375 | 3 | [] | no_license | /**
* Observation: substrings separated with such i which can never be a valid move,
* are independent to each other.
* So we can calculate grundy of each substring with streak of palindrome centers
* and xor them for grundy of game.
**/
#include <bits/stdc++.h>
using namespace std;
#define SZ(v) int((v).size())
#define ALL(vec) (vec).begin(),(vec).end()
typedef long long i64;
template<typename T> inline bool uax(T &x, T y) {return (y > x) ? x = y, true : false;}
template<typename T> inline bool uin(T &x, T y) {return (y < x) ? x = y, true : false;}
#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); \
stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string>) {}
template<typename T1,typename T2> ostream& operator<<(ostream& os, pair<T1,T2> buf) {
return os << "(" << buf.first << ": " << buf.second << ")"; }
#define DefOut(Con) template<typename T>ostream&operator<<(ostream&os,Con<T>&A){ bool f = false; os << "{"; \
for (const auto e: A) { if (f) os << ", "; os << e; f = true; } return os << "}"; }
#define DefOut2(Con) template<typename K,typename V>ostream&operator<<(ostream&os,Con<K,V>&A) \
{ bool f = false; os << "{"; for (auto &e: A) { if (f) os << ", "; os << e; f = true; } return os << "}"; }
template<typename T>ostream &operator << (ostream &os,vector<vector<T>>& A) {
for (auto &B: A) os << '\n' << B; return os; }
DefOut(vector) DefOut(set) DefOut(multiset) DefOut2(map)
template<typename T,typename... Args> void err(istream_iterator<string> it, T a, Args... args) {
cerr << *it << " =: " << a << endl; err(++it, args...); }
template<typename T> void kek(T ans) {cout << ans << endl; exit(0);}
int const MOD = 1e9 + 7;
long long const INF = 1e18;
/***********************************************************************/
vector<int> dp;
int grundy(int n) {
if (n <= 0) return 0;
int &g = dp[n];
if (~g) return g;
set<int> has;
for (int i = 1; i <= (n + 1) / 2; ++i) {
has.insert(grundy(i - 2) ^ grundy(n + 1 - i - 2));
}
g = 0;
for (auto it = has.begin();; ++it, ++g) {
if (it == has.end() || *it != g) return g;
}
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
string s;
cin >> s;
const int n = SZ(s);
dp.assign(n, -1);
int g = 0;
vector<int> inds, cnts;
for (int i = 0, cnt = 0; i < n; ++i) {
if (i > 0 && i + 1 < n && s[i - 1] == s[i + 1]) {
++cnt;
} else if (cnt > 0) {
inds.push_back(i - cnt);
cnts.push_back(cnt);
g ^= grundy(cnt);
cnt = 0;
}
}
if (g == 0) kek("Second");
cout << "First\n";
for (int i = 0; i < SZ(inds); ++i) {
for (int j = 1; j <= cnts[i]; ++j) {
if ((grundy(cnts[i]) ^ grundy(j - 2) ^ grundy(cnts[i] + 1 - j - 2)) == g) {
kek(inds[i] + j);
}
}
}
return 0;
}
| true |
c1e6c5eb7da5185712a9dad40de45ea462c49875 | C++ | souraavv/Algorithms | /data structure/BIT_Fenwick tree/BIT1_count_inverse.cpp | WINDOWS-1252 | 2,827 | 3.203125 | 3 | [] | no_license | #include<bits/stdc++.h>
#define ll long long
#define maxn 10001
#define mk make_pair
using namespace std;
ll sum;
/*
https://www.geeksforgeeks.org/count-inversions-array-set-3-using-bit/
*/
/*
Inversion Count for an array indicates how far (or close) the array is from being sorted.
If array is already sorted then inversion count is 0.
If array is sorted in reverse order that inversion count is the maximum.
*/
/*
APPROACH: using a binary index tree
test case: 7 6 5 4 3 2 1
******************* *******************
NEED OF BIT:we are calculating prefix sum for a dynamic dataset where update is present
So if we update what is at position i , we have to update all i+1 to n as
prefix array[i] = sum(1, i); that will be of order n^2
USING BIT:
In BIT , if we want to get sum(1, i), we can just go up (reducing the value upto last on bit)---> QUERY
if we want to update , we will update for all i+1 to n,---> UPDATE
we can just go down(adding the value upto last on bit)
Let us take 6 , for query (to get sum 1 to 6):
6 = (110)in bin = (100)2 +(10)2 --> sum from (1 to 4)+ (5,6)
7 = 111 = 110+1= sum from (1 to 6)+7= sum from (1 to 4)+ (5,6)+7
In tree, we are going up by subtracting upto last on bit
index -= index & (-index);
-----0------
/ | \
1(1) 2(1,2) 4(1,4)
| / \
3 5 6(5,6)
(3) (5) \
7(7)
Let us take 4 , for update(update 4 to rest ):
4 = (100)in bin = 100 + 100= 8 that is 4 will be held in 8
3 = 11 = 11+1= 100= 4 that is 3 will be held in 4
index += index & (-index);
*/
void update(ll b[],ll n, ll pos){
while(pos<=n){
b[pos] += 1;
pos += pos&(-pos);
}
}
ll query(ll b[],ll pos){
ll ans=0;
while(pos>0){
ans +=b[pos];
pos -= pos&(-pos);
}
return ans;
}
int main(){
ll t; cin>> t; while(t--){
ll n;
cin>> n;
ll BIT[n+1], arr[n+1],i, x;
memset(BIT, 0, sizeof(BIT));
memset(arr, 0, sizeof(arr));
vector<pair<ll,ll>> vec;
for(i=0;i<n;i++){
cin>> x;
vec.push_back(mk(x, i));
}
sort(vec.begin(), vec.end());// in case of negative input or large input
/*5
7 -90 100 2 1
*/
for(i=0;i<n;i++){// convert the case into 4 1 5 3 2
arr[vec[i].second] = i+1;
// cout<< " "<<arr[i]<< endl;
}
for(i=0;i<n;i++){
cout<< " "<<arr[i]<< endl;
}
for(i=n-1;i>=0;i--){ // for each position we will compute how many large number are present before it
cout<< sum<< endl;
sum+= query(BIT,arr[i]-1);
update(BIT, n, arr[i]);
}
cout<< sum<< endl;
sum=0;
}
}
| true |
7af5aca83a2a0cebbdf4f0f01a8ec0e1394b834a | C++ | myapit/cppcollection | /linux_programming/localdevel/nc-win.cpp | UTF-8 | 5,705 | 2.609375 | 3 | [
"MIT"
] | permissive | /*
* Very simple pop-up using ncurses form and menu library (not CDK).
*
* The buttons are made from items and the fields are made from... well fields.
*
* How to run:
* gcc -o test -lmenu -lform -lncurses ncurses-simple-pop-up.c -g && ./test
*/
// Depending on your OS you might need to remove 'ncurses/' from the include path.
#include <ncurses.h>
#include <curses.h>
#include <form.h>
#include <menu.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
/*
+-------------------------------+ <-- win_body
|+-----------------------------+|
|| ||
|| ||
|| win_form ||
|| ||
|| ||
|+-----------------------------+|
|+-----------------------------+|
|| win_menu ||
|+-----------------------------+|
+-------------------------------+
*/
//#define WINDOW,FORM,FIELD,MENU,ITEM;
WINDOW *win_body, *win_form, *win_menu;
FORM *form;
FIELD **fields;
MENU *menu;
ITEM **items;
bool is_on_button; // Used to know the "case" we're in
void new_popup(int rows, int cols, int posy, int posx, char **buttons,int nb_buttons, char **requests, int nb_fields)
{
int i, cury = 0, curx = 1, tmp;
WINDOW *inner;
win_body = newwin(rows, cols, posy, posx);
assert(win_body != NULL);
box(win_body, 0, 0);
items = malloc(sizeof(ITEM *) * (nb_buttons+1));
assert(items);
for (i = 0; i < nb_buttons; i++) {
items[i] = new_item(buttons[i], "");
assert(items[i] != NULL);
}
items[i] = NULL;
menu = new_menu(items);
win_menu = derwin(win_body, 3, cols-2, rows-4, 1);
assert(menu != NULL && win_menu != NULL);
box(win_menu, 0, 0);
set_menu_win(menu, win_menu);
set_menu_format(menu, 1, nb_buttons);
tmp = menu->fcols * (menu->namelen + menu->spc_rows);
tmp--;
inner = derwin(win_menu, 1, tmp, 1, (cols-3-tmp)/2);
assert(inner != NULL);
set_menu_sub(menu, inner);
set_menu_mark(menu, "");
fields = malloc(sizeof(FIELD *) * (nb_fields+1));
assert(fields);
for (i = 0; i < nb_fields; i++) {
fields[i] = new_field(1, 10, cury, curx, 0, 0);
assert(fields[i] != NULL);
set_field_buffer(fields[i], 0, requests[i]);
if (i % 2 == 1) {
cury = cury+1;
curx = 1;
field_opts_on(fields[i], O_ACTIVE);
field_opts_on(fields[i], O_EDIT);
set_field_back(fields[i], A_UNDERLINE);
} else {
curx = 20;
field_opts_off(fields[i], O_ACTIVE);
field_opts_off(fields[i], O_EDIT);
}
}
fields[i] = NULL;
form = new_form(fields);
assert(form != NULL);
win_form = derwin(win_body, rows-5, cols-2, 1, 1);
box(win_form, 0, 0);
assert(form != NULL && win_form != NULL);
set_form_win(form, win_form);
inner = derwin(win_form, form->rows+1, form->cols+1, 1, 1);
assert(inner != NULL);
set_form_sub(form, inner);
assert(post_form(form) == E_OK);
assert(post_menu(menu) == E_OK);
is_on_button = true;
pos_menu_cursor(menu);
}
void delete_popup(void)
{
int i;
unpost_form(form);
unpost_menu(menu);
for (i = 0; fields[i] != NULL; i++) {
free_field(fields[i]);
}
for (i = 0; items[i] != NULL; i++) {
free_item(items[i]);
}
free_menu(menu);
free_form(form);
delwin(win_form);
delwin(win_menu);
delwin(win_body);
}
/*
* Actions for 'return' on a button
*/
void driver_buttons(ITEM *item)
{
const char *name = item_name(item);
int i;
if (strcmp(name, "OK") == 0) {
mvprintw(LINES-2, 1, "[*] OK clicked:\t");
for (i = 0; i < form->maxfield; i++) {
printw("%s", field_buffer(fields[i], 0));
if (field_opts(fields[i]) & O_ACTIVE)
printw("\t");
}
} else if (strcmp(name, "QUIT") == 0)
mvprintw(LINES-2, 1, "[*] QUIT clicked, 'F1' to quit\n");
refresh();
}
/*
* When you want to change between the form and the buttons
*/
void switch_to_buttons(void)
{
// Those 2 lines allow the field buffer to be set
form_driver(form, REQ_PREV_FIELD);
form_driver(form, REQ_NEXT_FIELD);
menu_driver(menu, REQ_FIRST_ITEM);
is_on_button = true;
set_menu_fore(menu, A_REVERSE); // "show" the button
}
void driver(int ch)
{
switch (ch) {
case KEY_DOWN:
if (is_on_button)
break;
if (form->current == fields[form->maxfield-1])
switch_to_buttons();
else
form_driver(form, REQ_NEXT_FIELD);
break;
case KEY_UP:
if (is_on_button) {
is_on_button = false;
set_menu_fore(menu, A_NORMAL); // "hide" the button
} else
form_driver(form, REQ_PREV_FIELD);
break;
case KEY_LEFT:
if (is_on_button)
menu_driver(menu, REQ_LEFT_ITEM);
else
form_driver(form, REQ_LEFT_FIELD);
break;
case KEY_RIGHT:
if (is_on_button)
menu_driver(menu, REQ_RIGHT_ITEM);
else
form_driver(form, REQ_RIGHT_FIELD);
break;
case 10:
if (!is_on_button)
switch_to_buttons();
else
driver_buttons(current_item(menu));
break;
default:
if (!is_on_button)
form_driver(form, ch);
break;
}
if (is_on_button)
pos_menu_cursor(menu);
else
pos_form_cursor(form);
wrefresh(win_body);
}
int main()
{
char *buttons[] = { "OK", "QUIT" };
char *requests[] = { "Password:", "pass", "Id:", "id" };
int ch;
initscr();
noecho();
cbreak();
keypad(stdscr, TRUE);
new_popup(24, 80, (LINES-25)/2, (COLS-81)/2, buttons, 2, requests, 4);
refresh();
wrefresh(win_body);
wrefresh(win_form);
wrefresh(win_menu);
while ((ch = getch()) != KEY_F(1))
driver(ch);
delete_popup();
endwin();
return 0;
}
| true |
92564cfd44bc2d90059f28f9aada41434b6c39cb | C++ | Locutus18/Discrete-Matemathics-2 | /graph.cpp | UTF-8 | 271 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include "graph.h"
using namespace std;
int main()
{
Graph<int,int,false> graph = Graph<int,int,false>();
for(int i = 0; i < 10; ++i) {
graph.add(i);
}
for(int i = 0; i < 9; ++i) {
graph.add(i,i+1,i+2);
}
graph.print();
return 0;
}
| true |
9a19f841719dcc8d150ee35d406a0d4086a51229 | C++ | rvbc1/Carolo20 | /Src/Classes/Filters.h | UTF-8 | 1,838 | 2.53125 | 3 | [] | no_license | /*
* Filters.h
*
* Created on: 03.01.2018
* Author: mice
*/
#ifndef MULTIROTOR_FILTERS_H_
#define MULTIROTOR_FILTERS_H_
#include <stdbool.h>
#include <stdint.h>
#include <math.h>
#include "stm32f7xx_hal.h"
#include "Mathematics.h"
class Filter {
public:
virtual float apply(float input) = 0;
Filter(){};
virtual ~Filter(){};
};
class PT1Filter:
public Filter {
float state;
float k;
public:
float apply(float input);
void init(void);
PT1Filter(uint8_t f_cut, float dT);
virtual ~PT1Filter();
};
typedef enum {
FILTER_LPF = 0,
FILTER_NOTCH,
FILTER_BPF,
} biquadFilterType_e;
typedef enum {
LPF_PT1 = 0,
LPF_BIQUAD,
} LPFFilterType_e;
class BiquadFilter:
public Filter {
/* bandwidth in octaves */
const float BIQUAD_BANDWIDTH = 1.9f;
/* quality factor - butterworth*/
const float BIQUAD_Q = 1.0f / sqrtf(2.0f);
/* coefficients*/
float b0, b1, b2, a1, a2;
/* samples*/
float x1, x2, y1, y2;
public:
float apply(float input);
void init(void);
BiquadFilter( biquadFilterType_e type, float dT, float filterFreq, float cutoff = 0);
virtual ~BiquadFilter();
};
class KalmanFilter:
public Filter {
float q; //process noise covariance
float r; //measurement noise covariance
float p; //estimation error covariance matrix
float k; //kalman gain
float x; //state
float lastX; //previous state
public:
float apply(float input);
void init(void);
KalmanFilter(float qpar, float rpar, float ppar, float intialValue);
virtual ~KalmanFilter();
};
class NullFilter:
public Filter {
public:
float apply(float input);
void init(void);
NullFilter(){};
virtual ~NullFilter(){};
};
#endif /* MULTIROTOR_FILTERS_H_ */
| true |
4e0615f49398722689f8e639c8c59e4967edaf59 | C++ | azhi-fengye/Introduction-to-algorithms | /C Primer Plus/6.16编程练习(4)/源.cpp | GB18030 | 372 | 3.1875 | 3 | [] | no_license | /*
ʹǶѭĸʽӡĸ
A
BC
DEF
GHIJ
KLMNO
PQRSTU
ϵͳʹ˳Ĵ룬ϰ3ķ
*/
#include<stdio.h>
int main(void)
{
char ch = 'A';
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < i + 1; j++)
{
printf_s("%c",ch);
ch++;
}
printf_s("\n");
}
return 0;
} | true |
68b894d2098c0b720174dfa037d8d1154d3f3e95 | C++ | IoTClassroom/iot-lab-sigfox-training-baron-coisnon | /Workspace/Fade/fade/fade.ino | UTF-8 | 419 | 2.828125 | 3 | [] | no_license | int pin = 9;
int brightness = 0;
int fadeAmount = 5;
void setup() {
// declare pin 9 to be an output:
pinMode(pin, OUTPUT);
Serial.begin(9600);
}
void loop() {
analogWrite(pin, brightness);
brightness = brightness + fadeAmount;
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
Serial.print("brightness : ");
Serial.println(brightness);
delay(50);
}
| true |
21dfb9dda6e69d9afee985667f7fb9edbb74a2b0 | C++ | AStockinger/Cpp-Projects | /Projects/Zoo Tycoon/Penguin.hpp | UTF-8 | 599 | 2.546875 | 3 | [] | no_license | /*********************************************************************
** Program name: Zoo Tycoon
** Author: Amy Stockinger
** Date: Oct 8, 2018
** Description: Penguin specification, includes matching Animal
** constructors along with modified member vars
*********************************************************************/
#ifndef PENGUIN_HPP
#define PENGUIN_HPP
#include "Animal.hpp"
const double PENGUIN_COST = 1000.00;
const double PEN_FOOD_COST_MULT = 1.0;
const double PENGUIN_PAYOFF_MULT = 0.1;
class Penguin : public Animal{
public:
// constructor
Penguin();
};
#endif | true |
d099a6fa84678e1b1c50b348e872e0e6baaf1350 | C++ | jsdelivrbot/Reactor | /Common/PulseWidthModulator.hpp | UTF-8 | 1,349 | 2.53125 | 3 | [] | no_license | //
// Copyright (C) BlockWorks Consulting Ltd - All Rights Reserved.
// Unauthorized copying of this file, via any medium is strictly prohibited.
// Proprietary and confidential.
// Written by Steve Tickle <Steve@BlockWorks.co>, September 2014.
//
#ifndef __PULSEWIDTHMODULATOR_HPP__
#define __PULSEWIDTHMODULATOR_HPP__
#include <stdint.h>
template <uint32_t period, uint32_t ticksPerBit, uint8_t txMask, typename BufferType>
class PWM
{
public:
PWM(BufferType& _cmdFIFO) :
cmdFIFO(_cmdFIFO)
{
}
uint32_t GetPeriod()
{
return period;
}
void ProcessNegativeEdge()
{
}
void ProcessPositiveEdge()
{
}
void PeriodicProcessing( uint8_t inputValue, uint8_t& outputValue )
{
bool dataAvailable = false;
uint8_t currentCmd = cmdFIFO.NonBlockingGet(dataAvailable);
if( (bitNumber&0x01) == 0 )
{
SetTxLow( outputValue );
}
else
{
SetTxHigh( outputValue );
}
bitNumber++;
}
void SetTxHigh( uint8_t& outputValue )
{
outputValue |= txMask;
}
void SetTxLow( uint8_t& outputValue )
{
outputValue &= ~txMask;
}
uint32_t nextBitTimestamp = 0;
uint32_t bitNumber = 0;
BufferType& cmdFIFO;
};
#endif
| true |
1b807933ba477e832da4b925438be067b3488821 | C++ | Zhenyuan-Xi/Algorithms | /Bipartite Graph/LC886. Possible Bipartition.cpp | UTF-8 | 2,498 | 3 | 3 | [
"MIT"
] | permissive | /*
Given a set of N people (numbered 1, 2, ..., N), we would like to split everyone into two groups of any size.
Each person may dislike some other people, and they should not go into the same group.
Formally, if dislikes[i] = [a, b], it means it is not allowed to put the people numbered a and b into the same group.
Return true if and only if it is possible to split everyone into two groups in this way.
Note:
1 <= N <= 2000
0 <= dislikes.length <= 10000
1 <= dislikes[i][j] <= N
dislikes[i][0] < dislikes[i][1]
There does not exist i != j for which dislikes[i] == dislikes[j].
Input: N = 4, dislikes = [[1,2],[1,3],[2,4]]
Output: true
Explanation: group1 [1,4], group2 [2,3]
Input: N = 3, dislikes = [[1,2],[1,3],[2,3]]
Output: false
Input: N = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]
Output: false
*/
#include <bits/stdc++.h>
/*
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<string.h>
*/
using namespace std;
typedef long long ll;
typedef vector<int> VI;
typedef vector<vector<int> > VII;
typedef vector<char> VC;
typedef vector<string> VS;
typedef pair<int,int> PII;
#define REP(i,s,t) for(int i=(s);i<(t);++i)
#define RREP(i,s,t) for(int i=(s);i>=(t);--i)
#define ALL(x) (x).begin(),(x).end()
#define FILL(x,v) memset(x,v,sizeof(x))
#define LEN(x) sizeof(x)/sizeof(x[0])
#define MP(x,y) make_pair(x,y)
const int INF=0x3f3f3f3f;
const int dx[]={-1,0,1,0},dy[]={0,-1,0,1}; //i=3-i
/*----------------------------------------------*/
class Solution {
public:
bool possibleBipartition(int N, vector<vector<int>>& dislikes) {
VII adj(N+1,VI());
for(VI dislike:dislikes){
adj[dislike[0]].push_back(dislike[1]);
adj[dislike[1]].push_back(dislike[0]);
}
int colors[N+1];
FILL(colors,0);
REP(i,1,N+1){
if(colors[i]==0&&!bfs(adj,colors,i,1)) return false;
}
return true;
}
bool bfs(VII& adj,int colors[],int i,int color){
queue<int> q;
q.push(i);
colors[i]=color;
while(!q.empty()){
int size=q.size();
color=-color;
REP(i,0,size){
int u=q.front();q.pop();
for(int v:adj[u]){
if(!colors[v]){
colors[v]=color;
q.push(v);
}else if(colors[v]!=color) return false;
}
}
}
return true;
}
};
| true |