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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
d66f1157c39f6030f67ca81640e3288df0bb62fc | C++ | ChenLinL/Bin-packing-research | /main.cpp | UTF-8 | 5,937 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include "next_fit.cpp"
#include "first_fit.cpp"
#include "best_fit.cpp"
#include "first_fit_decreasing.cpp"
#include "best_fit_decreasing.cpp"
#include <fstream>
#include <ctime>
#include <chrono>
#include <random>
#include <vector>
#include <math.h>
using namespace std;
struct timing{
int n;
double seconds;
};
void create_empty_file(string filename){
ofstream f;
f.open(filename, ios::trunc);
f << "test_size,waste\n";
f.close();
}
void add_test_to_file(int testCase, double waste, string filename){
ofstream f;
f.open(filename,ios::app);
f<< testCase <<","<<waste<<"\n";
f.close();
}
mt19937 get_mersenne_twister_genreator_with_current_time_seed(){
unsigned seed = chrono::system_clock::now().time_since_epoch().count();
return mt19937(seed);
}
uniform_int_distribution<int> get_uniform_int_generator(int lb, int ub){
return uniform_int_distribution<int>(lb,ub);
}
uniform_real_distribution<double> get_uniform_double_generator(){
return uniform_real_distribution<double>(0.0,1.0);
}
int randint(mt19937 mt, int lb, int ub){
return uniform_int_distribution<int>(lb,ub)(mt);
}
double randdouble(mt19937 mt){
return uniform_real_distribution<double>(0.0,1.0)(mt);
}
void shuffle_vector(vector<double>& nums){
for(int i = nums.size(); i >= 0; i--){
mt19937 mt = get_mersenne_twister_genreator_with_current_time_seed();
int j = randint(mt,0,i);
double temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
std::vector<double> create_vector(int n){
vector<double> nums;
for(int i = 0; i<n; i++){
mt19937 mt = get_mersenne_twister_genreator_with_current_time_seed();
double d = randdouble(mt);
nums.push_back(d);
}
shuffle_vector(nums);
return nums;
}
double sum(std::vector<double> nums){
double total = 0.0;
for(double & n: nums){
total += n;
}
return total;
}
int bins_num (std::vector<int> nums){
int max = nums[0];
for(int & n:nums){
if(n > max){
max = n;
}
}
max += 1;
return max;
}
int main() {
// std::cout << "best_fit" << std::endl;
// //std::cout << "Hello, World!" << std::endl;
// std::vector<double> items = {0.12,0.83,0.61,0.42,0.71,0.21,0.53,0.72,0.99,0.81,0.25,0.57,0.32,0.76,0.11};
// std::cout<<"items: ";
// for(int i = 0; i<items.size();i++){
// std::cout<<i<<": "<<items[i]<<" | ";
// }
// std::cout<<std::endl;
// //std::cout<<items.at(0.13)<<std::endl;
// std::vector<int> nums = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
// std::vector<double> free;
// next_fit(items,nums,free);
// //first_fit(items,nums,free);
// //best_fit(items,nums,free);
// //first_fit_decreasing(items,nums,free);
// //best_fit_decreasing(items,nums,free);
// std::cout<<"bins remain: ";
// for(int i = 0; i<free.size(); ++i){
// std::cout<<i<<": "<<free[i]<<" | ";
// }
// std::cout<<std::endl;
// std::cout<<"assigments: ";
// for(int i = 0; i<nums.size(); ++i){
// std::cout<<i<<": "<<nums[i]<<" | ";
// }
// std::cout<<std::endl;
create_empty_file("next_fit.csv");
create_empty_file("first_fit.csv");
create_empty_file("best_fit.csv");
create_empty_file("first_fit_decreasing.csv");
create_empty_file("best_fit_decreasing.csv");
for(int n = 2; n <= 524288; n *= 2){
std::vector<double> nums = create_vector(n);
//the test case for the next fit.
vector<double> next_nums = nums;
vector<int> next_assigment(n,0);
vector<double> next_free;
next_fit(next_nums,next_assigment,next_free);
double next_waste = bins_num(next_assigment) - sum(next_nums);
//cout<<"wast: "<<next_waste<<endl;
add_test_to_file(n,next_waste,"next_fit.csv");
//--------------------------------------------------------------------//
//the test case for the first fit.
vector<double> first_nums = nums;
vector<int> first_assigment(n,0);
vector<double> first_free;
first_fit(first_nums,first_assigment,first_free);
double first_waste = bins_num(first_assigment) - sum(first_nums);
//cout<<"wast: "<<first_waste<<endl;
add_test_to_file(n,first_waste,"first_fit.csv");
//------------------------------------------------------------------------//
//the test case fot the best fit.
vector<double> best_nums = nums;
vector<int> best_assigment(n,0);
vector<double> best_free;
best_fit(best_nums,best_assigment,best_free);
double best_waste = bins_num(best_assigment) - sum(best_nums);
add_test_to_file(n,best_waste,"best_fit.csv");
//-------------------------------------------------------------------------//
//the test case for the first_fit_decreasing.
vector<double> first_d_nums = nums;
vector<int> first_d_assigment(n,0);
vector<double> first_d_free;
first_fit_decreasing(first_d_nums,first_d_assigment,first_d_free);
double first_d_waste = bins_num(first_d_assigment) - sum(first_d_nums);
add_test_to_file(n,first_d_waste,"first_fit_decreasing.csv");
//----------------------------------------------------------------------------//
//the test case for the best_fit_decreasing.
vector<double> best_d_nums = nums;
vector<int> best_d_assigment(n,0);
vector<double> best_d_free;
best_fit_decreasing(best_d_nums,best_d_assigment,best_d_free);
double best_d_waste = bins_num(best_d_assigment) - sum(best_d_nums);
//cout<<"wast: "<<best_d_waste<<endl;
add_test_to_file(n,best_d_waste,"best_fit_decreasing.csv");
//-----------------------------------------------------------------------------//
//std::cout<<"l"<<endl;
}
return 0;
}
| true |
ccb19fa223fc092e4cdb34a3e848d61f5163ef88 | C++ | aczoo/Algorithms | /traveling.cpp | UTF-8 | 3,316 | 3.609375 | 4 | [] | no_license | //Annie Zhu
//acz2npn
//4.23.2020
#include <iostream>
#include <cstdlib>
#include <algorithm>
using namespace std;
#include "middleearth.h"
float computeDistance(MiddleEarth me, const string& start, vector<string> dests);
void printRoute(const string& start, const vector<string>& dests);
/**
* @brief the main method
* @details This program runs a brute force search for the least costly
* that travels to each destination generated for the itinerary in Middle Earth.
* @param argc the number of arguments
* @param **argv the user input, which should contain the x-size, y-size, number of cities, random seed, and the number of cities to visit
*/
int main(int argc, char** argv) {
// check the number of parameters
if (argc != 6) {
cout << "Usage: " << argv[0] << " <world_height> <world_width> "
<< "<num_cities> <random_seed> <cities_to_visit>" << endl;
exit(0);
}
// we'll assume the parameters are all well-formed
int width = stoi(argv[1]);
int height = stoi(argv[2]);
int num_cities = stoi(argv[3]);
int rand_seed = stoi(argv[4]);
int cities_to_visit = stoi(argv[5]);
// create the world, and select your itinerary
MiddleEarth me(width, height, num_cities, rand_seed);
vector<string> dests = me.getItinerary(cities_to_visit);
vector<string> minimum_dests=dests;
float minimum=computeDistance(me, dests[0], dests);
sort(dests.begin()+1, dests.end());
while(next_permutation(dests.begin()+1, dests.end())){
float temp=computeDistance(me, dests[0], dests);
if (temp<minimum){
minimum=temp;
minimum_dests=dests;
}
}
cout<<"Minimum path has distance "<<minimum<<":"<<endl;
printRoute(minimum_dests[0],minimum_dests);
return 0;
}
/**
* @brief Return the total distance traveled in the cycle
* @details This method will compute the full distance of the cycle that starts at the
* 'start' parameter, goes to each of the cities in the dests
* vector in order, and ends back at the 'start' parameter.
* @param me our middle earth
* @param start our starting destination
* @param dests our vector of destinations in the itinerary
* @return the distance traveled in the ordered cycle as a float
*/
float computeDistance(MiddleEarth me, const string& start, vector<string> dests) {
float total=0.0;
for(int i=0;i<dests.size()-1;i++){
total+=me.getDistance(dests[i], dests[i+1]);
}
total+=me.getDistance(dests.back(),start);
return total;
}
/**
* @brief method that prints out a route
*
* @details This method takes in a list of destinations and will print the entire route in the desired
* format. It will start at the beginning of the vector and then loop back around for the starting destination.
*
* @param start the starting destination
* @param dests a vector containing all cities in the itinerary
*/
// This method will print the entire route, starting and ending at the
// 'start' parameter.
// The output should be similar to:
// Erebor -> Khazad-dum -> Michel Delving -> Bree -> Cirith Ungol -> Erebor
void printRoute(const string& start, const vector<string>& dests) {
for (int i=0; i<dests.size(); i++) {
cout << dests[i] << " -> ";
}
//cout<<dests.front()<<endl;
cout<<start<<endl;
}
| true |
ebf090acffa2ac7ea1ff5771cda4a1f9fc611db7 | C++ | jcmana/playground | /cpp/interface_extension/composite/composite_rectangle.h | UTF-8 | 510 | 2.671875 | 3 | [] | no_license | #pragma once
#include "indexable_impl.h"
#include "element_impl.h"
#include "rectangle_impl.h"
class composite_rectangle :
public indexable_impl,
public element_impl,
public rectangle_impl
{
public:
class factory
{
public:
static std::shared_ptr<composite_rectangle> make_composite(int x, int y, int width, int height);
};
public:
composite_rectangle(
indexable_impl && constructed_indexable_impl,
element_impl && constructed_element_impl,
rectangle_impl && constructed_rectangle_impl
);
}; | true |
32d546ac9ab390213351a85ea340f4dc03a3bee3 | C++ | aMammoth/CustomPuzzleLeague | /cocos2d/cocos/base/RepetitionClock.h | UTF-8 | 1,478 | 2.65625 | 3 | [] | no_license | #ifndef __cocos2d_custom__RepetitionClock__
#define __cocos2d_custom__RepetitionClock__
#include "platform/CCPlatformMacros.h"
#include <chrono>
NS_CC_BEGIN
class CC_DLL RepetitionClock
{
public:
using Milli = std::chrono::milliseconds;
using Instant = std::chrono::steady_clock::time_point;
//Basic constructor
RepetitionClock(bool enabled = false, Milli delay_repetition = Milli(1200), Milli frequence_repetition = Milli(333));
//Starts the clock, must be called on button pressed event
void Start(Instant current_time_point);
//Stops the clock, must be called on button released event
void Stop();
//Whether the input is to be considered egarding the spent amount of time and whether this button is repetable or not
bool ConsiderInput(Instant current_time_point);
//Whether the repetition is enabled or not
bool enabled;
//The duration before the first repetition after pressing the button the first time
Milli delay_repetition;
//The duration after the first repetition after pressing the button the first time
Milli frequency_repetition;
//Sets the repetition clock
void Setup(bool enabled, Milli delay, Milli frequency);
//Whether the clock is started or not
bool IsStarted() const;
private:
//Whether the repetition has started or not
bool started_;
//The previous moment
Instant previous_;
//The spent duration
Milli duration_;
//Whether the repetition is before the first one or not
bool before_first_;
};
NS_CC_END
#endif | true |
cfaab158a13016de496e21dcc3095f6fe709b406 | C++ | Maveldous/All_labs_C---1-course- | /5Lab.C/Middlelvl/ConsoleApplication2/ConsoleApplication2.cpp | UTF-8 | 1,293 | 2.828125 | 3 | [] | no_license | #include "pch.h"
#include <iostream>
#include <fstream>
#include <Windows.h>
//Задание: создать текстовый файл в текстовом редакторе. Организовать просмотр содержимого файла и выполнения действий в соответствии с услови-ем индивидуального задания. Обеспечить сохранение всех полученных результатов в новый файл
//Дан файл f, компоненты которого являются действительными числами. Найти сумму компонент файла.
using namespace std;
int main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
double sum = 0;
ifstream fp;
ofstream ft;
const char* file = "data.txt";
const char* filer = "result.txt";
fp.open(file);
ft.open(filer);
if (!fp.is_open()) {
cout << "stack";
}
else {
char num;
cout << "Содержание файла data.txt: ";
while (fp.get(num)) {
cout << num;
double num1 = atof(&num);
sum = sum + num1;
}
}
if (!ft.is_open()) {
cout << "stack";
}
else {
ft << "Сумма компонент файла: " << sum;
}
fp.close();
ft.close();
return 0;
}
| true |
2728b0765087e2d75efeb11cff8ae77b5385f8eb | C++ | mayurdw/Pong_Game | /c++/Pong.cpp | UTF-8 | 4,013 | 2.78125 | 3 | [
"MIT"
] | permissive | /*
Author: Mayur Wadhwani
Created: Nov 2018
*/
#include <string>
#include "abs_layer.h"
#include "error.h"
#include "ball.h"
#include "player.h"
using namespace Players;
using namespace Balls;
using namespace std;
static const int iWidth = 40;
static const int iHeight = 20;
static inline int iPaddleHeight()
{
return iHeight / 10;
}
static inline bool bDrawObject(int iY, int iYPos)
{
return ((iY >= (iYPos - iPaddleHeight())) &&
(iY <= (iYPos + iPaddleHeight())));
}
static int Draw(Player &cP1, Player &cP2, Ball &Pong)
{
int iX = 0, iY = 0;
// clear the console
system("clear");
while (iY <= iHeight)
{
iX = 0;
if (iY == 0 || iY == iHeight)
{
cout << std::string(iWidth, '_');
}
if (bDrawObject(iY, cP1.iGetYPos()))
{
cout << "|";
iX++;
}
if (iY == Pong.iGetYPos())
{
cout << std::string(Pong.iGetXPos() - 1, ' ');
iX += (Pong.iGetXPos() - 1);
cout << "*";
iX++;
}
if (bDrawObject(iY, cP2.iGetYPos()))
{
cout << std::string(iWidth - iX, ' ');
cout << "|";
}
cout << "\n";
iY++;
}
cout << "Player 1: " << cP1.iGetScore() << "\tPlayer 2: " << cP2.iGetScore() << "\n";
return 0;
}
static int iHandleCollision(Player &cP1, Player &cP2, Ball &Pong, bool *pbRestart)
{
if (pbRestart == NULL)
return -1;
if (Pong.iGetYPos() - 1 == 0 || Pong.iGetYPos() + 1 == iHeight)
{
Pong.iChangeDirectionAtWall();
}
else if (cP1.iGetXPos() == (Pong.iGetXPos() - 1))
{
if (((cP1.iGetYPos() - iPaddleHeight()) <= Pong.iGetYPos()) &&
((cP1.iGetYPos() + iPaddleHeight()) >= Pong.iGetYPos()))
{
Pong.iChangeDirectionAtPaddle();
}
else
{
*pbRestart = true;
cP2.vIncrementScore();
}
}
else if (cP2.iGetXPos() == (Pong.iGetXPos() + 1))
{
if (((cP2.iGetYPos() - iPaddleHeight()) <= Pong.iGetYPos()) &&
((cP2.iGetYPos() + iPaddleHeight()) >= Pong.iGetYPos()))
{
Pong.iChangeDirectionAtPaddle();
}
else
{
*pbRestart = true;
cP1.vIncrementScore();
}
}
else
{
// do nothing
}
return 0;
}
static int iHandleKeypress(Player &cP1, Player &cP2, Ball &Pong)
{
int iKeyPressed = 0;
if (kbhit(&iKeyPressed))
{
if (iKeyPressed == cP1.iGetUpChar() && ((cP1.iGetYPos() - iPaddleHeight()) > 1))
{
cP1.vSetDir(PLAYER_UP);
}
else if (iKeyPressed == cP1.iGetDownChar() && ((cP1.iGetYPos() + iPaddleHeight()) < iHeight - 1))
{
cP1.vSetDir(PLAYER_DOWN);
}
else if (iKeyPressed == cP2.iGetUpChar() && ((cP2.iGetYPos() - iPaddleHeight()) > 1))
{
cP2.vSetDir(PLAYER_UP);
}
else if (iKeyPressed == cP2.iGetDownChar() && ((cP2.iGetYPos() + iPaddleHeight()) < iHeight - 1))
{
cP2.vSetDir(PLAYER_DOWN);
}
else
{
// do nothing
}
}
return 0;
}
int main(int argc, char const *argv[])
{
Player cP1(0, iHeight, 'w', 's'), cP2(iWidth, iHeight, 'o', 'l');
Ball Pong(iWidth / 2, iHeight / 2);
Pong.vSetDirection(BOTTOM_RIGHT);
bool bRestart = false;
while (1)
{
sleep_ms(iHeight * 10);
cP1.vSetDir(PLAYER_STOP);
cP2.vSetDir(PLAYER_STOP);
if (bRestart)
{
bRestart = false;
Pong.iReset();
cP1.iReset();
cP2.iReset();
}
Return_if_Error(Draw(cP1, cP2, Pong));
Return_if_Error(iHandleCollision(cP1, cP2, Pong, &bRestart));
Return_if_Error(iHandleKeypress(cP1, cP2, Pong));
Pong.iMove();
cP1.iMove();
cP2.iMove();
}
return 0;
}
| true |
6c0c6229cffede1b9a9feab5cc0e1318f93688b3 | C++ | klasing/MnistExample | /CppConcurrencyInAction/listing_2_2.cpp | UTF-8 | 847 | 3.75 | 4 | [] | no_license | // Listing 2.2
// Waiting for a thread to finish
#include <iostream>
#include <thread>
using namespace std;
namespace ns_listing_2_2 {
struct func {
int& i;
func(int& i_) : i(i_) {}
void operator() () {
cout << "-> [listing 2.2] loop started" << endl;
for (unsigned j = 0; j < 1000000; ++j)
do_something(i);
cout << "-> [listing 2.2] loop ended" << endl;
}
void do_something(int& i) {}
};
inline void do_something_in_current_thread() {
throw ("exception thrown");
}
inline void f() {
int some_local_state = 0;
func my_func(some_local_state);
thread t(my_func);
//my_thread.detach();
//my_thread.join();
try {
do_something_in_current_thread();
}
catch (...) {
cout << "-> [listing 2.2] waiting for thread to finish after exception is thrown" << endl;
t.join();
throw;
}
t.join();
}
} | true |
d7cdf20ff1dbabff48d1f48cac5e06df3b2a81c1 | C++ | nicolechu/AssignmentFive | /DoublyLinkedList.h | UTF-8 | 5,860 | 3.9375 | 4 | [] | no_license | /* Nicole Chu
* 2290152
* nichu@chapman.edu
* 350-01
* Assignment #5
*/
/*
* This is my Doubly-Linked List template class. It contains functions to insert and remove elements to my list,
print my list, find or remove specific elements in my list, and return the size of my list.
*/
#ifndef DOUBLYLINKEDLIST_H
#define DOUBLYLINKEDLIST_H
#include <iostream>
#include "ListNode.h"
using namespace std;
template <class T>
class DoublyLinkedList
{
public:
DoublyLinkedList();
void destruct();
void insertFront(T d);
void insertBack(T d);
T removeFront();
T removeBack();
T getFront();
T getBack();
void printList() const;
int find(T val);
unsigned int getSize();
T deletePos(int pos);
T remove(T key);
ListNode<T>* frontNode() const;
bool isEmpty();
private:
ListNode<T> *front;
ListNode<T> *back;
unsigned int size; // unsigned = not negative
};
/*
* The default constructor sets the front and back pointers to null & the size variable to zero upon declaration
of a list object.
*/
template <class T>
DoublyLinkedList<T>::DoublyLinkedList()
{
front = NULL;
back = NULL;
size = 0;
}
/*
* destruct function
* This function manually destructs my list. I found this code on:
https://www.includehelp.com/code-snippets/implementation-of-queue-using-linked-list-in-cpp.aspx
*/
template <class T>
void DoublyLinkedList<T>::destruct()
{
while(front!=NULL)
{
ListNode<T> *temp = front;
front = front->next;
delete temp;
}
back = NULL;
cout << "Destroyed" << endl;
}
/*
* getSize function
* This returns the size of the list.
*/
template <class T>
unsigned int DoublyLinkedList<T>::getSize()
{
return size;
}
/*
* printList function
* This outputs the entire list to the user.
*/
template <class T>
void DoublyLinkedList<T>::printList() const
{
ListNode<T> *curr = front;
while(curr) // while curr is not NULL
{
cout << curr->data << endl;
curr = curr->next;
}
}
template <class T>
bool DoublyLinkedList<T>::isEmpty()
{
return front == NULL;
}
/*
* insertFront function
* The insertFront function inserts an element at the front of the list.
*/
template <class T>
void DoublyLinkedList<T>::insertFront(T d)
{
ListNode<T> *node = new ListNode<T>(d);
if(size == 0) // if list is empty
{
back = node;
}
else
{
front->prev = node;
node->next = front;
}
front = node;
size++;
}
/*
* insertBack function
* The insertBack function inserts an element at the back of the list (which is called from my Queue class).
*/
template <class T>
void DoublyLinkedList<T>::insertBack(T d)
{
ListNode<T> *node = new ListNode<T>(d);
if(size == 0) // if list is empty
{
front = node;
}
else
{
back->next = node;
node->prev = back;
}
back = node;
size++;
}
/*
* removeFront function
* The removeFront function deletes the element at the front of the list and is called from the Queue class.
* I had to slightly alter this code from what we programmed in class because it was giving me errors when
I tried to remove elements from a queue in multiple functions.
*/
template <class T>
T DoublyLinkedList<T>::removeFront()
{
ListNode<T> *temp = front;
if(front->next == NULL) // if there's only one node
{
back = NULL; // the list will be empty
}
else
{
front->next->prev = NULL;
}
T val = temp->data;
front = front->next;
size--;
return val;
}
/*
* removeBack function
* The removeBack function removes the element at the end of the list.
*/
template <class T>
T DoublyLinkedList<T>::removeBack()
{
ListNode<T> *temp = back;
if(back->prev == NULL) // if there's only one node
{
front = NULL; // the list will be empty
}
else
{
back->prev->next = NULL;
}
back = back->prev;
temp->prev = NULL;
T val = temp->data;
delete temp;
size--;
return val;
}
/*
* getFront function
* The getFront function returns the element at the front of the list and is called in the Queue peek function.
*/
template <class T>
T DoublyLinkedList<T>::getFront()
{
return front->data;
}
template <class T>
ListNode<T>* DoublyLinkedList<T>::frontNode() const
{
return front;
}
/*
* getBack function
* The getBack function returns the element at the end of the list.
*/
template <class T>
T DoublyLinkedList<T>::getBack()
{
return back->data;
}
/*
* remove function
* This function removes and returns a specific element from the list.
*/
template <class T>
T DoublyLinkedList<T>::remove(T key)
{
ListNode<T> *current = front;
while(current->data != key)
{
current = current->next;
/*
if(current == NULL)
{
return NULL;
}
*/
}
if(current == front)
{
front = current->next;
}
else
{
current->prev->next = current->next;
}
if(current == back)
{
back = current->prev;
}
else
{
current->next->prev = current->prev;
}
current->next = NULL;
current->prev = NULL;
--size;
return current->data;
}
/*
* find function
* This function finds & returns the index of a specific element from the list.
*/
template <class T>
int DoublyLinkedList<T>::find(T val)
{
int idx = 1;
ListNode<T> *curr = front;
while(curr != NULL)
{
++idx;
if(curr->data == val)
{
break;
}
else
{
curr = curr->next;
}
}
if(curr == NULL)
{
idx = -1;
}
return idx;
}
/*
* deletePos function
* The deletePos function removes & returns an element of the list at a specific index.
*/
template <class T>
T DoublyLinkedList<T>::deletePos(int pos)
{
int idx = 0;
ListNode<T> *prev = front;
ListNode<T> *curr = front;
while(idx != pos)
{
prev = curr;
curr = curr->next;
++idx;
}
prev->next = curr->next;
curr->next = NULL;
T d = curr->data;
size--;
delete curr;
return d;
}
#endif
| true |
dbc342a05b75b4e82bcec5e53f4bcebb074e0522 | C++ | bashok001/XmlParser | /InputParser/InputParser.cpp | UTF-8 | 2,015 | 2.703125 | 3 | [
"Unlicense"
] | permissive | //*************************************************************************//
// InputParser.cpp - Parses input provided to the project from file or string//
// ver 1.0 //
// ----------------------------------------------------------------------- //
// copyleft © Ashok Bommisetti, 2015 //
// No guarantees on anything; But free to modify, copy and distribute //
// ----------------------------------------------------------------------- //
// Author: Ashok Bommisetti //
// First Published (mm-dd-yyyy): 03-24-2015 //
//*************************************************************************//
#include "InputParser.h"
#include <iostream>
#include <fstream>
InputParser::InputParser( InputParser::inputStr input ) {
_inputString = _utilities->trim( input );
}
InputParser::InputParser( std::istream& inputFile ) {
std::string strStore,trimStore;
if( inputFile.good() ) {
while( !inputFile.eof() ) {
std::getline( inputFile,strStore );
trimStore += _utilities->trim( strStore );
}
} else {
std::cout << "\nFile is not accessible at given path. Check arguments. Exiting the program.\n";
exit( -1 );
}
_inputString = trimStore;
}
InputParser::~InputParser() {
_inputString = "";
delete _utilities;
}
#ifdef TEST_INPUTPARSER
int main() {
static std::string xmldata( "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\
<OS name=\"Microsoft-Windows-8.1\">\
<SetupLanguage>\
<UILang>en-IN</UILang>\
<ShowUI>OnError</ShowUI>\
</SetupLanguage>\
<SysLocale>en-US</SysLocale>\
<UserLocale>en-IN</UserLocale>\
</OS>" );
InputParser inputP( xmldata );
std::cout << inputP.getParsedInput();
std::ifstream in( "../TestFolder" );
InputParser inputP1( in );
std::cout << "\n\n\n" << inputP1.getParsedInput() << "\n";
}
#endif | true |
32532c93f082e0535e52b764e672b0b9ace2fb63 | C++ | zitmen/bachelor-thesis--sw-metrics | /src/ASTM/DataDefinition.h | UTF-8 | 807 | 3.15625 | 3 | [] | no_license | /*!
* \file
* DataDefinition.h
*
* \author
* Martin Ovesný (<a href="mailto:ovesnmar@fel.cvut.cz">ovesnmar@fel.cvut.cz</a>)
*/
#ifndef _ASTM_DATA_DEFINITION_H_
#define _ASTM_DATA_DEFINITION_H_
#include <vector>
#include "Definition.h"
#include "Expression.h"
/*!
* \brief
* Definitions involving data.
*
* \section cpp C++
* - example:
* \code
int x = 5; // this->isMutable = false, this->initialValue = "5"
\endcode
*
* \see Definition
*/
class DataDefinition : public Definition
{
public:
DataDefinition();
virtual ~DataDefinition() = 0;
virtual void identify(std::vector<int> &id) const;
/*!
* \brief
* Specifies if data is or is not mutable.
*/
bool isMutable;
/*!
* \brief
* Assigns initial value to data.
*/
Expression *initialValue;
};
#endif // _ASTM_DATA_DEFINITION_H_
| true |
8e4b88eb1a31ee2a6db5a9ebd09c606094bef7b1 | C++ | abhi7544/cp | /bit-manipulation/subsequence.cpp | UTF-8 | 633 | 3.53125 | 4 | [] | no_license | #include <iostream>
using namespace std;
//generate the all subsequence of a string
void subsequence(char str[],char out[],int i,int j)
{
//base case
if(str[i]=='\0')
{ out[j]='\0';
if(out[0]=='\0')
{cout<<" NUll";}
else cout<<out<<",";
return;
}
// recursive case
out[j]=str[i]; //including char at str[i] in subsequence
subsequence(str,out,i+1,j+1);
out[j]='\0';//Excluding tha char at str[i] in subsequence
subsequence(str,out,i+1,j);//keeping the j pointer same and increasing i pointer
}
int main()
{
char str[100];
cin>>str;
char out[100];
subsequence(str,out,0,0);
return 0;
}
| true |
89672f20150fedb16c1e4d4c49d00e10e2f8f5ae | C++ | Ryanel/Blazar | /src/Blazar/Blazar/Platform/OpenGL/OpenGLBuffer.h | UTF-8 | 863 | 2.78125 | 3 | [] | no_license | #pragma once
#include <cstdint>
#include "Blazar/Renderer/Primitives/Buffer.h"
namespace Blazar {
class OpenGLVertexBuffer : public VertexBuffer {
public:
OpenGLVertexBuffer(float* verticies, size_t size);
virtual ~OpenGLVertexBuffer();
virtual void Bind() const;
virtual void Unbind() const;
virtual void SetLayout(const BufferLayout& layout);
virtual const BufferLayout& GetLayout() const;
private:
uint32_t m_Id;
BufferLayout m_Layout;
};
class OpenGLIndexBuffer : public IndexBuffer {
public:
OpenGLIndexBuffer(uint32_t* verticies, size_t size);
virtual ~OpenGLIndexBuffer();
virtual void Bind() const override;
virtual void Unbind() const override;
virtual size_t GetCount() const override { return m_Count; }
private:
uint32_t m_Id;
size_t m_Count;
};
}; // namespace Blazar
| true |
c7602e9e621992df5720342b38ff1a088f6ab0ac | C++ | rikine/Algorithms-and-DS-ITMO | /Semester 1/Lab 2/B.cpp | UTF-8 | 1,496 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <fstream>
using namespace std;
/*stable_sort(v.begin(), v.end(), [](const auto& l, const auto& r) {
return l.first < r.first;
});
*/
void mergesort(vector<pair<string, string>> &a, int start, int end) {
if (end - start < 2)
return;
mergesort(a, start, start + (end - start) / 2);
mergesort(a, start + (end - start) / 2, end);
vector <pair <string, string>> b;
int b1 = start;
int e1 = start + (end - start) / 2;
int b2 = e1;
while (b.size() < end - start) {
if (b1 >= e1 || (b2 < end && a[b2].first < a[b1].first)) {
b.push_back(a[b2]);
b2++;
}
else {
b.push_back(a[b1]);
b1++;
}
}
for (int i = start; i < end; i++) {
a[i] = b[i - start];
}
}
int main()
{
vector<pair<string, string>> v;
ifstream fin("race.in");
int n, i;
fin >> n;
string country, name;
for (i = 0; i < n; i++) {
fin >> country >> name;
v.push_back(make_pair(country, name));
}
mergesort(v, 0, v.size());
ofstream fout("race.out");
country = v[0].first;
fout << "=== " << country << " ===" << endl;
for (const auto& it : v) {
if (country != it.first) {
country = it.first;
fout << "=== " << country << " ===" << endl;
}
fout << it.second << endl;
}
return 0;
}
| true |
d9f5d9811c285e03510fa8b572445391d43b88e7 | C++ | Shurimian/me101-programming | /Assignments/Assignment 1/square.cpp | UTF-8 | 458 | 3.078125 | 3 | [] | no_license | /*
Chamath Wijesekera
ME101 - Assignment 1
*/
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int main()
{
int side_length = 2;
int a = 0;
cout << "Provide a Value : ";
cin >> a;
cout << "The square of " << a << " is " << a * a << endl;
cout << "& the cube of " << side_length << " is " << side_length * side_length * side_length << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
/*
Paste output here
*/
| true |
e1433cd7204810e0d0bae5cc9bcb5ca9825a6b83 | C++ | alexandraback/datacollection | /solutions_5634697451274240_0/C++/Squarefk/a.cpp | UTF-8 | 597 | 2.765625 | 3 | [] | no_license | #include <cstdio>
#define REP(i,n) for (int i=1;i<=n;++i)
using namespace std;
int T;
int x,aa,ans;
int a[10];
bool check(int x) {
while (x) {
if (!a[x % 10]) {
a[x%10] = true;
++aa;
}
x/=10;
}
return aa == 10;
}
int calc(int x) {
REP(i,1000) {
if (check(x * i)) return i;
}
return -1;
}
int main() {
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
scanf("%d",&T);
REP(T_T,T) {
printf("Case #%d: ", T_T);
scanf("%d", &x);
aa = 0;
REP(i,10) a[i-1] = false;
ans = calc(x);
if (ans == -1) puts("INSOMNIA");
else printf("%d\n",ans*x);
}
return 0;
} | true |
3ac10f36ffb57807e75601d17e9593553f480fb9 | C++ | siamcodes/c | /odd.cpp | UTF-8 | 179 | 2.65625 | 3 | [] | no_license | #include <stdio.h>
main(){
st:
int x;
printf("Input:");
scanf("%d", &x);
for(int i=1; i<=x ; i++){
if(x%i==0){
printf("%d \t",i);
}
}
printf("\n");
goto st;
}
| true |
5a5f283f664189272cc87500c2d8b80b423da843 | C++ | bdliyq/algorithm | /misc/google/find-first-missing-positive-integer.cc | UTF-8 | 596 | 2.875 | 3 | [] | no_license | // Question: Find first missing positive integer.
int solve(vector<int> nums) {
if (nums.empty()) {
return 1;
}
int len = nums.size();
for (int i = 0; i < len; ++i) {
if (i+1 == nums[i]) {
continue;
}
while (nums[i] > 0 && nums[i] <= len && i+1 != nums[i] && nums[i] != nums[nums[i]-1]) {
int t = nums[nums[i]-1];
nums[nums[i]-1] = nums[i];
nums[i] = t;
}
}
for (int i = 0; i < len; ++i) {
if (nums[i] != i+1) {
return i+1;
}
}
return len+1;
}
| true |
bddec78a859221252930b5756052dd98c6f55dcc | C++ | RomanovAleksandr/oop | /lab5/Complex/Complex/CComplex.cpp | UTF-8 | 2,600 | 3.265625 | 3 | [] | no_license | #include "CComplex.h"
#define _USE_MATH_DEFINES
#include <cmath>
#include <exception>
#include <limits>
#include <stdexcept>
CComplex::CComplex(double real, double image) : m_real(real), m_image(image)
{
}
double CComplex::Re() const
{
return m_real;
}
double CComplex::Im() const
{
return m_image;
}
double CComplex::GetMagnitude() const
{
return sqrt(pow(m_real, 2) + pow(m_image, 2));
}
double CComplex::GetArgument() const
{
return atan2(m_image, m_real);
}
CComplex CComplex::operator+(const CComplex& a) const
{
return CComplex(m_real + a.m_real, m_image + a.m_image);
}
CComplex CComplex::operator-(const CComplex& a) const
{
return CComplex(m_real - a.m_real, m_image - a.m_image);
}
CComplex CComplex::operator*(const CComplex& a) const
{
double real = m_real * a.m_real - m_image * a.m_image;
double image = m_real * a.m_image + m_image * a.m_real;
return CComplex(real, image);
}
CComplex CComplex::operator/(const CComplex& a) const
{
double denominator = pow(a.m_real, 2) + pow(a.m_image, 2);
if (denominator == 0)
{
throw std::invalid_argument("division by zero");
}
double real = (m_real * a.m_real + m_image * a.m_image) / denominator;
double image = (a.m_real * m_image - m_real * a.m_image) / denominator;
return CComplex(real, image);
}
CComplex CComplex::operator+() const
{
return *this;
}
CComplex CComplex::operator-() const
{
return 0 - *this;
}
CComplex& CComplex::operator+=(const CComplex& a)
{
m_real += a.m_real;
m_image += a.m_image;
return *this;
}
CComplex& CComplex::operator-=(const CComplex& a)
{
m_real -= a.m_real;
m_image -= a.m_image;
return *this;
}
CComplex& CComplex::operator*=(const CComplex& a)
{
CComplex b = *this * a;
m_real = b.m_real;
m_image = b.m_image;
return *this;
}
CComplex& CComplex::operator/=(const CComplex& a)
{
CComplex b = *this / a;
m_real = b.m_real;
m_image = b.m_image;
return *this;
}
bool CComplex::operator==(const CComplex& a) const
{
CComplex delta = *this - a;
return fabs(delta.Re()) < DBL_EPSILON && fabs(delta.Im()) < DBL_EPSILON;
}
bool CComplex::operator!=(const CComplex& a) const
{
return !(*this == a);
}
CComplex operator+(const double a, const CComplex& b)
{
return b + a;
}
CComplex operator-(const double a, const CComplex& b)
{
return CComplex(a) - b;
}
CComplex operator*(const double a, const CComplex& b)
{
return b * a;
}
CComplex operator/(const double a, const CComplex& b)
{
return CComplex(a) / b;
}
bool operator==(const double a, const CComplex& b)
{
return b == a;
}
bool operator!=(const double a, const CComplex& b)
{
return b != a;
} | true |
36f31f18ddeeab8e0a7f3364e3adc478ae7b9155 | C++ | Alvarogd6/AceptaElReto | /165.cpp | UTF-8 | 399 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool impar(unsigned short i) {
return i % 2 == 1;
}
int main() {
string num;
cin >> num;
while(num[0] != '-') {
if(*(find_if (num.begin(), num.end(), impar)) == '\0') {
cout << "SI\n";
} else {
cout << "NO\n";
}
cin >> num;
}
return 0;
} | true |
37ff92a3b34ac41a7eaa0413acc59fcdf6a05965 | C++ | ryryrymyg/cpp_ryuseiGai | /cpp_practice/EZOE/examples/pointer/p_subobject.cpp | UTF-8 | 293 | 2.890625 | 3 | [] | no_license | struct Object
{
//サブオブジェクト
int subobject;
};
int main()
{
//クラスのオブジェクト
Object object;
//サブオブジェクトへのポインタ
int * pointer = &object.subobject;
*pointer = 123;
int read = object.subobject;
std::cout << read <<std::endl;
}
| true |
01feb510b158d5a96c5fdaf4c3724fd971d24508 | C++ | dipayandutta/datastructure | /LinearSearch/LinearSearch.cpp | UTF-8 | 941 | 4.15625 | 4 | [] | no_license | #include <iostream>
class LinearSearch {
public:
void linearSearch(int array[],int value , int i , int n){
int found = 0;
for(i=0;i<n;i++){
if (value == array[i]){
found = 1;
break;
}
}
if(found == 1){
std::cout << "Elemet is present in the array position " << i+1;
std::cout << std::endl;
}
else{
std::cout << "Item is not present in the array ";
std::cout << std::endl;
}
}
};
int main(){
int number;
int i,keynum;
std::cout<<"Enter the number of elements to insert "<< std::endl;
std::cin >> number;
int array[number];
std::cout << "Enter the elements one by one" << std::endl;
for(i=0;i<number;i++){
std::cin >> array[i];
}
std::cout << "Enter the item to search for "<< std::endl;
std::cin >> keynum;
LinearSearch LS;
LS.linearSearch(array,keynum,i,number);
return 0;
}
| true |
99a60510ab0257f6774d0fb8c084504f08451ccb | C++ | kzhereb/knu-is-ooop2018 | /code-demo/oopTests/classes.h | UTF-8 | 2,558 | 3.15625 | 3 | [] | no_license | /*
* classes.h
*
* Created on: Nov 8, 2018
* Author: KZ
*/
#ifndef CODE_DEMO_OOPTESTS_CLASSES_H_
#define CODE_DEMO_OOPTESTS_CLASSES_H_
class AccessModifiersSUT {
friend class FriendlyClass;
friend int sum_of_all_fields(const AccessModifiersSUT & sut);
public:
AccessModifiersSUT(int pub, int prot, int priv) :
public_field(pub), protected_field(prot), private_field(priv){
}
AccessModifiersSUT():AccessModifiersSUT(0,0,0) {}
int public_field;
int sum_of_all_fields(const AccessModifiersSUT & sut) const {
return sut.private_field + sut.protected_field + sut.public_field;
}
int get_private_field() const {
return private_field;
}
void set_private_field(int private_field_) {
private_field = private_field_;
}
void set_another_private_field(AccessModifiersSUT & sut, int private_field_) const {
sut.private_field = private_field_;
}
protected:
int protected_field;
private:
int private_field;
};
class Child: public AccessModifiersSUT {
public:
Child(int pub, int prot)
//: public_field(pub), protected_field(prot)
// ERROR - must initialize members of base class in base class constructor
{
public_field = pub;
// OK - can assign members of base class from subclass
protected_field = prot;
// OK - can access protected members of base class from subclass
// private_field = 0;
// ERROR - subclass cannot access private members of base class
}
int sum_of_fields() const {
return public_field + protected_field;
}
};
class FriendlyClass {
public:
int sum_of_all_fields(const AccessModifiersSUT & sut) const {
return sut.private_field + sut.protected_field + sut.public_field;
}
};
int sum_of_all_fields(const AccessModifiersSUT & sut ) {
return sut.private_field + sut.protected_field + sut.public_field;
}
//cannot use const here - non-member function
class Static {
private:
int private_field;
static int static_private_field;
public:
int public_field;
Static(int priv, int pub) :
private_field(priv), public_field(pub){
}
static int static_sum(const Static & sut) {
return sut.private_field + sut.public_field;
// OK - static methods can access private fields from same class argument
}
//cannot use const here - static method
};
const int MyConst = 12345;
int MyInt = 123;
const int * MyIntPointer = &MyConst;
int * const MyIntPointerConst = &MyInt;
int const * const MyIntPointerConstConst = &MyConst;
#endif /* CODE_DEMO_OOPTESTS_CLASSES_H_ */
| true |
1a6df95f6cd96d6ccaeb25e9430e85ed502e38d8 | C++ | chimamedia/Xtion2Sample | /Xtion2Sample/Xtion2Sample/main.cpp | SHIFT_JIS | 3,086 | 2.640625 | 3 | [] | no_license | // Windows̏ꍇReleaseRpC
// Iȑxœ삵܂B
using namespace std;
#include "openni2.h"
#include "opencv.h"
#include <iostream>
void PleaseBottom()
{
system("pause");
}
int main(int argc, char **argv)
{
try
{
//hCȍ
openni::Status rc = openni::STATUS_OK;
//foCX
openni::Device device;
//ZT瓾ꂽRGB-Df[^
openni::VideoStream depthStream, colorStream;
//ANY_DEVICEȂPCɐڑĂfoCXǂݍ
const char* deviceURI = openni::ANY_DEVICE;
//OpenNȈs
rc = openni::OpenNI::initialize();
printf("After initialization:\n%s\n", openni::OpenNI::getExtendedError());
//foCXǂݍ߂ǂ
rc = device.open(deviceURI);
if (rc != openni::DEVICE_STATE_OK)
{
printf("Viewer: Device open failed:\n%s\n", openni::OpenNI::getExtendedError());
openni::OpenNI::shutdown();
throw std::runtime_error("openni::Device::open() failed");
}
//J[摜̏s
rc = colorStream.create(device, openni::SENSOR_COLOR);
if (rc == openni::STATUS_OK)
{
rc = colorStream.start();
if (rc != openni::STATUS_OK)
{
printf("Viewer: Couldn't start color stream:\n%s\n", openni::OpenNI::getExtendedError());
colorStream.destroy();
throw std::runtime_error("Couldn't start color stream failed");
}
}
else
{
printf("SimpleViewer: Couldn't find color stream:\n%s\n", openni::OpenNI::getExtendedError());
throw std::runtime_error("Couldn't find color stream failed");
}
//[x̏s
rc = depthStream.create(device, openni::SENSOR_DEPTH);
if (rc == openni::STATUS_OK)
{
rc = depthStream.start();
if (rc != openni::STATUS_OK)
{
printf("Viewer: Couldn't start depth stream:\n%s\n", openni::OpenNI::getExtendedError());
depthStream.destroy();
throw std::runtime_error("Couldn't find depth stream failed");
}
}
else
{
printf("Viewer: Couldn't find depth stream:\n%s\n", openni::OpenNI::getExtendedError());
throw std::runtime_error("Couldn't find depth stream failed");
}
//\pϐ
cv::Mat colorImage, depthImage;
//{
while (1)
{
//t[̍XV
openni::VideoFrameRef colorFrame, depthFrame;
//XVꂽt[̎擾
colorStream.readFrame(&colorFrame);
depthStream.readFrame(&depthFrame);
//t[f[^摜f[^֕ϊ
ChangeColorStream(colorFrame, colorImage);
ChangeDepthStream(depthFrame, depthImage);
if (!colorImage.empty()) cv::imshow("COLOR", colorImage);
if (!depthImage.empty()) cv::imshow("DEPTH", depthImage);
int key = cv::waitKey(1);
if (key == 'Q' || key == 'q')
{
break;
}
}
return 0;
}
catch (std::exception& e)
{
cerr << openni::OpenNI::getExtendedError() << "\n";
PleaseBottom();
}
}
| true |
986995932a2d2c64d3c768791a6bc8f7b5662ecd | C++ | rcory/drake | /geometry/frame_id_vector.cc | UTF-8 | 1,690 | 2.734375 | 3 | [
"BSD-3-Clause"
] | permissive | #include "drake/geometry/frame_id_vector.h"
#include <string>
#include <unordered_set>
#include <utility>
namespace drake {
namespace geometry {
using std::vector;
FrameIdVector::FrameIdVector(SourceId source_id) : source_id_(source_id) {}
FrameIdVector::FrameIdVector(SourceId source_id, const vector<FrameId>& ids)
: source_id_(source_id) {
AddFrameIds(ids);
}
int FrameIdVector::GetIndex(FrameId frame_id) const {
auto iter = id_index_map_.find(frame_id);
if (iter != id_index_map_.end()) {
return iter->second;
}
using std::to_string;
throw std::logic_error(
"The given frame id (" + to_string(frame_id) + ") is not in the set.");
}
void FrameIdVector::AddFrameId(FrameId frame_id) {
ThrowIfContains(frame_id);
int index = static_cast<int>(id_index_map_.size());
id_index_map_[frame_id] = index;
index_id_map_.push_back(frame_id);
}
void FrameIdVector::AddFrameIds(const vector<FrameId>& ids) {
ThrowIfContainsDuplicates(ids);
id_index_map_.reserve(id_index_map_.size() + ids.size());
for (auto id : ids) {
AddFrameId(id);
}
}
void FrameIdVector::ThrowIfContainsDuplicates(
const std::vector<FrameId>& frame_ids) {
std::unordered_set<FrameId> unique_ids{frame_ids.begin(), frame_ids.end()};
if (unique_ids.size() != frame_ids.size()) {
throw std::logic_error("Input vector of frame ids contains duplicates.");
}
}
void FrameIdVector::ThrowIfContains(FrameId frame_id) {
if (id_index_map_.find(frame_id) != id_index_map_.end()) {
using std::to_string;
throw std::logic_error("Id vector already contains frame id: " +
to_string(frame_id) + ".");
}
}
} // namespace geometry
} // namespace drake
| true |
4d5c4fccd3863adcb099cf27ad41e753c8ed7e4e | C++ | peanut-buttermilk/fun-run | /Google/FractionToRecDec.cc | UTF-8 | 1,915 | 3.46875 | 3 | [] | no_license | /**
166. Fraction to Recurring Decimal My Submissions QuestionEditorial Solution
Total Accepted: 29736 Total Submissions: 197126 Difficulty: Medium
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
For example,
Given numerator = 1, denominator = 2, return "0.5".
Given numerator = 2, denominator = 1, return "2".
Given numerator = 2, denominator = 3, return "0.(6)".
Show Hint
Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
**/
class Solution {
public:
string fractionToDecimal(int64_t n, int64_t d) {
/*
1) Get integral division value
2) Get remindar
3) If remindar is zero return to_string(res)
4) rem *= 10;
5) take map
res2;
6) repeat until rem is zero
7) res = rem/d;
8) rem = rem%d;
9) if map.count(rem) > 0 .. return
10) res2 += to_string(res);
11) rem *= 10;
*/
if (n == 0) {
return "0";
}
assert(0 != d);
bool isNeg = ((n < 0) ^ (d<0));
n = abs(n);
d = abs(d);
std::string res;
if (isNeg) { res += "-";
std::cout << "negative" << "\n";
}
res += to_string(n/d);
if (n%d == 0) return res;
res += ".";
std::unordered_map<int, int> map;
for (int64_t r = n%d; r; r %= d) {
if (map.count(r) > 0) {
res.insert(map[r], 1, '(');
res += ')';
break;
}
map[r]=res.size();
r *= 10;
res += to_string(r/d);
//std::cout << "rem: " << rem << "\n";
}
return res;
}
};
| true |
b452100935a8245e1205b932670e29a2b5660bed | C++ | juanmrq95/ee149_104 | /serialSender/serialSender.ino | UTF-8 | 1,519 | 2.53125 | 3 | [] | no_license | /*
Emic 2 Text-to-Speech Module: Basic Demonstration
Author: Joe Grand [www.grandideastudio.com]
Contact: support@parallax.com
Program Description:
This program provides a simple demonstration of the Emic 2 Text-to-Speech
Module. Please refer to the product manual for full details of system
functionality and capabilities.
Revisions:
1.0 (February 13, 2012): Initial release
1.1 (April 29, 2014): Changed rxPin/txPin to use pins 10/11, respectively, for widest support across the Arduino family (http://arduino.cc/en/Reference/SoftwareSerial)
*/
//Sender Code
// include the SoftwareSerial library so we can use it to talk to the Emic 2 module
#include <SoftwareSerial.h>
#include <stdlib.h>
#include <string.h>
SoftwareSerial emicSerial(6, 5); // RX, TX pins work but must connect uno and nano grounds together
void setup() // Set up code called once on start-up
{
// set the data rate for the SoftwareSerial port
emicSerial.begin(9600);
Serial.begin(9600);
}
void loop() {
//Serial.print(4);
int number = 1;
emicSerial.write('h');
Serial.write('h');
delay(250);
emicSerial.write('e');
Serial.write('e');
delay(250);
emicSerial.write('l');
Serial.write('l');
delay(250);
emicSerial.write('l');
Serial.write('l');
delay(250);
emicSerial.write('o');
Serial.write('o');
delay(250);
emicSerial.write('.');
Serial.write('.');
delay(250);
}
| true |
523062588f054a78dd1a6c8366ea746821a7f011 | C++ | fmi-lab/up-2018-kn-group3-sem | /Exercises/Exercise 13/ourQuicksort.cpp | UTF-8 | 774 | 3.640625 | 4 | [] | no_license | #include<iostream>
using namespace std;
void swap2(double& num1, double& num2){
double num3;
num3 = num1;
num1 = num2;
num2 = num3;
}
int partition1(int lo, int hi, double* arr){
double pivot = arr[hi];
int i = lo - 1;
for(int j = lo; j<hi; j++){
if(pivot > arr[j]){
i++;
swap(arr[i], arr[j]);
}
}
swap2(arr[i+1], arr[hi]);
return i+1;
}
void quicksort(int lo, int hi, double* arr ){
if(lo<hi){
int sorted = partition1(lo, hi, arr);
quicksort(lo, sorted-1, arr);
quicksort(sorted+1, hi, arr);
}
}
int main(){
double arr[] = {40, 23, 5, -52, 43, 10, -0.5, 34.56};
quicksort(0, 6, arr);
for(int i = 0; i<8; i++){
cout<<arr[i]<<' ';
}
}
| true |
bb84b6cf0323c63586fe195548b8c9b4f45bff18 | C++ | pabloh1995/clash_reversioned | /back_up_funcionando/main.cpp | UTF-8 | 7,386 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <SDL.h>
#include <SDL_image.h>
#include <string>
#include <fstream>
#include "juego.h"
#include "moneda.h"
#include "casillero.h"
#include "tren.h"
#include "mina.h"
#include "estacion.h"
using namespace std;
/* PARAMETROS
S: Segundos que dura un intervalo.
P: cantidad máxima que puede pedir un bandido.
A: posiciones para definir el área de Ataque de un bandido.
posXE: posición x de la estación.
posYE: posición y de la estación.
IM: intervalo máximo para generación de monedas.
VM: intervalos máximos de vida de una moneda.
IB: máxima cantidad de intervalos para la aparición de bandidos.
VB: tiempo máximo de vida de un bandido.
IP: intervalos entre producciones de las minas.
/**/
void evaluarEventosTeclado(JUEGO &juego,SDL_Event &event,const unsigned char *keys);
void evaluarCambioDireccion(JUEGO &juego,TREN &tren);
void evaluarSalidadePista(JUEGO &juego,TREN &tren);
int main(int argc,char *argv[])
{
if (SDL_Init(SDL_INIT_EVERYTHING) >= 0)
{
//iniciaciones
SDL_Window *window;
SDL_Renderer *renderer;
JUEGO juego;
initJuego(juego);
setJuegoAnchoVentana(juego,800);
setJuegoAltoVentana(juego,600);
window = SDL_CreateWindow(
"Clash of UnLa",
SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,
getJuegoAnchoVentana(juego),getJuegoAltoVentana(juego),SDL_WINDOW_RESIZABLE | SDL_RENDERER_PRESENTVSYNC);
renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED);
SDL_Event event;
const unsigned char *keys;
keys = SDL_GetKeyboardState(NULL);
IMG_Init(IMG_INIT_PNG);
SDL_RenderClear(renderer);
CASILLERO casillero;
initCasilleros(renderer,casillero); //renderizamos el fondo
MONEDA moneda;
initMoneda(renderer,moneda);
TREN tren;
MINA mina;
ESTACION estacion;
SDL_RenderPresent(renderer);
SDL_Delay(1000);
//SETEO DE PARAMETROS
std::ifstream file("parametros.txt");
std::string line;
while (std::getline(file, line))
{
std::string key = line.substr(0,line.find(":"));
std::string value = line.substr((line.find(":")+1));
value = value.substr(0,value.find(";"));
cout << key << " el valor del parametro: " << value<<endl;
if (key == "S"){
setJuegoIntervalo(juego, atoi(value.c_str()));
}
if (key == "IM"){
setJuegoIntervaloMoneda(juego, atoi(value.c_str()));
}
if (key == "posXE"){
setEstacionPosX(estacion, atoi(value.c_str()));
}
if (key == "posYE"){
setEstacionPosY(estacion, atoi(value.c_str()));
}
}
//GAME LOOP
int counter = 1;
while(getJuegoGameisnotOver(juego))
{
//cout << counter << endl;
evaluarEventosTeclado(juego,event,keys);
evaluarCambioDireccion(juego,tren);
if((counter % getJuegoIntervaloMoneda(juego)) == 0)
{
generarMoneda(moneda);
//cout << getMonedaPosX(moneda) << endl;
//cout << getMonedaPosY(moneda) << endl;
}
//disminuimos la velocidad de render por intervalo
if (counter % getJuegoIntervalo(juego) == 0){
SDL_RenderClear(renderer);
initCasilleros(renderer,casillero);
initTren(renderer,tren);
initMinas(renderer,mina);
initEstacion(renderer,estacion);
SDL_RenderPresent(renderer);
SDL_Delay(30);
}
evaluarSalidadePista(juego,tren);
counter++;
}//while del juego
cout<<"Destruimos renderer"<<endl;
SDL_DestroyRenderer(renderer);
cout<<"Destruimos window"<<endl;
SDL_DestroyWindow(window);
IMG_Quit();
SDL_Quit();
}
return 0;
}
void evaluarEventosTeclado(JUEGO &juego,SDL_Event &event,const unsigned char *keys){
if(SDL_PollEvent(&event)){//indica que hay eventos pendientes
switch(event.type){
case SDL_QUIT:
setJuegoGameisnotOver(juego, false);
break;
case SDL_KEYDOWN:
if(keys[SDL_SCANCODE_ESCAPE]){
setJuegoGameisnotOver(juego, false);
}
if(keys[SDL_SCANCODE_LEFT]){
setJuegoDireccionSiguiente(juego,3);
cout<<"izq"<<endl;
}
if(keys[SDL_SCANCODE_RIGHT]){
setJuegoDireccionSiguiente(juego,1);
cout<<"der"<<endl;
}
if(keys[SDL_SCANCODE_UP]){
setJuegoDireccionSiguiente(juego,0);
cout<<"arr"<<endl;
}
if(keys[SDL_SCANCODE_DOWN]){
setJuegoDireccionSiguiente(juego,2);
cout<<"abj"<<endl;
}
if(keys[SDL_SCANCODE_SPACE]){
//
}
break;
}
}
}
void evaluarCambioDireccion(JUEGO &juego,TREN &tren){
int dprevia = getJuegoDireccionPrevia(juego);
int dsiguiente = getJuegoDireccionSiguiente(juego);
if (dprevia == 0 && dsiguiente == 1)
{
setTrenTipoDireccion(tren,1);
setTrenDireccion(tren,dsiguiente);
setJuegoDireccionPrevia(juego,dsiguiente);
}
if (dprevia == 0 && dsiguiente == 3)
{
setTrenTipoDireccion(tren,0);
setTrenDireccion(tren,dsiguiente);
setJuegoDireccionPrevia(juego,dsiguiente);
}
if (dprevia == 1 && dsiguiente == 0)
{
setTrenTipoDireccion(tren,0);
setTrenDireccion(tren,dsiguiente);
setJuegoDireccionPrevia(juego,dsiguiente);
}
if (dprevia == 1 && dsiguiente == 2)
{
setTrenTipoDireccion(tren,1);
setTrenDireccion(tren,dsiguiente);
setJuegoDireccionPrevia(juego,dsiguiente);
}
if (dprevia == 2 && dsiguiente == 3)
{
setTrenTipoDireccion(tren,0);
setTrenDireccion(tren,dsiguiente);
setJuegoDireccionPrevia(juego,dsiguiente);
}
if (dprevia == 2 && dsiguiente == 1)
{
setTrenTipoDireccion(tren,1);
setTrenDireccion(tren,dsiguiente);
setJuegoDireccionPrevia(juego,dsiguiente);
}
if (dprevia == 3 && dsiguiente == 0)
{
setTrenTipoDireccion(tren,0);
setTrenDireccion(tren,dsiguiente);
setJuegoDireccionPrevia(juego,dsiguiente);
}
if (dprevia == 3 && dsiguiente == 2)
{
setTrenTipoDireccion(tren,1);
setTrenDireccion(tren,dsiguiente);
setJuegoDireccionPrevia(juego,dsiguiente);
}
}
void evaluarSalidadePista(JUEGO &juego,TREN &tren){
int anchoVentana = getJuegoAnchoVentana(juego);
int altoVentana = getJuegoAltoVentana(juego);
int trenPosX = getTrenPosX(tren);
int trenPosY = getTrenPosY(tren);
if (trenPosX > anchoVentana || trenPosX < 0){
setJuegoGameisnotOver(juego,false);
}
if (trenPosY > altoVentana || trenPosY < 0){
setJuegoGameisnotOver(juego,false);
}
}
| true |
59cdacd27165df8990de743a360bd0fe9b90a466 | C++ | SchwyzerDose/dhbw-objektorientierung | /Beispielprojekt/Beispielprojekt.cpp | UTF-8 | 1,108 | 2.640625 | 3 | [] | no_license | #include "stdafx.h"
#include <Gosu/Gosu.hpp>
#include <Gosu/AutoLink.hpp>
#include <vector>
#include <string>
#include <iostream>
#include "Planet.h"
#include "Vektor2d.h"
class GameWindow : public Gosu::Window
{
public:
Gosu::Image Bild;
GameWindow()
: Window(800, 600), Bild("planet3.png")
{
set_caption("Gosu Tutorial Game mit Git");
}
double x=0;
double y;
double z;
void draw() override
{
graphics().draw_line(
x, 20, Gosu:: Color :: RED, 200, 100, Gosu::Color :: GREEN, 0.0
);
graphics().draw_triangle(x, y, Gosu::Color::RED, 150+x, 150, Gosu::Color::GREEN, 600, 400, Gosu::Color::BLUE, 0.0,Gosu::AlphaMode::AM_INTERPOLATE);
Bild.draw_rot(x, y, 0.0,
100*x/y, // Rotationswinkel in Grad
0.5, 0.5, // Position der "Mitte" relativ zu x, y
0.2,0.2,Gosu::Color::AQUA
);
}
// Wird 60x pro Sekunde aufgerufen
void update() override
{
x = input().mouse_x();
y = input().mouse_y();
//x = (x + 1) % 300;
if (input().down(Gosu::ButtonName::KB_ESCAPE)) {
close();
}
}
};
// C++ Hauptprogramm
int main()
{
GameWindow window;
window.show();
} | true |
6ea7bae53b8ba7f476a95fcf6a96ebfb6f27f80d | C++ | XWwanwan/li_xiao_wan | /homework618/main.cpp | UTF-8 | 274 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include<cmath>
using namespace std;
double integerPower(double base,int exponent)
{
double result=1;
for(int i=0;i<exponent;i++)
{
result*=base;
}
return result;
}
int main()
{
cout<<integerPower(2,3);
return 0;
}
| true |
b5dcc0a2739e5d5ec9cf1cbede7707a3a82d52ad | C++ | ogglO/Incubator | /src/hwInterfaces.cpp | UTF-8 | 6,609 | 2.5625 | 3 | [] | no_license | #include <Arduino.h>
#include "hwInterfaces.h"
#include "definitions.h"
#include "controller.h"
#include "menu.h"
#include "appHelpers.h"
//set all hw states except TFT
//heater
//lights
//fan
bool statusLight = LIGHT_ON_START_ENABLE;
uint16_t timeSinceLightsOn = 0;
//encoder
bool encoderALast;
int16_t encoderValue;
volatile uint8_t encoderRegisteredClicks = 0;
uint32_t encoderLastClick;
volatile bool encoderDebouncing = 0;
void setupPWM();
void setupTimer2();
void singleClick();
void doubleClick();
void tripleClick();
void singleClick()
{
/*if(menuIsOpen())
{
menuSingleClick();
}
else
{
setLight();
}*/
setLight();
}
void doubleClick()
{
//menuDoubleClick();
rotationEnable();
}
void tripleClick()
{
//menuTripleClick();
controllerEnable();
}
void encDebounce()
{
encoderDebouncing = 0;
}
uint8_t getEncClicks()
{
return encoderRegisteredClicks;
}
void encClickHandler()
{
if (millis() - encoderLastClick >= ENCODER_RESET)
{
switch (encoderRegisteredClicks)
{
case 1:
singleClick();
break;
case 2:
doubleClick();
break;
case 3:
tripleClick();
break;
}
encoderRegisteredClicks = 0;
}
}
void encClick()
{
if (!encoderDebouncing)
{
encoderDebouncing = 1;
encoderRegisteredClicks += 1;
encoderLastClick = millis();
}
}
void stepperStep(uint16_t t_steps)
{
controllerState(CONTROLLER_PAUSED); //pause controller
digitalWrite(PIN_STEPPER_DISABLE, 0); //enable stepper
for (uint16_t i = 0; i < t_steps; i++) //step
{
digitalWrite(PIN_STEPPER_STEP, 1),
delayMicroseconds(STEPPER_PULSE_DURATION);
digitalWrite(PIN_STEPPER_STEP, 0);
delayMicroseconds(STEPPER_STEP_DELAY);
}
digitalWrite(PIN_STEPPER_DISABLE, 1); //disable stepper
controllerState(CONTROLLER_ACTIVE); //reactivate controller
}
void setupTimer2(char t_counterInit)
{
//https://busylog.net/arduino-timer-interrupt-isr-example/
//http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf
//calculation
//timer 2 is an 8-bit timer. it counts from 1 to 255
//16 MHz / (255 - t_counterInit) ticks = min. 62 kHz
//62 kHz / prescaler 128 = min. 490 Hz
//490 Hz is about 2 ms
//t_counterInit > 0 (max 254) makes overflow happen faster
//Atmel 328p datasheet p. 116
TCCR2B = 0x00; //reset timer 2
TCNT2 = t_counterInit; //set the timer count start (counts from here to 255, then resets)
TCCR2A = 0x00; //normal operationg mode, no pin connected p. 127-128
TCCR2B |= (1 << CS22) | (1 << CS20); // Prescale 128 (Timer/Counter started) p.131
TCCR2B &= ~(1 << CS21); // CS22=1 CS21=0 CS20=1 -> prescale = 128
TIMSK2 |= (1 << TOIE2); //enable overflow interrupt p. 132
}
ISR(TIMER2_OVF_vect)
{
evaluateEncoder();
encDebounce();
}
int16_t getEncoderValue()
{
return encoderValue;
}
//turn fan on or off
void setFan(bool state)
{
digitalWrite(PIN_FAN, state);
}
void setLight()
{
statusLight = !statusLight;
digitalWrite(PIN_LED, statusLight);
if(statusLight == 0)
{
timeSinceLightsOn = 0;
}
}
void setLight(bool t_state)
{
statusLight = t_state;
digitalWrite(PIN_LED, statusLight);
if(statusLight == 0)
{
timeSinceLightsOn = 0;
}
}
void lightAutoOff()
{
if (statusLight)
{
timeSinceLightsOn += 1;
if(timeSinceLightsOn >= LIGHT_AUTO_OFF_DELAY)
{
setLight(0);
}
}
}
//evaluate encoder
void evaluateEncoder()
{
bool encA;
bool encB;
//encA = digitalRead(PIN_ENC_A); //switch to more basic readout if too slow
//encB = digitalRead(PIN_ENC_B);
encA = PIND & B00100000; //faster way (pin 2 is 2rd pin in register D. pin 3 3rd)
encB = PIND & B00001000;
//switch signs to change direction
if (encA != encoderALast)
{ //if pinA changed
if (encA != encB)
{ //increase if A=B (one click for KY-040)
encoderValue += 1;
menuUp();
}
else
{ //decrase if A!=B
encoderValue -= 1;
menuDown();
}
}
encoderALast = encA;
}
void setupHWInterfaces()
{
pinMode(PIN_HEATER, OUTPUT); //define before changing pwm settings! (setupPWM())
pinMode(PIN_STEPPER_DISABLE, OUTPUT);
pinMode(PIN_STEPPER_STEP, OUTPUT);
pinMode(PIN_TFT_BACKLIGHT, OUTPUT);
pinMode(PIN_ENC_A, INPUT);
pinMode(PIN_ENC_B, INPUT_PULLUP);
pinMode(PIN_ENC_SW, INPUT_PULLUP);
pinMode(PIN_FAN, OUTPUT);
pinMode(PIN_LED, OUTPUT);
//pinMode(PIN_SENSOR_LID, INPUT_PULLUP); //A6, A7 don't have digital features. Just analog pins
setupPWM(); //set pwm to 20 kHz
setupTimer2(0); //set timer 2 for timer interrupt encoder
digitalWrite(PIN_STEPPER_DISABLE, 1); //make sure stepper is disabled or motor will overheat
analogWrite(PIN_HEATER, 0); //init with the heater turned off
digitalWrite(PIN_FAN, 0); //init with fan turned off
digitalWrite(PIN_LED, LIGHT_ON_START_ENABLE); //init LED
//attach interrupt to encoder button
//attachInterrupt(digitalPinToInterrupt(PIN_ENC_SW), controllerEnable, FALLING);
attachInterrupt(digitalPinToInterrupt(PIN_ENC_SW), encClick, FALLING);
}
void setupPWM()
{
//Timer1 FastPWM Datasheet p.102
//set PIN9 as output but not here for overview
//pinMode(PIN_PWM, OUTPUT);
//reset timer registers
TCCR1A = 0;
TCCR1B = 0;
//COM1A1 = 2 for non-inverted PWM //COM1A0 = 0
TCCR1A |= (1 << COM1A1);
//define pwm mode to fast pwm with icr1 as TOP
//TCCR1A |= (1 << WGM10);
TCCR1A |= (1 << WGM11); //WGM10 = 0 Datasheet p.109
TCCR1B |= (1 << WGM12);
TCCR1B |= (1 << WGM13);
//fclk = 16 MHz
//fpwm = fclk/(N*(1+TOP))
//n = 1,8,64,256,1024 <- prescaler // no prescaling
TCCR1B |= (1 << CS10);
//TCCR1B |= (1 << CS11);
//TCCR1B |= (1 << CS12);
//ICR1 as TOP
//set ICR1 16-bit register //set to 800;
ICR1 = 800;
//OCR1A as Duty cycle 16-bit register OCR1A = TOP equals 100%
//OCR1A = 0;
//analogWrite works too. Better than setting registers, because analogWrite to 0 actually turns off pwm
//setting register to 0 leads to a 1 cycle long spike on every reset
}
| true |
baa51e570cf9d8558427660952cbae0ec0f9be08 | C++ | alanijohnson/DotsnBoxes_CISC220Lab3 | /Game.cpp | UTF-8 | 19,078 | 4.09375 | 4 | [] | no_license | #include "Game.hpp"
#include <cstdlib>
#include <iostream>
#include <time.h>
using namespace std;
/*Game() - sets up the game
ask the user for board size, number of players, number of computer
players. If the user enters 6 or more for the number of the computers
asks for a new input.
Calls makeBoard() and getPlayers().
Randomly decides who starts the game
starts game by calling playGame()
input - none
return - void*/
Game::Game() {
// for non-automatized version – asks for board size, num players, num of computer players, and then initializes
// everything
srand(time(NULL)); //randomizes the random int
//game set up - describes the game rules
cout << "Dots & Boxes" << endl << "x - left to right" << endl << "y - top to bottom" << endl << "(0,0) top left corner" << endl << endl;
cout << "Game Setup:" << endl;
cout << "Board Size (3-11): ";
cin >> size; //set board size from input
cout << size << endl; //print input
cout << "Number of Players (2-5): ";
cin >> numPlayers;
cout << numPlayers << endl;
cout << "Number of Computer Players: ";
cin >> compplayers;
cout << compplayers << endl;
//check to ensure the computer input is less than the total number of players
//or more than 5 inputs and asks user to input compplayers again
while (compplayers > numPlayers || compplayers > 5) {
cout << "Computer Players must be less than 5 and less than total players." << endl << "Try again: ";
cin >> compplayers;
cout << compplayers << endl;
}
makeBoard(); //generate the 2D array using the board size
getPlayers(); //generate the players for the game
turn = rand() % numPlayers; //randomly decide which player goes first
won = false;
playGame(); //start the game;
}
/*Game(bool b) - sets up the game
* when bool is true:
* computer only game of 2 players
* board size is random inbetween 3 & 11
* set up the players
* start the game - playGame()
* when false:
* calls Game() function
input - bool b
return - void*/
Game::Game(bool b) {
//for the automated version – if b is true, randomly generate the size of the board, set the num of players and the
//num of compplayers to 2, and the, of course initialize everything
//sets up the random number generator to be zero
srand(time(NULL));
if (b) {
numPlayers = 2;
compplayers = 2;
size = rand() % 9 + 3;
makeBoard();
turn = rand() % numPlayers;
won = false;
getPlayers();
playGame();
} else {
Game();
}
}
/*makeBoard() - sets up the 2D array that is the board
* dynamically generates a square board of size by size
* each cell initally contains char 'c'
input - none
return - void*/
void Game::makeBoard() {
//dynamically create an array of size size to store the addresses of the arrays
board = new char*[size];
//dynamically create arrays to store characters
for (int i = 0; i < size; i++) {
board[i] = new char[size]; //
}
//fill the arrays with char '.'
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
board[i][j] = '.';
}
}
}
/*printBoard() - prints the board
input - none
return - void
*/
void Game::printBoard() {
//Note: I’m giving you this one
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
cout << board[i][j] << " ";
}
cout << endl;
}
}
/*getPlayers() - this method dynamically generates an array of players
* if the player is human:
* ask for player name and assign it and ask for player character
* if the player is computer:
* choose player name and character from array (only 5)
*
* checks to make sure computer character is different than the existing characters in the game
* if human inputs existing character, ask for new one
*
input - none
return - void
*/
void Game::getPlayers() {
//This method dynamically generates an array of players, and then, for each element in the array, creates a new
//player object with a name and a character. For the number of players that are computers, I used an array of names
// and an array of characters, and then just selected the next name and character in the list for my player object.
// for humans I called the Player constructor with no input parameters (that one asked the user for their name and
// their preference character.
string compnames[5] = {"Computer1", "Computer2", "Computer3", "Computer4", "Computer5"}; //list of computer player names
char playerChar[5] = {'o', 'x', '*', '#', '@'}; //list of computer player characters
players = new Player*[numPlayers]; //dynamically creates an array of players
int addedPlayers = 0; //count the number of players that have been added to the array
//while loop to add all human players
while (addedPlayers < numPlayers - compplayers) { //numPlayers - compplayers is the number of human players
players[addedPlayers] = new Player();
cout << "What is player's name?" << endl;
cin >> players[addedPlayers]->name;
cout << players[addedPlayers]->name << endl;
int count = 0;
bool tf1;
do { //do while loop makes sure all characters in game are different
if (count == 0) { //first time asking for character
cout << "What is player's character?" << endl;
} else { //multiple times asking for character
cout << "Character Taken. Insert New Character" << endl;
}
cin >> players[addedPlayers]->c; //input character
cout << players[addedPlayers]->c << endl; //print character
tf1 = false; //reset bool to false after choosing new character
//iterate through all players characters and check if the characters are the same
//if characters are the same bool becomes true and ask for new character
for (int i = 0; i < addedPlayers; i++) {
if (players[i]->c == players[addedPlayers]->c) {
tf1 = true;
}
}
count++;
} while (tf1);
addedPlayers++;
}
//add computers to list
while (addedPlayers < (numPlayers)) {
players[addedPlayers] = new Player();
players[addedPlayers]->name = compnames[addedPlayers - (numPlayers - compplayers)];
players[addedPlayers]->isComputer = true;
int val = -1;
char tempchar;
bool tf;
//choose character from computer character list and ensure character is
//different than characters already in the game
do {
tempchar = playerChar[val + 1];
tf = false;
for (int i = 0; i < addedPlayers; i++) {
if (players[i]->c == tempchar) {
tf = true;
val++;
}
}
} while (tf);
players[addedPlayers]->c = tempchar;
addedPlayers++;
}
//print out all the players
cout << endl << "Players:" << endl;
printPlayers();
}
/*printPlayers() - prints the players names and character separated by a dash
input - none
return - void
*/
void Game::printPlayers() {
for (int i = 0; i < (numPlayers); i++) {
cout << players[i]->name << " - " << players[i]->c << endl;
}
}
/*playGame() - game play
* loops for each turn till board is full
* prints board
* asks user where they want to place their piece; computer random space generated
* checks to ensure space is available for play
* if it is, character is placed
* checks to see if a square was completed
* if square completed player gets another turn, get a point
* if square not completed next players turn
* if space unavailable, asks user to choose new space, new random space is generated for computer
*
input - none
return - void
*/
void Game::playGame() {
//This is the heart of the game. I called this method directly from my Game constructor(s) as the very last thing.
//This method loops until the board is full.
// In each loop, the next player either chooses where to place their character (if human) or the x,y coordinates are
// randomly generated (and checked to make sure the player isn’t overwriting a piece already on the board).
//It checks to see if the new piece completes a square, and, if so, that player’s score goes up by 1 and that player
// takes another turn. At the end of each round, the board is printed out and each player’s name and score is printed.
//Your code goes here
int moves = size*size; //total number of moves in the game
int x = 0; //initialize coordinates
int y = 0;
cout << endl << "Start Game!";
//loops until there aren't anymore moves
while (moves > 0) {
cout << endl;
printBoard();
cout << endl;
cout << players[turn % numPlayers]->name << "'s turn." << endl; //print who's turn it is
//moves for human vs computer
if (!(players[turn % numPlayers]->isComputer)) { //player is human
cout << "choose x: "; //ask player for x coordinate
cin >> x;
cout << x;
cout << " choose y: "; //ask player for y coordinate
cin >> y;
cout << y << endl;
//loops until move is allowed (space isn't already occupied)
while (moveTaken(x, y)) { //move is unavailable
cout << "choose new x: ";
cin >> x;
cout << x;
cout << " choose new y: ";
cin >> y;
cout << y << endl;
}
placeMove(x, y, players[turn % numPlayers]); //place the players character at their position
} else { //player is computer
findMoves(players[turn % numPlayers]); //generate moves
}
//print the score for all players at the end of the round
cout << "Score:" << endl;
for (int i = 0; i < numPlayers; i++) {
cout << players[i]->name << ": " << players[i]->score << endl;
}
moves--; //decrease move by 1
}
//end of game - no more moves
won = true;
cout << endl;
printBoard(); //print the final board
cout << endl << "GAME OVER!!" << endl;
//print the winners
getWinner();
//Note: for the extra credit version, the findMoves method returns a dynamically created array of 3 different moveLists.
// The first of the 3 contains the list of moves that would complete a square. The second of the 3 contains a list of
// neutral moves, and the third of the 3 contains the list of moves that place a third corner on a square (which are bad
// moves because the next player will then be able to complete a square.
// In this version, the next move is chosen by first trying to pick (randomly) among potential moves that would
// complete a square, and then by trying to pick a move that is, in essence, neutral, and then last, it chooses from the
// list of bad moves as a last resort.
}
/*findMoves(Player *p) - generates random x,y coordinates until an availiable moveis found
* and places the move on the board
input - Player - current player in the game
return - void
*/
void Game::findMoves(Player *p) {
// Regular version, this method continues to generate random x,y values until that cell on the
// board is empty, then places the player's character v on the board, and checks to see if a
// square is completed using checkFour.
int x = rand() % size;
int y = rand() % size;
while (moveTaken(x, y)) {
x = rand() % size;
y = rand() % size;
}
cout << "x: " << x << " y: " << y << endl;
placeMove(x, y, p);
}
/*moveTaken(int, int) - checks to see if the character on the board is '.' indicating available
* also checks to ensure the coordinate is within the board
input - int x - x coordinate
* int y - y coordinate
return - bool
* true - coordinate not within board or coordinate already occupied
* false - move is available
*/
bool Game::moveTaken(int x, int y) {
//returns true if space is occupied
//returns false if space is free
if (x >= size || y >= size) { //ensures input is within board size
return true;
}
if (board[y][x] == '.') { //checks to see if a players character occupies the cell
return false;
} else {
return true;
}
}
/*placeMove(int, int, Player) - puts the players character at the specified
* coordinate and increases players score if the
* placement completes a square. If it doesn't turn
* is increased.
input - int x - x coordinate
* int y - y coordinate
* Player* p - pointer to player
return - void
*/
void Game::placeMove(int x, int y, Player *p) {
board[y][x] = p->c;
if (checkFour(x, y)) {
(p->score)++;
} else {
turn++;
}
}
// movesList * Game::findMoves(char v) {
// The extra credit version of this method – this method dynamically creates a list of 3 movesList objects. It then goes
// through the entire board and classifies each possible move left on the board as being either good (will complete a
// square, in which case it’s added to the new list of movesLists at [0], neutral (doesn’t do anything), in which it’s
// added to the second of the movesLists, or bad (3/4 of a square), in which case it’s added to the third of the
// movesLists.
// This method uses checkFour() method to determine whether a move is good, checkThree to determine if a move is
// bad, and if neither of those is true, then the move is considered neutral.
// This method returns the list of three movesList objects.
//}
/*checkFour(int, int) - checks to see if placing a piece at a coordinate will make a square
input - int x - x coordinate
* int y - y coordinate
return - bool
* true - square complete
* false - doesn't complete a square
*/
bool Game::checkFour(int x, int y) {
// this method checks to see if placing a piece at x and y on the board will complete a square, and, if so, it
// returns true. Otherwise it returns false.
if (x == 0) {
if (y == 0) { //top left corner
return checkDownRight(x, y);
} else if (y == (size - 1)) { //bottom left corner
return checkUpRight(x, y);
} else { //left edge
return (checkUpRight(x, y) || checkDownRight(x, y));
}
} else if (x == (size - 1)) {
if (y == 0) { //top right corner
return checkDownLeft(x, y);
} else if (y == (size - 1)) { //bottom right corner
return checkUpLeft(x, y);
} else { // right edge
return ((checkUpLeft(x, y)) || (checkDownLeft(x, y)));
}
} else if (y == 0) { //top edge (no corners)
return (checkDownLeft(x, y) || checkDownRight(x, y));
} else if (y == (size - 1)) { //bottom edge
return (checkUpRight(x, y) || checkUpLeft(x, y));
} else { //anywhere in the middle
return (checkUpRight(x, y) || checkUpLeft(x, y) || checkDownLeft(x, y) || checkDownRight(x, y));
}
}
/*getWinner() - determines and prints the winners
input - none
return - void
*/
void Game::getWinner() {
// This method determines which of the players in the array of Players has the highest score, and prints out
// that player’s name and their score.
int highscore = 0; // initialize high score
//determine what the highscore of the game is
for (int i = 0; i < numPlayers; i++) {
if (players[i]->score > highscore) {
highscore = players[i]->score;
}
}
cout << "High Score: " << highscore << endl << "Winner(s):" << endl;
//print out all players with the high score - code necessary for tie
for (int i = 0; i < numPlayers; i++) {
if (players[i]->score == highscore) {
cout << players[i]->name << endl;
}
}
}
//bool Game::checkThree(int x, int y) {
// Only needed for Extra Credit
// This method determines whether placing a piece on the board at x and y will complete ¾ of a square and, if so, it
// returns true. Otherwise it returns false.
//}
/*checkDownLeft(int x, int y) - checks to see if square is complete when coordinate
* is in upper Right Hand corner of square
input - int x - x coordinate
* int y - y coordinate
return - bool
* true - square complete
* false - doesn't complete a square
*/
bool Game::checkDownLeft(int x, int y) {
if ((board[y + 1][x - 1] != '.')&&(board[y + 1][x] != '.')&&(board[y][x - 1] != '.')) {
return true;
} else {
return false;
}
}
/*checkDownRight(int x, int y) - checks to see if square is complete when coordinate
* is in upper Left Hand corner of square
input - int x - x coordinate
* int y - y coordinate
return - bool
* true - square complete
* false - doesn't complete a square
*/
bool Game::checkDownRight(int x, int y) {
if ((board[y + 1][x + 1] != '.')&&(board[y + 1][x] != '.')&&(board[y][x + 1] != '.')) {
return true;
} else {
return false;
}
}
/*checkUpRight(int x, int y) - checks to see if square is complete when coordinate
* is in lower left Hand corner of square
input - int x - x coordinate
* int y - y coordinate
return - bool
* true - square complete
* false - doesn't complete a square
*/
bool Game::checkUpRight(int x, int y) {
if ((board[y - 1][x + 1] != '.')&&(board[y - 1][x] != '.')&&(board[y][x + 1] != '.')) {
return true;
} else {
return false;
}
}
/*checkUpLeft(int x, int y) - checks to see if square is complete when coordinate
* is in lower Right Hand corner of square
input - int x - x coordinate
* int y - y coordinate
return - bool
* true - square complete
* false - doesn't complete a square
*/
bool Game::checkUpLeft(int x, int y) {
if ((board[y - 1][x - 1] != '.')&&(board[y - 1][x] != '.')&&(board[y][x - 1] != '.')) {
return true;
} else {
return false;
}
} | true |
67f16d4fa5171957143e5fa1d36c597b42246087 | C++ | zellyn/project-euler | /cc/077.cc | UTF-8 | 226 | 2.796875 | 3 | [] | no_license | // Project Euler Problem 077
//
// What is the first value which can be written as the sum of primes
// in over five thousand different ways?
#include <cstdio>
int main(int argc, const char* argv[]) {
printf("%d\n", 0);
}
| true |
93b3ae3d8f9aee868239c5f2d3d76f51b99a1676 | C++ | SiluPanda/competitive-programming | /leetcode/product_lastk.cpp | UTF-8 | 1,520 | 3.203125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class ProductOfNumbers{
public:
vector <int> arr, prefix;
int last_seen = -1;
ProductOfNumbers(){
arr.clear();
prefix.clear();
}
void add(int num){
if(num == 0){
last_seen = arr.size();
}
arr.push_back(num);
if(prefix.empty()){
prefix.push_back(num);
}
else{
if(prefix.back() == 0){
prefix.push_back(num);
}
else{
prefix.push_back(prefix.back()*num);
}
}
}
int getProduct(int k){
int N = prefix.size();
if(k == N){
if(last_seen >= N-k) return 0;
else return prefix[N-1];
}
else{
if(last_seen >= N-k){
return 0;
}
else{
if(arr[N-k-1] == 0){
return prefix[N-1];
}
else{
return prefix[N-1]/prefix[N-1-k];
}
}
}
}
};
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ProductOfNumbers pro;
int n;
cin >> n;
while(n--){
char c;
cin >> c;
if(c == 'a'){
int num;
cin >> num;
pro.add(num);
}
else{
int k;
cin >> k;
cout << pro.getProduct(k) << endl;
}
}
} | true |
c5bfe11eac33bbc9c317dfd9d4e397c194affd27 | C++ | KudeGit/elments_of_programming_interview | /first_pass/ch14/es8.cpp | UTF-8 | 1,503 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <set>
#include <unordered_map>
#include "../utils.hpp"
struct Interval {
int left;
int right;
};
std::ostream& operator<< (std::ostream& out, const Interval& I)
{
out << "(" << I.left << ", " << I.right << ")";
return out;
}
struct CompareLeft
{
bool operator() (const Interval* a, const Interval* b) const {
return a->left != b->left ?
a->left < b->left :
a->right < b->right;
}
};
struct CompareRight
{
bool operator() (const Interval* a, const Interval* b) const {
return a->right != b->right ?
a->right < b->right :
a->left < b->left;
}
};
std::vector<int> find_smallest_covering_set (
const std::vector<Interval> intervals)
{
std::vector<int> result;
std::set<const Interval*, CompareLeft> L;
std::set<const Interval*, CompareRight> R;
for (const auto& i: intervals) {
L.emplace(&i); R.emplace(&i);
}
while (!R.empty()) {
auto b = (*R.cbegin())->right;
auto l = L.cbegin();
result.emplace_back(b);
while (l != L.cend() && (*l)->left <= b) {
R.erase(*l);
L.erase(l);
l = L.cbegin();
}
}
return result;
}
int main (void)
{
std::vector<Interval> intervals = {
Interval{0,2}, Interval{1,4}, Interval{3,5}};
auto res = find_smallest_covering_set(intervals);
std::cout << res << std::endl;
return 0;
}
| true |
af85a7c32970dc53fdbd689aff6e1bba5790eb25 | C++ | superman2211/ekx | /ekx/core/src/ecxx/ecxx.hpp | UTF-8 | 3,688 | 2.53125 | 3 | [
"ISC"
] | permissive | #pragma once
#include "impl/world.hpp"
#include "impl/view_forward.hpp"
#include "impl/view_backward.hpp"
namespace ecs {
/**
* NULL entity value
*/
template<typename ...Component>
inline auto view() {
return ViewForward<Component...>{the_world};
}
/** special view provide back-to-front iteration
and allow modify primary component map during iteration
**/
template<typename ...Component>
inline auto view_backward() {
return ViewBackward<Component...>{the_world};
}
template<typename ...Component>
inline EntityApi create() {
EntityIndex e;
the_world.create<Component...>(&e, 1);
return EntityApi{e};
}
[[nodiscard]] inline bool valid(EntityRef ref) {
return ref && the_world.check(ref.passport);
}
inline void destroy(EntityApi e) {
EK_ASSERT_R2(e.isAlive());
the_world.destroy(&e.index, 1);
}
template<typename Func>
inline void each(Func func) {
const auto* entities = the_world.entityPool;
const auto count = the_world.size;
for (uint32_t i = 1, processed = 1; processed < count; ++i) {
const auto index = entities[i];
if (index == i) {
func(EntityApi{index});
++processed;
}
}
}
/** Entity methods impl **/
inline bool EntityApi::isAlive() const {
return index && the_world.entityPool[index] == index;
}
template<typename Component, typename ...Args>
inline Component& EntityApi::assign(Args&& ... args) {
EK_ASSERT_R2(isAlive());
return the_world.assign<Component>(index, args...);
}
template<typename Component, typename ...Args>
inline Component& EntityApi::reassign(Args&& ... args) {
EK_ASSERT_R2(isAlive());
return the_world.reassign<Component>(index, args...);
}
template<typename Component>
[[nodiscard]] inline bool EntityApi::has() const {
EK_ASSERT_R2(isAlive());
return the_world.has<Component>(index);
}
template<typename Component>
inline Component& EntityApi::get() const {
EK_ASSERT_R2(isAlive());
return the_world.get<Component>(index);
}
template<typename Component>
inline Component* EntityApi::tryGet() const {
EK_ASSERT_R2(isAlive());
return the_world.tryGet<Component>(index);
}
template<typename Component>
inline Component& EntityApi::get_or_create() const {
EK_ASSERT_R2(isAlive());
return the_world.getOrCreate<Component>(index);
}
template<typename Component>
inline const Component& EntityApi::get_or_default() const {
EK_ASSERT_R2(isAlive());
return the_world.getOrDefault<Component>(index);
}
template<typename Component>
inline void EntityApi::remove() {
EK_ASSERT_R2(isAlive());
return the_world.remove<Component>(index);
}
template<typename Component>
inline bool EntityApi::try_remove() {
EK_ASSERT_R2(isAlive());
return the_world.tryRemove<Component>(index);
}
/** Entity methods impl **/
inline EntityRef::EntityRef(EntityApi ent) noexcept:
EntityRef{ent.index, the_world.generation(ent.index)} {
}
inline bool EntityRef::valid() const {
return passport && the_world.generation(index()) == version();
}
[[nodiscard]]
inline bool EntityRef::check(ecs::EntityApi e) const {
return valid() && e.index == index();
}
[[nodiscard]]
inline EntityApi EntityRef::get() const {
EK_ASSERT(the_world.check(passport));
return EntityApi{index()};
}
// compat
template<typename ...Component>
using view_forward_t = ViewForward<Component...>;
template<typename ...Component>
using view_backward_t = ViewBackward<Component...>;
}
#ifndef ECX_COMPONENT
#define ECX_COMPONENT(T) ecs::the_world.registerComponent<T>()
#define ECX_COMPONENT_RESERVE(T, cap) ecs::the_world.registerComponent<T>(cap)
#endif // #ifndef ECX_COMPONENT | true |
e3e5e10696659ac132755b874331a9891df3d34d | C++ | cohennadi/BlackWidow | /BlackWidow/Agent.h | UTF-8 | 1,622 | 2.796875 | 3 | [] | no_license | #pragma once
#include "Ultrasonic.h"
#undef main
#include <array>
#include <filesystem>
#include <Cryptopp/aes.h>
class Agent final
{
public:
// ctor
// param[in] encryption_root_path root path for the files encryption.
Agent(std::filesystem::path encryption_root_path);
// dtor
~Agent();
// Executes the agent logic.
void execute();
// Decrypt the files in the directory recursively.
void decrypt(const std::array<CryptoPP::byte, CryptoPP::AES::DEFAULT_KEYLENGTH>& encryption_key) const;
// Deleted functions
Agent(const Agent&) = delete;
Agent(Agent&&) = delete;
Agent& operator=(const Agent&) = delete;
Agent& operator=(Agent&&) = delete;
private:
// Encrypt the files in the directory recursively.
void encrypt_directory(const std::array<CryptoPP::byte, CryptoPP::AES::DEFAULT_KEYLENGTH>& encryption_key) const;
// Generates aes key.
// return The aes key.
static std::array<CryptoPP::byte, CryptoPP::AES::DEFAULT_KEYLENGTH> generate_key();
// The ultrasonic function for the main thread.
void ultrasonic_main();
// Sends the key by using the ultrasonic.
void send_key(const std::array<CryptoPP::byte, CryptoPP::AES::DEFAULT_KEYLENGTH>& encryption_key);
// Members
const std::filesystem::path m_encryption_root_path;
std::mutex m_ultrasonic_mutex;
ultrasonic::Ultrasonic m_ultrasonic;
std::unique_ptr<std::jthread> m_ultrasonic_main_thread;
std::unique_ptr<std::jthread> m_send_key_thread;
bool m_agent_running = true;
const std::array<CryptoPP::byte, CryptoPP::AES::BLOCKSIZE> m_init_vector{ 232, 123, 156, 89, 95, 3, 5, 76, 4, 45, 77, 23, 67, 78, 43, 229 };
};
| true |
dc76a8dbe623f17720a9b548391b42fd9aed6fcb | C++ | mateusfavarin/HP1-PS1-Tools | /src/extract.cpp | UTF-8 | 3,400 | 3.484375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <fstream>
#include <string>
#include <filesystem>
#include "extract.h"
using namespace std;
namespace fs = std::filesystem;
bool check_dir(fs::path file_path) {
// Creating path for current folder
fs::path folder(file_path);
bool dir = false;
bool dat = false;
// Checking if the folder has POTTER.DIR and POTTER.DAT files
for (const auto& entry : fs::directory_iterator(folder)) {
string file_name = entry.path().filename().string();
if (file_name == "POTTER.DIR") {
dir = true;
} else if (file_name == "POTTER.DAT") {
dat = true;
}
}
// If POTTER.DIR and POTTER.DAT are in the folder
if (dir && dat) {
return true;
}
return false;
}
string convert_file_name(char name[]) {
string file_name;
for (int i = 0; i < NAME_SIZE; i++) {
// Search for end of string
if (name[i] == 0x00) {
break;
}
// Adds character to the string
file_name += name[i];
}
return file_name;
}
void extract_dat(fs::path file_path) {
// ifstream to read the Harry Potter DIR and DAT files
ifstream potter_dir;
ifstream potter_dat;
// Opening files
potter_dir.open(file_path / "POTTER.DIR", ios::in | ios::binary);
potter_dat.open(file_path / "POTTER.DAT", ios::in | ios::binary);
// Getting number of files to extract
HEADER header;
potter_dir.read((char *) &header, sizeof(header));
METADATA metadata;
// Creating directories to put extracted data
fs::path potter_path = file_path / "POTTER";
fs::path main_potter = potter_path;
fs::create_directory(main_potter);
fs::path lang(potter_path / "LANG");
fs::create_directory(lang);
fs::path img(potter_path / "IMG");
fs::create_directory(img);
fs::path lev(potter_path / "LEV");
fs::create_directory(lev);
// Memory block to hold variable size of data to read from the POTTER.DAT
char * mem_block;
cout << "Extracting POTTER.DAT to POTTER/..." << endl;
// Reading every single file information
for (int i = 0; i < header.num_files; i++) {
// Reading file metadata
potter_dir.read((char *) &metadata, sizeof(metadata));
// Creating a block of memory to read the data from POTTER.DAT
mem_block = new char[metadata.size];
// Adjusting pointer to read the data from
potter_dat.seekg(metadata.offset, ios::beg);
potter_dat.read(mem_block, metadata.size);
// Converting filename to a string
string file_name = convert_file_name(metadata.file_name);
string extension = file_name.substr(file_name.size() - 3);
// Creating extracted file
ofstream new_file;
if (extension == "BIN") {
new_file.open(potter_path / "LANG" / file_name, ios::out | ios::binary);
} else if (extension == "IMG") {
new_file.open(potter_path / "IMG" / file_name, ios::out | ios::binary);
} else {
new_file.open(potter_path / "LEV" / file_name, ios::out | ios::binary);
}
new_file.write(mem_block, metadata.size);
new_file.close();
// Freeing data space to be used later for the next file
delete[] mem_block;
cout << file_name << " successfully extracted." << endl;
}
}
| true |
0b04fcb80e523489617e4e5df4cbbe76dedfaf54 | C++ | xxqxpxx/CodeForces-Solutions | /27/A[ Next Test ].cpp | UTF-8 | 540 | 2.65625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
//freopen("in.in" , "r" , stdin);
//freopen("out.out" , "w" , stdout);
#endif
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin >> arr[i];
sort (arr , arr + n);
for (int i = 0 , z = 1 ; i < n ; ++i , ++z)
{
if (arr[i] != z)
{
cout << z << endl;
return 0;
}
}
cout << arr[n-1]+1 << endl;
return 0 ;
}
| true |
b8afe063ec1694f07f4bae3989610839eb18384b | C++ | sekihan02/Arduino_Storage | /Ltika/source/Ltika.cpp | UTF-8 | 925 | 2.53125 | 3 | [] | no_license | //---------------------------------------------------------------------------
#include "mariamole_auto_generated.h"
//---------------------------------------------------------------------------
void led_blink(int interval, int count);
//---------------------------------------------------------------------------
void setup() {
pinMode(13, OUTPUT);
}
//---------------------------------------------------------------------------
void loop() {
led_blink(1000, 5);
led_blink(5000, 3);
}
//---------------------------------------------------------------------------
// 秒間間隔と回数を受け取り、その回数分LEDを点滅させる
void led_blink(int interval, int count)
{
int i = 0;
while(i < count)
{
digitalWrite(13, HIGH);
delay(interval);
digitalWrite(13, LOW);
delay(interval);
i++;
}
}
//--------------------------------------------------------------------------- | true |
5506a00138b4f3760d1b852de386cdf93767897c | C++ | HuTongsama/learn | /Practice/ch07/Screen.cpp | UTF-8 | 420 | 3.21875 | 3 | [] | no_license | #include "Screen.h"
void Window_mgr::push(const Screen & s)
{
m_screens.push_back(s);
}
Screen Window_mgr::get(ScreenIndex index) const
{
if (index >= 0 && index < m_screens.size())
{
return m_screens[index];
}
return Screen();
}
void Window_mgr::clear(ScreenIndex index)
{
if (index >= 0 && index < m_screens.size())
{
Screen &s = m_screens[index];
s.contents = std::string(s.height*s.width, '0');
}
}
| true |
848256f5bec195198f5c77d3bb48336f82095c1a | C++ | uriqishtepi/uvaonlinejudge | /algo_class_dijkstra.cpp | UTF-8 | 6,535 | 3.421875 | 3 | [] | no_license | /* shortest path from a node n to every other node, known as
* Dijkstra's algorithm. This is for graphs that have no negative cycles
* start from the origin node, and expand via BFS updating shortest path as you go
*/
#include <stack>
#include <queue>
#include <assert.h>
#include <vector>
#include <map>
#include <set>
#include <iostream>
#include <string>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//#define DEBUG true
#ifdef DEBUG
#define out printf
#else
#define out
#endif
struct edge {
int from;
int to;
int weight;
bool operator<(const edge & other) {
out("****** operrator < \n");
return this->weight < other.weight;
}
};
struct cmpedge {
bool operator()(const edge & a, const edge &b) {
return a.weight < b.weight;
}
};
#define vi std::vector<int>
#define vd std::vector<int>
#define mwp std::map<int, edge> //map weight and destination point
#define mdi std::multimap<int, int> //map int int
#define se std::multiset<edge, cmpedge> //set of edges
#define graphtp std::vector< se > //graph is a vector of maps -- the edges
#define INFINITY 1000000
enum {white=0, gray=1, black=2,};
void print_graph(const graphtp & g)
{
out("Printing Graph\n");
for(int n = 0; n < g.size(); n++)
{
out("%d: ", n);
for(se::const_iterator it = g[n].begin(); it != g[n].end(); ++it) {
out("%d-%d(%d), ", it->from, it->to, it->weight);
}
out("\n");
}
}
void printSP(std::vector<edge> P, int i, int final)
{
std::vector<edge> s;
while(i != final) {
s.push_back(P[i]);
i = P[i].from;
}
for(std::vector<edge>::const_reverse_iterator rit = s.rbegin(); rit != s.rend(); ++rit)
printf("%d -> %d (%d) ",rit->from, rit->to, rit->weight);
}
//shortest path from a node n to every other node:
//Dijkstra's this is for graphs that have no negative cycles
//start from node, and expand via BFS updating shortest path as you go
void ShortestPath(const graphtp & g, int n)
{
int comparisons = 0;
vi visited(g.size());
vd D(g.size());
std::vector<edge> P(g.size());
//start with current in queue
mdi q; //poor man's queue: map of weight to from_node
mdi rev; //node and lowest weight to it
int i = 0;
for(vd::iterator it = D.begin(); it != D.end(); ++it) {
if(i != n) {
*it = INFINITY;
q.insert(std::make_pair(INFINITY,i));
}
i++;
}
D[n] = 0;
q.insert(std::make_pair(0,n));
out("initial n %d\n", n);
int counter = 0;
while(!q.empty())
{
//pop first
int node = q.begin()->second;
q.erase(q.begin());
visited[node] = true;
out("n - %d\n", node);
out("\n%d: popped %d \n", counter++, node);
for(se::const_iterator it = g[node].begin(); it != g[node].end(); ++it)
{
if(it->from != node)
printf("%d != %d\n", it->from, node);
assert(it->from == node && "encountered an inconsistend element");
out("considering %d -> %d \n", node, it->to);
if(visited[it->to]) { //need to check because q allows dup nodes
out("encountered a prev. visited node %d\n", it->to);
continue;
}
int dist = D[node] + it->weight;
out("dist from %d to %d; old dist %d vs new dist %d\n",
node, it->to, D[it->to], dist);
comparisons++;
if((comparisons % 100000) == 1)
out("comparisons %d D.size()=%d q.size()=%d\n", comparisons, D.size(), q.size());
if(D[it->to] > dist) { //this is the relaxation step
int old = D[it->to];
D[it->to] = dist;
P[it->to] = *it;
//already in q so need to delete it first and add it
mdi::iterator qit = q.find(old);
if(qit == q.end() ) printf("relax qit is end() for %d\n", old);
assert(qit != q.end() && "not found in q");
while(qit->second != it->to) qit++; //find the actual node
q.erase(qit);
q.insert(std::make_pair(D[it->to], it->to));
}
//if this were a priority queue, we would search for the to elements
//and do decrease key on it -- so we would not insert again key
//unfortunately we can not do so with a map
}
}
for(int i = 0; i < D.size(); i++) {
printf("%d -> %d sp=%d ", n, i, D[i]);
printSP(P, i, n);
printf("\n");
}
out("comparisons %d\n", comparisons);
}
int main(void)
{
out("starting ...\n");
std::cout << " ShortestPath " << std::endl;
int N; //test cases
scanf("%d\n", &N);
out("N %d\n",N);
int ord = 0;
while(N-- > 0) {
char * buff = NULL;
graphtp g;
size_t n;
int m; //nodes
scanf("%d\n", &m);
out("m %d\n",m);
int counter = 0;
while(counter++ < m && getline(&buff, &n, stdin) != -1 )
{
out("this is buff ='%s'\n", buff);
char * tok = strtok(buff, " \n\t"); //node from
out("this is node ='%s'\n", tok);
if(tok == NULL) {
printf("Error in input file");
exit(1);
}
int nodefrom = atoi(tok);
se me;
tok = strtok(NULL, " \n\t"); //node
while(tok > 0)
{
int nodeto = atoi(tok);
if(nodeto < m) {
out("red (node) tok='%s'\n", tok);
}
else {
printf("ERROR: node %d outside of range (max %d)\n", nodeto,m);
}
tok = strtok(NULL, " \n\t"); //weight
if(tok == NULL)
printf("ERROR: weight must be given for each link \n");
int weight = atoi(tok);
out("red (weight) tok='%s'\n", tok);
edge e;
e.from = nodefrom;
e.to = nodeto;
e.weight = weight;
out("inserting e %d %d %d\n",e.from, e.to, e.weight);
me.insert(e);
tok = strtok(NULL, " \n\t"); //node
}
g.push_back(me);
out("size of g %d\n",g.size());
}
printf("Case %d:\n", ++ord);
if(g.size() != m) {
printf("need to have all the nodes explicitly defined, even if no links\n");
continue;
}
print_graph(g);
ShortestPath(g, 0);
printf("\n");
}
return 0;
}
| true |
39c5c866caf8acb18c94aef30976aa19be7a8131 | C++ | ggm6/Parallel-Processing | /Lab4/barrier.cc | UTF-8 | 3,154 | 2.875 | 3 | [] | no_license | // barrier.cc
// Implementations of barrier functions.
//
// developed from the following C source code:
// http://athena.univ-lille1.fr:8888/ab2/coll.45.4/MTP/@Ab2TocView/
//
// Y. Wu, McMaster University, Sept. 2000
#include <thread>
#include <mutex>
#include <condition_variable>
#include "barrier.h"
//--------------------------------------------------------------------------
//Barrier::Barrier
// Initialize a barrier for given number of threads.
//
// "count" is the number of threads involved
// "type" is one of three types:
// USYN_THREAD : synchronize threads in the same process.
// USYN_PROCESS : synchronize different processes.
// USYN_PROCESS_ROBUST : synchronize threads in different processes.
// "arg" is reserved for future use.
//--------------------------------------------------------------------------
Barrier::Barrier(int count, int type, void *arg)
{
maxcnt = count;
CurrentSb = &sb[0];
for (int i = 0; i < 2; ++i) { // construct two subbarriers
_sb *CurrentSb = &sb[i];
CurrentSb->runners = count;
//mutex_init(&CurrentSb->wait_lk, type, arg);
CurrentSb->wait_lk=new std::mutex;
//cond_init(&CurrentSb->wait_cv, type, arg);
CurrentSb->wait_cv=new std::condition_variable;
}
}
//---------------------------------------------------------------------------
// Barrier::~Barrier
// Clean up.
//
//---------------------------------------------------------------------------
Barrier::~Barrier()
{
for (int i=0; i < 2; ++ i) {
//cond_destroy(&sb[i].wait_cv); // delete condition variables
delete sb[i].wait_cv;
//mutex_destroy(&sb[i].wait_lk); // delete locks
delete sb[i].wait_lk;
}
}
//---------------------------------------------------------------------------
// Barrier::Wait
// Wait untill all threads reach this barrier. The last thread switches
// "CurrentSb" point to another sub barrier before waking up all waiting
// threads.
//---------------------------------------------------------------------------
int
Barrier::Wait()
{
_sb *TempSb = CurrentSb; // ptr to a subbarrier
//mutex_lock(&TempSb->wait_lk); // acquire lock
TempSb->wait_lk->lock();
if (TempSb->runners == 1) { // last thread reaching barrier
if (maxcnt != 1) {
TempSb->runners = maxcnt;
// reset counter
CurrentSb = (CurrentSb == &sb[0]) ? &sb[1] : &sb[0];
// switch the current subbarrier
// cond_broadcast(&TempSb->wait_cv);
pthread_cond_broadcast((pthread_cond_t*) TempSb->wait_cv);
// wake up all waiting threads
}
}
else { // not the last thread
TempSb->runners--; // wait
while (TempSb->runners != maxcnt)
{
pthread_cond_wait((pthread_cond_t*)TempSb->wait_cv, (pthread_mutex_t*) TempSb->wait_lk);
}
}
// mutex_unlock(&TempSb->wait_lk); // release lock
// TempSb->wait_lk->lock();
TempSb->wait_lk->unlock();
return(0);
}
| true |
54e15de609299a01b0c6c4b167f8691e3194b00c | C++ | Nikhil569/InterviewBit | /RotatedArray.cpp | UTF-8 | 809 | 3.734375 | 4 | [] | no_license | /*Problem:
Suppose a sorted array A is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
The array will not contain duplicates.
*/
/**
* @input A : Read only ( DON'T MODIFY ) Integer array
* @input n1 : Integer array's ( A ) length
*
* @Output Integer
*/
int findMin(const int* A, int n1) {
int low = 0;
int high = n1-1;
int mid = (high+low)/2;
if(A[mid]>A[high]){
low = mid;
while(A[low]<A[low+1]){
low++;
}
return A[low+1];
}
else if(A[mid]<A[high]){
if(A[mid]<A[mid-1]) return A[mid];
high = mid;
while(A[high]>A[high-1]){
high--;
}
return A[high];
}
return A[high];
}
| true |
5da7bd13fcf5a9b5112a4b78b510bac60bf9f026 | C++ | idiliev18/cpp_essentials_oop_module_2_exam | /problem_5/problem_5.cpp | UTF-8 | 238 | 3.140625 | 3 | [] | no_license | #include <iostream>
using namespace std;
class A {
public:
A() :val(0) {}
int val;
int inc() { ++val; return val--; }
};
void Do(A* a) {
a->val = a->inc();
}
int main()
{
A a;
Do(&a);
cout << a.inc();
return 0;
}
// Answer: 2
| true |
a338071b4b9c6ebf0ce6d1e7683745392329e0e4 | C++ | rmosolgo/sorbet | /dsl/OpusEnum.h | UTF-8 | 553 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | #ifndef SRUBY_DSL_OPUSENUM_H
#define SRUBY_DSL_OPUSENUM_H
#include "ast/ast.h"
namespace sorbet::dsl {
/**
* This class makes it easier to use Opus::Enum in `typed: strict` files:
*
* class MyEnum < Opus::Enum
* X = new
* Y = new('y')
* end
*
* becomes
*
* class MyEnum < Opus::Enum
* X = T.let(new, self)
* Y = T.let(new('y'), self)
* end
*/
class OpusEnum final {
public:
static void patchDSL(core::MutableContext ctx, ast::ClassDef *klass);
OpusEnum() = delete;
};
} // namespace sorbet::dsl
#endif
| true |
b194468a9d6f264aacf5df363be7ab2cb2b25e8a | C++ | subr809/CSCE121 | /Linked List/starter_code/level_2/LinkedList.h | UTF-8 | 1,447 | 3.703125 | 4 | [] | no_license | #ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <iostream>
#include <stdexcept>
#include <string>
class LinkedList {
struct Node {
int data;
Node* next;
Node(int data) : data(data), next(nullptr) {}
};
Node* head;
Node* tail;
unsigned int size;
public:
LinkedList();
int& front() const;
void push_front(const int&);
unsigned int length() const;
void pop_front();
friend std::ostream& operator<<(std::ostream& os, const LinkedList& list) {
os << "[WARNING] ostream operator<< not yet implemented";
return os;
}
};
LinkedList::LinkedList() : head(nullptr), tail(nullptr), size(0) {}
int& LinkedList::front() const {
if (size == 0) {
throw std::out_of_range("empty list");
}
return head->data;
}
void LinkedList::push_front(const int& data) {
Node* node = new Node(data);
if (head) {
node->next = head;
} else {
tail = node;
}
head = node;
size++;
}
unsigned int LinkedList::length() const {
return size;
}
void LinkedList::pop_front() {
if (size == 0) {
throw std::out_of_range("empty list");
}
if (head == tail) {
// 1 node
delete head;
head = nullptr;
tail = nullptr;
} else {
// > 1 node
Node* next = head->next;
delete head;
head = next;
}
size--;
}
#endif | true |
172533c2800bf23155a146b936ac124820f3c1d6 | C++ | oneseedfruit/UTMSPACE_2019-2020-sem2_SCSJ2013_Data_Structures_-_Algorithm | /lab_02/BubbleSort2.cpp | UTF-8 | 3,033 | 3.734375 | 4 | [
"MIT"
] | permissive | // Prepared by : Pn Nor Bahiah Hj. Ahmad
// Prepared by : Nor Bahiah Hj. Ahmad
// School of Computing, Faculty of Engineering
// Universiti Teknologi Malaysia
// e-mail : bahiah@utm.my
//
// Reference : data Structure & Problem Solving with C++
// Frank M. Carrano, Pearson International Edition
// IMPROVED BUBBLE SORT
// Modified by Randy Tan Shaoxian
// - Removed unused headers.
// - Removed mixing C and C++ code.
// - Fixed/added code to show time taken to run an algorithm.
// - Added an array containing arrays of values for given worst case, average case, and best case.
#include <iostream>
#include <chrono>
using namespace std;
// Sorts the items in an array into ascending order.
void ImprovedBubbleSort(int data[], int n)
{
int pass, compare = 0, swap = 0;
int temp;
bool sorted = false; // false when swaps occur
auto before = chrono::high_resolution_clock::now();
for (pass = 1; pass < n && !sorted; ++pass)
{
sorted = true; // assume sorted
for (int x = 0; x < n - pass; ++x)
{
compare++;
if (data[x] > data[x + 1]) { // exchange items
// swap(theArray[index], theArray[nextIndex]);
temp = data[x];
data[x] = data[x + 1];
data[x + 1] = temp;
sorted = false; // signal exchange
swap++;
}
}
}
auto after = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<chrono::microseconds>(after - before).count();
cout << "\n\nTime taken to sort the data: " << duration << " microseconds";
cout << "\n\nTotal pass in improved bubble sort: " << pass - 1;
cout << "\nTotal comparison occur: " << compare;
cout << "\nTotal number to exchange data: " << swap;
}
int main()
{
const int size = 10;
int x;
int data[3][size] = {
{ 20, 19, 18, 17, 16, 15, 14, 13, 12, 11 }, // Worst case
{ 12, 9, 20, 18, 7, 5, 15, 17, 11, 25 }, // Average case
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } // Best case
};
cout << "Content of the lists before sorting:\n\n" ;
for (int x = 0; x < 3; x++)
{
cout << "Case " << x + 1 << ": ";
for (int y = 0; y < size; ++y)
{
cout << data[x][y] << " ";
}
cout << "\n";
}
cout << "\n===============================================\n";
for (int i = 0; i < 3; ++i)
{
cout << "\n\n-----------------------------------------------\n";
cout << "Case " << i + 1 << ":";
ImprovedBubbleSort(data[i], size);
}
cout << "\n\n\n===============================================\n";
cout << "\n\nContent of the lists after sorting:\n\n";
for (int x = 0; x < 3; x++)
{
cout << "Case " << x + 1 << ": ";
for (int y = 0; y < size; ++y)
{
cout << data[x][y] << " ";
}
cout << "\n";
}
return 0;
} | true |
c941aeb3c57a8a00e0bcd6f17b2acf497beb3332 | C++ | shirleymbeyu/OOP1-MCS1.2 | /CON(de)STRUCTORS/const-param/main.cpp | UTF-8 | 444 | 3.515625 | 4 | [] | no_license | #include <iostream>
using namespace std;
/*constructor parameters-> parameters used for setting
initial values for certain member attributes*/
class Car{
public:
string brand;
string model;
int year;
car(string x, string y, int z){
brand = x;
model = y,
year = z;
}
};
int main()
{
Car carobj1("BMW", "X5", 1999);
cout << carobj1.brand <<" " <<carobj1.model<< carobj1.year<<endl;
return 0;
}
| true |
d9801296c57373a26717d0b313695a6f48fb2e37 | C++ | jhnnnmcstr/Experiment-3 | /Exp3_Prb2.cpp | UTF-8 | 1,412 | 3.75 | 4 | [] | no_license | // Create a C++ Program that store temperature of Province A, Province B and Province C
// for a week (seven days) and display it
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
const int a = 3;
const int b = 7;
char prov;
int main ()
{
cout << "Enter all temperature for a week of Province A, Province B, and then Province C.\n\n";
int temp [a] [b];
for (int i = 0; i < a; ++i)
{
for (int j = 0; j < b; ++j)
{
if (i + 1 == 1)
{
cout << "Province A, Day " << j + 1 << " : ";
cin >> temp [i] [j];
}
else if (i + 1 == 2)
{
cout << "Province B, Day " << j + 1 << " : ";
cin >> temp [i] [j];
}
else if (i + 1 == 3)
{
cout << "Province C, Day " << j + 1 << " : ";
cin >> temp [i] [j];
}
}
}
cout << "\n\nDisplaying Values:" << endl;
for (int i = 0; i < a; ++i)
{
for (int j = 0; j < b; ++j)
{
if (i + 1 == 1)
{
cout << "Province " << prov << ", Day " << j + 1 << " = " << temp [i] [j];
cout << endl;
}
else if (i + 1 == 2)
{
cout << "Province " << prov << ", Day " << j + 1 << " = " << temp [i] [j];
cout << endl;
}
else if (i + 1 == 3)
{
cout << "Province " << prov << ", Day " << j + 1 << " = " << temp [i] [j];
cout << endl;
}
}
}
getch();
return 0;
}
| true |
fb80bc8b03161f9593f470e0641c9ed52aee0942 | C++ | SaveliyLipaev/Homework-1-course | /test/ZachetTest/zachetTest_1/zachetTest_1/ListForSort.h | UTF-8 | 581 | 2.84375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <string>
struct List;
struct ListNode;
//returns the address of the selected memory cell for the List structure
List* createList();
//return true if list pustoy
bool isEmpty(List *list);
//Adds an item to the top of the list
void push(List *list, const std::string &str);
//Removes the entire list
void deleteList(List *list);
//Sorts the list, true if needed by name, false if needed by number
void mergeSort(List *list);
//prints a list
void printListInFile(List *list, std::ofstream &file);
ListNode* findNode(List *&list, const std::string &str); | true |
c68401c2497112f62f2f81af8579778d21ff2916 | C++ | Hariamy/projeto_metodosII | /modelo/vetor.h | UTF-8 | 575 | 2.671875 | 3 | [] | no_license | #ifndef VETOR_H
#define VETOR_H
#include <iostream>
#include <vector>
#include <cmath>
#include <cstring>
class vetor{
public:
int tam;
std::vector <double> *valores;
vetor (int novoTam, double valIncial = 0);
double& operator [] (int pos);
void operator = (vetor novosValores);
void operator = (vetor* novosValores);
vetor* operator + (vetor vet2);
vetor* operator - (vetor vet2);
void operator * (double constante);
double operator * (vetor vet2);
double tamanho ();
void unitario ();
void mostrar_debug ();
};
#endif //VETOR_H | true |
7b48b91e5731b8de59f4dbd7cd93e12e2a63090f | C++ | gbrlas/AVSP | /CodeJamCrawler/dataset/11_23462_28.cpp | UTF-8 | 1,240 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <iterator>
using namespace std;
vector<string> board;
int r;
int c;
bool cover(int row, int col)
{
if (row+1 == r || col+1 == c)
return false;
if ( (board[row+1][col] != '#') || (board[row][col+1] != '#') || (board[row+1][col+1] != '#') )
return false;
board[row][col] = '/';
board[row][col+1] = '\\';
board[row+1][col] = '\\';
board[row+1][col+1] = '/';
return true;
}
void solve(int t)
{
cin >> r;
cin >>c;
board.clear();
for(int i = 0; i < r; ++i)
{
string s;
cin >> s;
board.push_back(s);
}
for(int row = 0; row < r; ++row)
{
for(int col = 0; col < c; ++col)
{
if (board[row][col] != '#')
continue;
if (!cover(row,col))
{
cout << "Case #" << t+1 << ":" << endl;
cout << "Impossible" << endl;
return;
}
}
}
cout << "Case #" << t+1 << ":"<< endl;
copy(board.begin(), board.end(), ostream_iterator<string>(cout, "\n"));
}
int main()
{
int t;
cin >> t;
for(int i = 0; i < t; ++i)
solve(i);
} | true |
eba8494045e1b7856d50bd67a84af71e18d6c25f | C++ | SwarnenduGanguli25/Code-Asylums | /RecursionPractice/PrintStringsOfLengthK.cpp | UTF-8 | 960 | 3.9375 | 4 | [] | no_license | /*
Given a set of characters and a positive integer k,
print all possible strings of length k that can be formed from the given set.
Input:
set[] = {'a', 'b'}, k = 3
Output:
aaa
aab
aba
abb
baa
bab
bba
bbb
*/
#include<iostream>
using namespace std;
void printStringsOfLengthK(char set[], string prefix, int k, int n) {
if(k == 0)
{
cout << prefix << " ";
return;
}
for(int i = 0; i < n; i++) {
string newPrefix;
newPrefix = prefix + set[i];
printStringsOfLengthK(set, newPrefix, k - 1,n);
}
}
int main() {
cout << "Enter the length of set of characters" << endl;
int n;
cin >> n;
char set[n];
cout << "Enter the characters" << endl;
for(int i = 0; i < n; i++)
cin >> set[i];
cout << "Enter k" << endl;
int k;
cin >> k;
printStringsOfLengthK(set, "", k, n);
cout << endl;
return 0;
} | true |
928a8e5129981965819cd9344fcc0103c3f04c78 | C++ | lishuhuakai/Parser | /LR(1)/ActionGoto.h | GB18030 | 1,225 | 2.71875 | 3 | [] | no_license | #pragma once
#include "Common.h"
#include "Status.h"
/*
* ActionGotoҪڼ¼,ƽ,ǹԼ.
*/
class ActionGoto
{
friend class FiniteStateAutomaton;
public:
ActionGoto(Grammar&);
public:
~ActionGoto();
public:
struct Action {
enum Type { kShift, kReduce};
Type type;
rulePtr rule;
Action() :
type(kShift)
{}
Action(rulePtr& r) :
type(kReduce), rule(r)
{}
friend wostream& operator<<(wostream& os, Action& act) {
switch (act.type)
{
case kShift:
os << L"s";
break;
case kReduce:
os << L"r " << *act.rule;
break;
default:
break;
}
return os;
}
};
public:
void queryAction(int pos, wstring&);
void queryGoto(int pos, wstring&);
private:
typedef set<Item> itemSet;
typedef shared_ptr<set<Item>> itemSetPtr;
set<symbolPtr> symbols_; /* ¼ս */
map<int, itemSetPtr> mapping_; /* ڼ¼labelItemӳ */
map<int, shared_ptr<map<symbolPtr, Action>>> action_;
map<int, shared_ptr<map<symbolPtr, int>>> goto_;
Grammar& g_;
private:
void appendNewStat(int label,const shared_ptr<set<statusPtr>>& s);
void recordRelations(int from, int to, symbolPtr& s);
bool isReduceItem(itemSetPtr&);
};
| true |
a6e95248c2249f9596315fa12d9b36b31e2ff22f | C++ | Codes-iiita/UVa | /UVa-Solutions-master/608.cpp | UTF-8 | 1,541 | 2.984375 | 3 | [] | no_license | //Steven Kester Yuwono - UVa 608 - Counterfeit Dollar
#include <iostream>
#include <string>
using namespace std;
int main(){
int up[100];
int down[100];
for(int i=0;i<100;i++){
up[i]=0;
down[i]=0;
}
string temp;
string command[3];
char ans;
bool heavy=true;
int n;
cin>> n;
getline(cin,temp);
while(n--){
for(int i=0;i<3;i++){
getline(cin,command[0],' ');
getline(cin,command[1],' ');
getline(cin,command[2]);
if(command[2]=="even"){
int len=command[0].length();
for(int j=0;j<len;j++){
up[command[0][j]]=-3;
down[command[0][j]]=-3;
up[command[1][j]]=-3;
down[command[1][j]]=-3;
}
}
else if (command[2]=="up"){
int len=command[0].length();
for(int j=0;j<len;j++){
down[command[0][j]]++;
up[command[1][j]]++;
}
}
else if (command[2]=="down"){
int len=command[0].length();
for(int j=0;j<len;j++){
up[command[0][j]]++;
down[command[1][j]]++;
}
}
}
/*
cout << save[0] << endl;
cout << save[1] << endl;
cout << save[2] << endl;
for(int i=65;i<=76;i++){
cout << coins[i] << endl;
}*/
int max=-5;
for(int i=65;i<=76;i++){
if(max<up[i]){
max=up[i];
ans=i;
heavy=false;
}
if(max<down[i]){
max=down[i];
ans=i;
heavy=true;
}
}
if(heavy){
cout << ans << " is the counterfeit coin and it is heavy." << endl;
}
else{
cout << ans << " is the counterfeit coin and it is light." << endl;
}
for(int i=63;i<93;i++){
up[i]=0;
down[i]=0;
}
}
return 0;
}
| true |
d2c2599d8f783e07d6c46e542358f7f6b288ff3b | C++ | zhushiqi123/ios- | /C++语言程序设计 郑莉 第四版(课件、课后答案、例题源代码)/C++语言程序设计案例的源代码和目录/10852C++案例教程源代码/case05/5_11.cpp | GB18030 | 627 | 3.75 | 4 | [] | no_license | #include <iostream>
using namespace std;
class FunClass
{ static int count; //̬ݳԱ
public:
FunClass() { count++; cout << "Constructing object " <<count << endl; }
~FunClass() { cout << "Destroying object " << count << endl; count--; }
static int GetCount() { return count; } //̬Ա
};
int FunClass::count; //̬ݳԱ
int main()
{ FunClass a, b, c;
cout << "From Class, there are now " << FunClass::GetCount() << " in existence.\n";
cout << "From Object, there are now " << a.GetCount() <<" in existence.\n";
return 0;
}
| true |
b1deabf763ab8f7801036fdd52be86485a2500c1 | C++ | MrFICAX/StrukturePodataka | /Tudji labovi/LabPraktikum/struktureLAB/StrukturePodataka(Lab1)-zad8MATRICA/StrukturePodataka(Lab1)-zad8MATRICA/Node.cpp | UTF-8 | 304 | 2.90625 | 3 | [] | no_license | #include "Node.h"
Node::Node()
{
info = -1;
i = 0;
j = 0;
linkk = NULL;
linkv = NULL;
}
Node::Node(int a, int b, int c, Node* p1, Node* p2)
{
i = a;
j = b;
info = c;
linkv = p1;
linkk = p2;
}
void Node::print(){
cout << "[" << i << "," << j << "]" << "=" << info << " ";
}
Node::~Node()
{
} | true |
2baa1b40396e7d6705959cb2b23dc25373322049 | C++ | CRoberts245/CPlusPlusProjects | /CS2_Assignment2.cpp | UTF-8 | 2,079 | 3.515625 | 4 | [] | no_license | //============================================================================
// Name : Chapter8ProgrammingAssignment.cpp
// Description : Sorting & Searching functions
// Author : Cameron Roberts
// Extra Credit: No.
// Date : 02/03/2017
// OS : Windows
// IDE : Eclipse Neon
//============================================================================
#include "utilities.hpp"
using namespace std;
int main() {
vector<int> randomInts;
for(int i = 0; i < 10; i++){
randomInts.push_back (getRandomInt(0, 11));
}
bubbleSort(randomInts, 'd');
for(int i = 0; i < 10; i++){
cout << randomInts[i];
}
cout << " bubbleSort Descending" << endl;
bubbleSort(randomInts, 'a');
for (int i = 0; i < 10; i++) {
cout << randomInts[i];
}
cout << " bubbleSort Ascending" << endl;
selectionSort(randomInts, 'd');
for (int i = 0; i < 10; i++) {
cout << randomInts[i];
}
cout << " selectionSort Descending" << endl;
selectionSort(randomInts, 'a');
for (int i = 0; i < 10; i++) {
cout << randomInts[i];
}
cout << " selectionSort Ascending" << endl;
int userChoice;
do{
int userChoice = inputInt("Linear Search(0) or Binary Search(1)?(-1 to exit)", 0, 1, -1);
if(userChoice == -1){
break;
}
else if(userChoice == 0){
int searchValue = inputInt("Choose a value 0-10: ", 0, 10, -1);
bool foundLinear = linearSearch(randomInts, searchValue);
if(foundLinear == true){
cout << "Value is present." << endl;
}
else if (searchValue == -1){
break;
}
else{
cout << "Value is not present." << endl;
}
}
else if(userChoice == 1) {
int searchValue = inputInt("Choose a value 0-10: ", 0, 10, -1);
bool foundBinary = intVectorBinSearch(randomInts, searchValue);
if(foundBinary == true){
cout << "Value is present." << endl;
}
else if (searchValue == -1) {
break;
}
else{
cout << "Value is not present." << endl;
}
}
else{}
}while(true);
cout << "Have a nice day!" << endl; // prints "Have a nice day"
return 0;
}
| true |
7612662ec5648e377490decc2eb2178431971abf | C++ | luoxiaojian/dany | /type_index.h | UTF-8 | 1,140 | 2.84375 | 3 | [] | no_license | #ifndef TYPE_INDEX_H_
#define TYPE_INDEX_H_
#include <string>
enum TypeIndex {
TIUNKNOWN,
TIVOID,
TICHAR,
TII32,
TII64,
TIU32,
TIU64,
TISTRING,
TIPVOID,
TIPCHAR,
TIPI32,
TIPI64,
TIPU32,
TIPU64,
};
template <typename T>
TypeIndex type_index() {
return TIUNKNOWN;
}
template <>
TypeIndex type_index<void> {
return TIVOID;
}
template <>
TypeIndex type_index<char> {
return TICHAR;
}
template <>
TypeIndex type_index<int32_t> {
return TII32;
}
template <>
TypeIndex type_index<uint32_t> {
return TIU32;
}
template <>
TypeIndex type_index<int64_t> {
return TII64;
}
template <>
TypeIndex type_index<uint64_t> {
return TIU64;
}
template <>
TypeIndex type_index<std::string> {
return TISTRING;
}
template <>
TypeIndex type_index<void*> {
return TIPVOID;
}
template <>
TypeIndex type_index<char*> {
return TIPCHAR;
}
template <>
TypeIndex type_index<int32_t*> {
return TIPI32;
}
template <>
TypeIndex type_index<uint32_t*> {
return TIPU32;
}
template <>
TypeIndex type_index<int64_t*> {
return TIPI64;
}
template <>
TypeIndex type_index<uint64_t*> {
return TIPU64;
}
#endif
| true |
e227904bf7cdd6cb31980fe80aef23badd5bb98f | C++ | peauc/RType | /server/src/Engine/Zone.cpp | UTF-8 | 2,531 | 2.578125 | 3 | [] | no_license | //
// Created by romain on 21/01/18.
//
#include <Components/Zone/ZoneComponent.hpp>
#include "Zone.hpp"
#include "Game.hpp"
Engine::Zone::Zone(const Vector2d &topLeftCoords, const Vector2d &bottomRightCoords)
{
this->_topLeftCoords = topLeftCoords;
this->_bottomRightCoords = bottomRightCoords;
}
void Engine::Zone::createZone(const Vector2d &mapSize, Engine::Game &game) const
{
Engine::Entity *zone = new Engine::Entity(0);
Component::ZoneComponent *zoneComponent = new Component::ZoneComponent(zone,
Engine::Hitbox(Engine::Hitbox::ZONE,
Vector2d(0, 0),
Vector2d(
(this->_bottomRightCoords.x -
this->_topLeftCoords.x) /
mapSize.x * 8000,
(this->_bottomRightCoords.y -
this->_topLeftCoords.y) /
mapSize.y * 6000)
),
game.getWorld().get());
for (const auto &entity : this->_zoneObjects) {
Engine::Entity *clone = entity.createEntity(game);
if (clone != nullptr) {
clone->getTransformComponent().getPosition().x = entity._pos.x / mapSize.x * 8000;
clone->getTransformComponent().getPosition().y = entity._pos.y / mapSize.y * 6000;
zoneComponent->addEntity(std::unique_ptr<Entity>(clone));
}
}
zone->addComponent(zoneComponent);
if (game.getWorld()->getMediator() != nullptr) {
zoneComponent->registerToMediator(game.getWorld()->getMediator().get());
}
zone->setActive(true);
zone->getTransformComponent().getPosition().x = this->_topLeftCoords.x / mapSize.x * 8000;
zone->getTransformComponent().getPosition().y = this->_topLeftCoords.y / mapSize.y * 6000;
game.getWorld()->addObject(std::unique_ptr<Entity>(zone));
}
void Engine::Zone::addZoneObject(
const Engine::Zone::ZoneObject &zoneObject)
{
this->_zoneObjects.push_back(zoneObject);
}
const Vector2d &Engine::Zone::getTopLeftCoords() const
{
return (this->_topLeftCoords);
}
const Vector2d &Engine::Zone::getBotRightCoords() const
{
return (this->_bottomRightCoords);
}
const std::vector<Engine::Zone::ZoneObject> &
Engine::Zone::getZoneObjects() const
{
return (this->_zoneObjects);
}
Engine::Zone::ZoneObject::ZoneObject(const std::string &libname, const Vector2d &pos) : _libname(libname),
_pos(pos)
{
}
Engine::Entity *Engine::Zone::ZoneObject::createEntity(Engine::Game &game) const
{
return game.cloneEntity(this->_libname);
} | true |
4f3f9b294043b3087003d6cd41e455961203c700 | C++ | paopaoshuiqiang/c-learning | /chapter4/class_test/screen.h | UTF-8 | 261 | 2.5625 | 3 | [] | no_license | #pragma once
#include<iostream>
using namespace std;
class screen
{
public:
screen(void);
screen &move(int i,int j);
screen &set(string s)
{
return *this;
}
screen &display(ostream &os)
{
return *this;
}
~screen(void);
private:
int i,j,k;
};
| true |
0ec4e777269708a670eb20efc0d0ab54f22cf7bd | C++ | nuts-ilyam/Machine-Learning | /Affinity-propagation/affinity_propagation.cpp | WINDOWS-1251 | 2,224 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <ctime>
#include <cstdlib>
#include "Functions.h"
using namespace std;
//choose cluster labels
int main() {
int iteration = 0, Maxiteration = 600;
using Vector_of_edges = vector<Edge*>; //
vector<Vector_of_edges> from_edge(N); // row,
vector<Vector_of_edges> to_edge(N); // column
vector<Edge*> diagonal;
/*x
srand(time(NULL));
vector<string> coordinates; // [from, to]
string line;
ifstream in;
int x, y, N = 196591;
int counter = 0;
in.open("C:\\Users\\Nuts\\Documents\\Visual Studio 2015\\Projects\\AffinityPropagation\\Gowalla_edges.txt");
if (in.is_open())
{
cout << "Begin!!" << endl;
//counter = 0;
start = clock();
while (getline(in, line)) //&& counter < 1000)
{
split1(line, coordinates); // split
x = stoi(coordinates[0]);
y = stoi(coordinates[1]);
//cout << x << " " << y << endl;
double press = 0.0001 * (rand() % 101);
Edge *edge = new Edge(x, y, 1 + press, 0, 0); //pointer at the new edge,
from_edge[x].push_back(edge);
to_edge[y].push_back(edge);
//counter++;
}
finish = clock();
cout << "Time of reading : " << (double)(finish - start) / ((double)CLOCKS_PER_SEC) << endl;
in.close();
for (int i = 0; i < N; i++)
{
double press = 0.0001 * (rand() % 101);
Edge *edge = new Edge(i, i, -1 - press, 0, 0);
diagonal.push_back(edge);
}
}
*/
read(from_edge, to_edge, diagonal);
// reading and filling
while (iteration < Maxiteration)
{
iteration++;
// update matrix R
start = clock();
update_R(from_edge, diagonal);
//matrix A
update_A(to_edge, diagonal);
finish = clock();
cout << iteration << " iteration : " << (double)(finish - start) / ((double)CLOCKS_PER_SEC) << " s" << endl;
if (iteration%50==0)
{
choose_cluster(from_edge, diagonal);
}
}
choose_cluster(from_edge, diagonal);
system("pause");
return 0;
}
| true |
0c3887a97c652b69f223d3b695f6b17665142ed3 | C++ | anveshh/cpp-book | /src/Interview-Problems/FAANG/apple_min-time.cpp | UTF-8 | 1,340 | 3.5 | 4 | [] | no_license | /*
Problem Statement:
The computing cluster has multiple processors, each with 4 cores. The number of tasks to handle is equal to the
number of cores in the cluster. Each task has a predicted execution time and each processor has a specified time
when its core becomes available. Assuming that exactly 4 tasks are assigned to each processor ans those tasks run
independently(asynchronously) on the cores of the chosen processor.
What is the earliest time taht all tasks can be processed.
Sample Test Cases:
Sample: #1
ProcessorTime : {8,10}
taskTime : {2,2,3,1,8,7,4,5}
Output:
16
Sample: #2
ProcessorTime : {10,20}
taskTime : {2,3,1,2,5,8,4,3}
Output:
23
*/
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int minTime(vector<int> processorTime, vector<int> taskTime)
{
sort(processorTime.begin(), processorTime.end());
sort(taskTime.begin(), taskTime.end());
reverse(taskTime.begin(), taskTime.end());
int ans = 0;
int curTask = 0;
for (int procTime : processorTime)
{
for (int i = 0; i < 4; ++i)
{
int completionTime = taskTime[curTask] + procTime;
curTask++;
ans = max(ans, completionTime);
}
}
return ans;
}
int main()
{
cout << minTime({8, 10}, {2, 2, 3, 1, 8, 7, 4, 5}) << endl;
return 0;
}
| true |
1bb473cba2e0b43c0757aa76ff142b40344b2bc9 | C++ | jjzhang166/BOSS_ExternalLibs | /BOSS/RawFile/RawFileWriter.cxx | UTF-8 | 498 | 2.703125 | 3 | [] | no_license | #include "RawFile/RawFileWriter.h"
RawFileWriter::RawFileWriter(const std::string& fname)
{
m_wfs = raw_ofstream::instance(fname);
}
RawFileWriter::~RawFileWriter()
{
raw_ofstream::release();
}
int RawFileWriter::writeEvent(const uint32_t* pevt)
{
const char* pbuf = reinterpret_cast<const char*>(pevt);
int sizeBytes = pevt[1] * 4; //unit of size is word
raw_ofstream::lock();
int nfile = m_wfs->write_event(pbuf, sizeBytes);
raw_ofstream::unlock();
return nfile;
}
| true |
35b511ab2de052c04d4ac1ea11fe398a6207e8b4 | C++ | alansam/CF.STL_Containers_Stack | /CF.STL_Containers_Stack/stacks.cpp | UTF-8 | 9,942 | 2.890625 | 3 | [] | no_license | //
// stacks.cpp
// CF.STL_Containers_Stack
//
// Created by Alan Sampson on 4/10/21.
//
// MARK: - Reference.
// @see: https://en.cppreference.com/w/cpp/container/stack
// #see: https://en.wikipedia.org/wiki/Brainfuck
//
#include <iostream>
#include <iomanip>
#include <string>
#include <string_view>
#include <algorithm>
#include <numeric>
#include <compare>
#include <memory>
#include <type_traits>
#include <stack>
#include <deque>
#include <array>
#include <map>
#include <vector>
#include <stdexcept>
#include <cassert>
#include <cstddef>
using namespace std::literals::string_literals;
using namespace std::literals::string_view_literals;
// MARK: - Definitions
// MARK: - Local Constants.
// ....+....!....+....!....+....!....+....!....+....!....+....!....+....!....+....!
// MARK: namespace konst
namespace konst {
auto delimiter(char const dc = '-', size_t sl = 80) -> std::string const {
auto const dlm = std::string(sl, dc);
return dlm;
}
static
auto const dlm = delimiter();
static
auto const dot = delimiter('.');
} /* namespace konst */
#if (__cplusplus > 201707L)
#endif /* (__cplusplus > 201707L) */
// MARK: - Function Prototype.
auto C_stack(int argc, char const * argv[]) -> decltype(argc);
auto C_stack_deduction_guides(int argc, char const * argv[]) -> decltype(argc);
// MARK: - Implementation.
// ....+....!....+....!....+....!....+....!....+....!....+....!....+....!....+....!
/*
* MARK: main()
*/
int main(int argc, char const * argv[]) {
std::cout << "CF.STL_Containers_Stack\n"sv;
std::cout << "C++ Version: "s << __cplusplus << std::endl;
std::cout << '\n' << konst::dlm << std::endl;
C_stack(argc, argv);
std::cout << '\n' << konst::dlm << std::endl;
C_stack_deduction_guides(argc, argv);
return 0;
}
// MARK: - C_stack
// ....+....!....+....!....+....!....+....!....+....!....+....!....+....!....+....!
// ================================================================================
// ....+....!....+....!....+....!....+....!....+....!....+....!....+....!....+....!
/*
* MARK: C_stack()
*/
auto C_stack(int argc, char const * argv[]) -> decltype(argc) {
std::cout << "In "s << __func__ << std::endl;
/// Member functions
// ....+....!....+....!....+....!....+....!....+....!....+....!
std::cout << konst::dot << '\n';
std::cout << "std::stack - constructor"s << '\n';
{
std::stack<int> c1;
c1.push(5);
std::cout << c1.size() << '\n';
std::stack<int> c2(c1);
std::cout << c2.size() << '\n';
std::deque<int> deq { 3, 1, 4, 1, 5 };
std::stack<int> c3(deq);
std::cout << c3.size() << '\n';
std::cout << '\n';
};
/// Element access
// ....+....!....+....!....+....!....+....!....+....!....+....!
std::cout << konst::dot << '\n';
std::cout << "std::stack - top"s << '\n';
{
std::stack<int> stk;
stk.push( 2 );
stk.push( 6 );
stk.push( 51 );
std::cout << stk.size() << " elements on stack\n"sv;
std::cout << "Top element: "sv
<< stk.top() // Leaves element on stack
<< '\n';
std::cout << stk.size() << " elements on stack\n"sv;
stk.pop();
std::cout << stk.size() << " elements on stack\n"sv;
std::cout << "Top element: "sv << stk.top() << '\n';
std::cout << '\n';
};
/// Capacity
// ....+....!....+....!....+....!....+....!....+....!....+....!
std::cout << konst::dot << '\n';
std::cout << "std::stack - empty"s << '\n';
{
std::cout << std::boolalpha;
std::stack<int> container;
std::cout << "Initially, container.empty(): "sv
<< container.empty() << '\n';
container.push(42);
std::cout << "After adding elements, container.empty(): "sv
<< container.empty() << '\n';
container.pop();
std::cout << "Initially, container.size(): "sv
<< container.size() << '\n';
for (auto i_ : { 0, 1, 2, 3, 4, 5, 6, }) {
container.push(i_);
}
std::cout << "After adding elements, container.size(): "sv
<< container.size() << '\n';
std::cout << std::noboolalpha;
std::cout << '\n';
};
/// Modifiers
// ....+....!....+....!....+....!....+....!....+....!....+....!
std::cout << konst::dot << '\n';
std::cout << "std::stack - push"s << '\n';
{
/*
* ....+....!....+....!....+....!....+....!....+....!....+.
* BrainFuckInterpreter
* #see: https://en.wikipedia.org/wiki/Brainfuck
*/
class BrainFuckInterpreter {
std::map<unsigned, unsigned> open_brackets, close_brackets;
unsigned program_pos_ { 0 };
std::array<std::uint8_t, 32'768> data_;
int data_pos_ { 0 };
void collect_brackets_positions(std::string_view const program) {
std::stack<unsigned> brackets_stack;
for (auto pos { 0U }; pos != program.length(); ++pos) {
char const ch { program[pos] };
if ('[' == ch) {
brackets_stack.push(pos);
}
else if (']' == ch) {
if (brackets_stack.empty()) {
throw std::runtime_error("brackets [] do not match!"s);
}
else {
open_brackets[brackets_stack.top()] = pos;
close_brackets[pos] = brackets_stack.top();
brackets_stack.pop();
}
}
}
if (!brackets_stack.empty()) {
throw std::runtime_error("brackets [] do not match!"s);
}
}
void check_data_pos(int pos) {
if (pos < 0 or pos >= static_cast<int>(data_.size())) {
throw std::out_of_range{"data pointer out of bound"s};
}
}
public:
BrainFuckInterpreter(const std::string_view program) {
collect_brackets_positions(program);
data_.fill(0);
for (; program_pos_ < program.length(); ++program_pos_) {
switch (program[program_pos_]) {
case '<':
check_data_pos(--data_pos_);
break;
case '>':
check_data_pos(++data_pos_);
break;
case '-':
--data_[data_pos_];
break;
case '+':
++data_[data_pos_];
break;
case '.':
std::cout << data_[data_pos_];
break;
case ',':
std::cin >> data_[data_pos_];
break;
case '[':
if (data_[data_pos_] == 0) {
program_pos_ = open_brackets[program_pos_];
}
break;
case ']':
if (data_[data_pos_] != 0) {
program_pos_ = close_brackets[program_pos_];
}
break;
}
}
}
};
try {
BrainFuckInterpreter {
"++++++++[>++>>++>++++>++++<<<<<-]>[<+++>>+++<-]>[<+"
"+>>>+<<-]<[>+>+<<-]>>>--------.<<+++++++++.<<----.>"
">>>>.<<<------.>..++.<++.+.-.>.<.>----.<--.++.>>>+."
};
}
catch (std::exception & ex) {
std::cout << "BrainFuckInterpreter exception: "sv
<< ex.what()
<< '\n';
}
std::cout << '\n';
};
/// Modifiers
// ....+....!....+....!....+....!....+....!....+....!....+....!
std::cout << konst::dot << '\n';
std::cout << "std::stack - swap"s << '\n';
{
auto print = [](auto stack /* pass by value */, int id) {
std::cout << "s"sv << id << " ["sv << stack.size() << "]: "sv;
for (; !stack.empty(); stack.pop()) {
std::cout << stack.top() << ' ';
}
std::cout << (id > 1 ? "\n\n"sv : "\n"sv);
};
std::vector<std::string>
#define UTF16_
#if defined(UTF16_)
v1 { "1"s, "2"s, "3"s, "4"s, },
v2 { "\u2C6F"s, "B"s, "\u0186"s, "D"s, "\u018E"s, };
#elif defined(UTF8_)
v1 { "1"s, "2"s, "3"s, "4"s, },
v2 { "\xE2\xB1\xAF"s, "B"s, "\xC6\x86"s, "D"s, "\xC6\x8E"s, };
#else
v1 { "1"s, "2"s, "3"s, "4"s, },
v2 { "Ɐ"s, "B"s, "Ɔ"s, "D"s, "Ǝ"s, };
#endif
std::stack s1{std::move(v1)};
std::stack s2{std::move(v2)};
print(s1, 1);
print(s2, 2);
s1.swap(s2);
print(s1, 1);
print(s2, 2);
std::cout << '\n';
};
/// Non-member functions
// ....+....!....+....!....+....!....+....!....+....!....+....!
std::cout << konst::dot << '\n';
std::cout << "std::stack - std::swap(std::stack)"s << '\n';
{
std::stack<int> alice;
std::stack<int> bob;
auto print = [](auto const & title, auto const & cont) {
std::cout << title << " size="sv << cont.size();
std::cout << " top="sv << cont.top() << '\n';
};
for (int i_ = 1; i_ < 4; ++i_) {
alice.push(i_);
}
for (int i_ = 7; i_ < 11; ++i_) {
bob.push(i_);
}
// Print state before swap
print("alice:"sv, alice);
print("bob :"sv, bob);
std::cout << "-- SWAP\n"sv;
std::swap(alice, bob);
// Print state after swap
print("alice:"sv, alice);
print("bob :"sv, bob);
std::cout << '\n';
};
std::cout << std::endl; // make sure cout is flushed.
return 0;
}
// MARK: - C_stack_deduction_guides
// ....+....!....+....!....+....!....+....!....+....!....+....!....+....!....+....!
// ================================================================================
// ....+....!....+....!....+....!....+....!....+....!....+....!....+....!....+....!
/*
* MARK: C_stack_deduction_guides()
*/
auto C_stack_deduction_guides(int argc, char const * argv[]) -> decltype(argc) {
std::cout << "In "s << __func__ << std::endl;
// ....+....!....+....!....+....!....+....!....+....!....+....!
std::cout << konst::dot << '\n';
std::cout << "std::stack = deduction guides"s << '\n';
{
std::vector<int> vi = { 1, 2, 3, 4, };
std::stack si { vi }; // guide #1 deduces std::stack<int, vector<int>>
std::cout << '\n';
};
std::cout << std::endl; // make sure cout is flushed.
return 0;
}
| true |
8b2b212df2cb09cf3400e084a35511c3dd5c57a3 | C++ | kotwys/stx-gimp-plugin | /src/gimp_interop.cpp | UTF-8 | 2,205 | 2.53125 | 3 | [
"MIT"
] | permissive | #include <babl/babl.h>
#include "gimp_interop.h"
#include "stx/structure.h"
stx::Result<gint32> to_gimp(const stx::Image &data) {
using Result = stx::Result<gint32>;
gint32 image_id = gimp_image_new(
data.geometry.width,
data.geometry.height,
GIMP_RGB
);
gint32 layer_id = gimp_layer_new(
image_id,
"Texture",
data.geometry.width, data.geometry.height,
GIMP_RGBA_IMAGE,
100.0,
GIMP_NORMAL_MODE
);
gboolean success = gimp_image_insert_layer(image_id, layer_id, 0, 0);
if (!success) {
gimp_image_delete(image_id);
return ERR(stx::Error::GIMP_ERROR);
}
babl_init();
GeglBuffer *buffer = gimp_drawable_get_buffer(layer_id);
const Babl *bgra = babl_format_new(
babl_model("R~G~B~A"),
babl_type("u8"),
babl_component("B~"),
babl_component("G~"),
babl_component("R~"),
babl_component("A"),
NULL
);
gegl_buffer_set(
buffer,
GEGL_RECTANGLE(0, 0, data.geometry.width, data.geometry.height),
0, bgra, data.image_data, GEGL_AUTO_ROWSTRIDE
);
delete[] data.image_data;
gegl_buffer_flush(buffer);
g_object_unref(buffer);
babl_exit();
return OK(image_id);
}
stx::Result<stx::Image> from_gimp(
const StxParams ¶ms,
const gint32 drawable_id
) {
using Result = stx::Result<stx::Image>;
stx::Image img;
img.has_e6 = params.e6_write;
img.magical_number = params.magical_number;
GeglBuffer *buffer = gimp_drawable_get_buffer(drawable_id);
guint16 width = gegl_buffer_get_width(buffer);
guint16 height = gegl_buffer_get_height(buffer);
stx::Geometry geometry = {
width,
height,
params.scale_x,
params.scale_y
};
img.geometry = geometry;
babl_init();
img.image_data = new unsigned char[width * height * STX_NUM_CHANNELS];
const Babl *bgra = babl_format_new(
babl_model("R~G~B~A"),
babl_type("u8"),
babl_component("B~"),
babl_component("G~"),
babl_component("R~"),
babl_component("A"),
NULL
);
gegl_buffer_get(
buffer,
GEGL_RECTANGLE(0, 0, width, height),
1.0, bgra, img.image_data, GEGL_AUTO_ROWSTRIDE,
GEGL_ABYSS_NONE
);
g_object_unref(buffer);
babl_exit();
return OK(img);
}
| true |
9e3ddf87161c865d8250d8c5a09e14cc0cc1a14c | C++ | amazonsx/archives | /leetcode/minimum_path_sum/cpp/solution.cc | UTF-8 | 1,154 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <limits>
#include <assert.h>
#include <vector>
#define DEBUG
using namespace std;
class Solution {
public:
int minPathSum( vector<vector<int> > &grid);
};
int Solution::minPathSum( vector<vector<int> > &grid) {
assert(grid.size() > 0);
int m = grid.size(), n = grid.back().size();
vector<vector<int> > pathSum( m, vector<int>(n, numeric_limits<int>::max()));
pathSum[m-1][n-1] = grid[m-1][n-1];
for ( int i = m-2; i >= 0; i --)
pathSum[i][n-1] = pathSum[i+1][n-1] + grid[i][n-1];
for ( int i = n-2; i >= 0; i --)
pathSum[m-1][i] = pathSum[m-1][i+1] + grid[m-1][i];
int i = m - 2, j = n - 2;
while ( i >= 0 && j >= 0) {
pathSum[i][j] = grid[i][j] + min(pathSum[i+1][j], pathSum[i][j+1]);;
for ( int k = i - 1; k >= 0; k --)
pathSum[k][j] = grid[k][j] + min( pathSum[k+1][j], pathSum[k][j+1]);
for ( int k = j - 1; k >= 0; k --)
pathSum[i][k] = grid[i][k] + min( pathSum[i+1][k], pathSum[i][k+1]);
i --; j --;
}
return pathSum[0][0];
}
int main(int argc, char *argv[]) {
return 1;
}
| true |
6670bcd9a13e6715295c4e0a398406a76b7b56b2 | C++ | hank19960918/Image_Processing | /image_morphology/Source.cpp | UTF-8 | 2,882 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
void readImage(unsigned char *image, string path, int height, int width)
{
const char *s = path.c_str();
FILE *f = fopen(s, "rb");
fread(image, sizeof(unsigned char), height * width, f);
fclose(f);
}
void imageDilation(unsigned char *image1, unsigned char *image2, int width, int height, int maskHeight, int maskWidth, string name)
{
const char *s = name.c_str();
unsigned char *mask = new unsigned char[maskHeight * maskWidth];
for (int i = 0; i < maskHeight; i++)
{
for (int j = 0; j < maskWidth; j++)
{
mask[i * maskWidth + j] = 255;
}
}
int xBoundry = (maskHeight - 1) / 2, yBoundry = (maskWidth - 1) / 2;
for (int i = xBoundry; i < height - xBoundry; i++)
{
for (int j = yBoundry; j < width - yBoundry; j++)
{
bool flag = 0;
for (int mh = -xBoundry; mh < xBoundry + 1; mh++)
{
for (int mw = -yBoundry; mw < yBoundry + 1; mw++)
{
if (image1[(i + mh) * width + (j + mw)] == mask[(mh + xBoundry) * maskWidth + (mw + yBoundry)])
{
flag = 1;
}
else
{
image2[(i + mh) * width + (j + mw)] = 0;
}
}
}
if (flag == 1)
{
for (int mh = -xBoundry; mh < xBoundry + 1; mh++)
{
for (int mw = -yBoundry; mw < yBoundry + 1; mw++)
{
image2[(i + mh) * width + (j + mw)] = 255;
}
}
}
}
}
Mat newImage(height, width, CV_8U, image2);
imwrite(s, newImage);
}
void imageErosion(unsigned char *image1, unsigned char *image2, int width, int height, int maskHeight, int maskWidth, string name)
{
const char *s = name.c_str();
int xBoundry = (maskHeight - 1) / 2, yBoundry = (maskWidth - 1) / 2;
for (int i = xBoundry; i < height - xBoundry; i++)
{
for (int j = yBoundry; j < width - yBoundry; j++)
{
bool flag = 0;
for (int mh = -xBoundry; mh < xBoundry+1; mh++)
{
for (int mw = -yBoundry; mw < yBoundry+1; mw++)
{
if (image1[(i + mh) * width + (j + mw)] == 0)
{
flag = 1;
break;
}
}
}
if (flag == 1)
{
image2[i * width + j] = 0;
}
else
{
image2[i * width + j] = 255;
}
}
}
Mat imageRro(height, width, CV_8U, image2);
imwrite(s, imageRro);
}
int main()
{
int height = 180, width = 360;
unsigned char *imageLetter = new unsigned char[height * width];
readImage(imageLetter, "letters_360x180.raw", height, width);
unsigned char *imageOutput = new unsigned char[height * width];
unsigned char *imageOutput2 = new unsigned char[height * width];
imageErosion(imageLetter, imageOutput, width, height, 3, 3, "imageErosion.png");
imageDilation(imageLetter, imageOutput2, width, height, 5, 5, "imageDilation.png");
delete[] imageLetter;
system("pause");
return 0;
} | true |
364f8e458c159d690180022062fc0299d28c06a7 | C++ | limdor/quoniam | /src/viewpoint-measures/KullbackLeibler.h | UTF-8 | 405 | 2.53125 | 3 | [] | no_license | #ifndef KULLBACK_LEIBLER_H
#define KULLBACK_LEIBLER_H
//Project includes
#include "Measure.h"
/// Class that implements the kullback leibler distance [Sbert et al. 2005]
class KullbackLeibler : public Measure
{
public:
explicit KullbackLeibler(const std::string &pName);
/// Method that computes the measure
void Compute(const SceneInformationBuilder *pSceneInformationBuilder);
};
#endif
| true |
829e83275c84f0fd012b5fea48e1c7a036bf6799 | C++ | bhrgv/MissionRnD-C-Strings-Worksheet | /src/commonWords.cpp | UTF-8 | 1,849 | 3.6875 | 4 | [] | no_license | /*
OVERVIEW: Given two strings, find the words that are common to both the strings.
E.g.: Input: "one two three", "two three five". Output: "two", "three".
INPUTS: Two strings.
OUTPUT: common words in two given strings, return 2D array of strings.
ERROR CASES: Return NULL for invalid inputs.
NOTES: If there are no common words return NULL.
*/
#include <stdio.h>
#include <malloc.h>
#define SIZE 31
int strLength(char* str){
if (str == NULL)
return 0;
int i;
for (i = 0; str[i] != '\0'; i++){}
return i;
}
char ** commonWords(char *str1, char *str2) {
int len1 = strLength(str1);
char** result;
int start[20], end[20];
int len2 = strLength(str2);
int count = 0;
if (len1==0||len2==0)
return NULL;
int i=0, j=0;
while (str1[i] != '\0')
{
while (str1[i] == ' '&&str1[i] != '\0')
i++;
int itemp = i;
j = 0;
while (str2[j] != '\0')
{
int flag = 0;
i = itemp;
while (str2[j] == ' ' && str2[j] != '\0')
j++;
if (str2[j] == '\0')
break;
while (str1[i] == str2[j] || (str1[i] == ' '&&str2[j] == '\0') || (str1[i] == '\0'&&str2[j] == ' '))
{
if ((str1[i] == ' '&&str2[j] == '\0') || (str1[i] == '\0'&&str2[j] == ' ') || (str1[i] == ' '&&str2[j] == ' ')){
start[count] = itemp;
end[count] = i;
count++;
flag = 1;
break;
}
else
{
i++, j++;
}
}
if (flag)
break;
else
{
while (str2[j] != ' '&&str2[j] != '\0')
j++;
}
}
i = itemp;
while (str1[i] != ' '&&str1[i] != '\0')
i++;
}
if (!count)
return NULL;
else
{
result = (char**)malloc(count*sizeof(char));
for (i = 0; i < count; i++)
{
char* str = (char*)malloc(31 * sizeof(char));
j = start[i];
int k = 0;
while (j < end[i])
{
str[k] = str1[j];
j++;
k++;
}
str[k] = '\0';
result[i] = str;
}
}
return result;
} | true |
a4addbe91884a7d4917c1c1f3279ad3c8b77ce09 | C++ | bryanedds/ax | /src/cpp/ax/math.cpp | UTF-8 | 5,035 | 2.96875 | 3 | [
"MIT"
] | permissive | #include <algorithm>
#include <functional>
#include <cmath>
#include "ax/math.hpp"
namespace ax
{
float ax::saturate(float value, float max)
{
return std::max(0.0f, std::min(max, value));
}
ax::v2 get_ortho(const ax::v3& vector)
{
return ax::v2(vector.x, vector.y);
}
ax::line2 get_ortho(const ax::line3& line)
{
VAL& line_ortho = ax::line2(
ax::v2(std::get<0>(line).x, std::get<0>(line).y),
ax::v2(std::get<1>(line).x, std::get<1>(line).y));
return line_ortho;
}
ax::triangle2 get_ortho(const ax::triangle3& triangle)
{
VAL& triangle_ortho = ax::triangle2(
ax::v2(std::get<0>(triangle).x, std::get<0>(triangle).y),
ax::v2(std::get<1>(triangle).x, std::get<1>(triangle).y),
ax::v2(std::get<2>(triangle).x, std::get<2>(triangle).y));
return triangle_ortho;
}
float get_depth(const ax::v2& point, const ax::triangle3& triangle)
{
VAL& triangle_ortho = ax::get_ortho(triangle);
VAL& coords = ax::get_barycentric_coords(point, triangle_ortho);
VAL depth =
std::get<0>(triangle).z * coords.x +
std::get<1>(triangle).z * coords.y +
std::get<2>(triangle).z * coords.z;
return depth;
}
ax::v2 get_interpolation(const ax::v2& point, const ax::triangle2& triangle)
{
VAL& coords = ax::get_barycentric_coords(point, triangle);
VAL interpolation =
std::get<0>(triangle) * coords.x +
std::get<1>(triangle) * coords.y +
std::get<2>(triangle) * coords.z;
return interpolation;
}
ax::v3 get_tangent(const ax::triangle3& triangle)
{
return (std::get<1>(triangle) - std::get<0>(triangle)).NormalizeSafe();
}
ax::v3 get_normal(const ax::triangle3& triangle)
{
VAR cross_product = (std::get<1>(triangle) - std::get<0>(triangle)) ^ (std::get<2>(triangle) - std::get<0>(triangle));
return cross_product.NormalizeSafe();
}
ax::box2 get_bounds(const ax::triangle2& triangle)
{
VAL left = std::min(
std::get<0>(triangle).x,
std::min(std::get<1>(triangle).x, std::get<2>(triangle).x));
VAL right = std::max(
std::get<0>(triangle).x,
std::max(std::get<1>(triangle).x, std::get<2>(triangle).x));
VAL bottom = std::min(
std::get<0>(triangle).y,
std::min(std::get<1>(triangle).y, std::get<2>(triangle).y));
VAL top = std::max(
std::get<0>(triangle).y,
std::max(std::get<1>(triangle).y, std::get<2>(triangle).y));
return
{{ left, bottom },
{ right, top }};
}
ax::box2 get_intersection(const ax::box2& box, const ax::box2& box2)
{
return
{{std::min(box.first.x, box2.first.x),
std::min(box.first.y, box2.first.y)},
{std::max(box.second.x, box2.second.x),
std::max(box.second.y, box2.second.y)}};
}
ax::v3 get_barycentric_coords(ax::v2 point, const ax::triangle2& triangle)
{
VAL& a = ax::v3(std::get<2>(triangle).x - std::get<0>(triangle).x, std::get<1>(triangle).x - std::get<0>(triangle).x, std::get<0>(triangle).x - point.x);
VAL& b = ax::v3(std::get<2>(triangle).y - std::get<0>(triangle).y, std::get<1>(triangle).y - std::get<0>(triangle).y, std::get<0>(triangle).y - point.y);
VAL& u = a ^ b;
if (std::abs(u.z) < 1.0f)
{
// we have a degenerate triangle
// NOTE: I don't have high confidence in the math here being correct. It was converted from
// integer math and I suspect I thereby lost something.
return ax::v3(-1.0f, 1.0f, 1.0f);
}
return ax::v3(
1.0f - (u.x + u.y) / u.z,
u.y / u.z,
u.x / u.z);
}
bool get_in_bounds(const ax::v2& point, const ax::triangle2& triangle)
{
VAL& coords = ax::get_barycentric_coords(point, triangle);
return coords.x >= 0 && coords.y >= 0 && coords.z >= 0;
}
bool get_in_bounds(const ax::v2& point, const ax::box2& box)
{
VAL result =
point.x >= std::get<0>(box).x && point.y >= std::get<0>(box).y &&
point.x < std::get<1>(box).x && point.y < std::get<1>(box).y;
return result;
}
bool get_in_bounds(const ax::v2i& point, const ax::box2i& box)
{
VAL result =
point.x >= std::get<0>(box).x && point.y >= std::get<0>(box).y &&
point.x < std::get<1>(box).x && point.y < std::get<1>(box).y;
return result;
}
bool get_in_bounds(const ax::v2& point, const ax::v2& size)
{
return ax::get_in_bounds(point, ax::box2(ax::zero<ax::v2>(), size));
}
bool get_in_bounds(const ax::v2i& point, const ax::v2i& size)
{
return ax::get_in_bounds(point, ax::box2i(ax::zero<ax::v2i>(), size));
}
}
| true |
3a8796227ccf0154d0acd9f4308276ce535d58b8 | C++ | tectronics/minerstatemachine | /src/game/algorithms/flocking.cpp | UTF-8 | 11,502 | 2.75 | 3 | [] | no_license | #include "flocking.h"
#include "../vehicle.h"
#include "../stages/ingame.h"
#include "../entitymanager.h"
#include <cassert>
using std::string;
using std::vector;
//------------------------- ctor -----------------------------------------
//
//------------------------------------------------------------------------
Flocking::Flocking(Vehicle* agent):
m_pVehicle(agent),
m_iFlags(0),
m_dWeightCohesion(1.0),
m_dWeightAlignment(1.0),
m_dWeightSeparation(2.0),
m_SummingMethod(prioritized)
{
}
//---------------------------------dtor ----------------------------------
Flocking::~Flocking()
{
}
/////////////////////////////////////////////////////////////////////////////// CALCULATE METHODS
//----------------------- Calculate --------------------------------------
//
// calculates the accumulated steering force according to the method set
// in m_SummingMethod
//------------------------------------------------------------------------
Vector2D Flocking::Calculate()
{
//reset the steering force
m_vSteeringForce.Zero();
switch (m_SummingMethod)
{
case weighted_average:
m_vSteeringForce = CalculateWeightedSum(); break;
case prioritized:
m_vSteeringForce = CalculatePrioritized(); break;
case dithered:
m_vSteeringForce = CalculateDithered();break;
default:m_vSteeringForce = Vector2D(0,0);
}//end switch
return m_vSteeringForce;
}
//------------------------- ForwardComponent -----------------------------
//
// returns the forward oomponent of the steering force
//------------------------------------------------------------------------
double Flocking::ForwardComponent()
{
return m_pVehicle->Heading().Dot(m_vSteeringForce);
}
//--------------------------- SideComponent ------------------------------
// returns the side component of the steering force
//------------------------------------------------------------------------
double Flocking::SideComponent()
{
return m_pVehicle->Side().Dot(m_vSteeringForce);
}
//--------------------- AccumulateForce ----------------------------------
//
// This function calculates how much of its max steering force the
// vehicle has left to apply and then applies that amount of the
// force to add.
//------------------------------------------------------------------------
bool Flocking::AccumulateForce(Vector2D &RunningTot,
Vector2D ForceToAdd)
{
//calculate how much steering force the vehicle has used so far
double MagnitudeSoFar = RunningTot.Length();
//calculate how much steering force remains to be used by this vehicle
double MagnitudeRemaining = m_pVehicle->MaxForce() - MagnitudeSoFar;
//return false if there is no more force left to use
if (MagnitudeRemaining <= 0.0) return false;
//calculate the magnitude of the force we want to add
double MagnitudeToAdd = ForceToAdd.Length();
//if the magnitude of the sum of ForceToAdd and the running total
//does not exceed the maximum force available to this vehicle, just
//add together. Otherwise add as much of the ForceToAdd vector is
//possible without going over the max.
if (MagnitudeToAdd < MagnitudeRemaining)
{
RunningTot += ForceToAdd;
}
else
{
//add it to the steering force
RunningTot += (Vec2DNormalize(ForceToAdd) * MagnitudeRemaining);
}
return true;
}
//---------------------- CalculatePrioritized ----------------------------
//
// this method calls each active steering behavior in order of priority
// and acumulates their forces until the max steering force magnitude
// is reached, at which time the function returns the steering force
// accumulated to that point
//------------------------------------------------------------------------
Vector2D Flocking::CalculatePrioritized()
{
Vector2D force;
//these next three can be combined for flocking behavior (wander is
//also a good behavior to add into this mix)
if (On(separation))
{
force = Separation(m_pVehicle->World()->Agents()) * m_dWeightSeparation;
if (!AccumulateForce(m_vSteeringForce, force)) return m_vSteeringForce;
}
if (On(allignment))
{
force = Alignment(m_pVehicle->World()->Agents()) * m_dWeightAlignment;
if (!AccumulateForce(m_vSteeringForce, force)) return m_vSteeringForce;
}
if (On(cohesion))
{
force = Cohesion(m_pVehicle->World()->Agents()) * m_dWeightCohesion;
if (!AccumulateForce(m_vSteeringForce, force)) return m_vSteeringForce;
}
return m_vSteeringForce;
}
//---------------------- CalculateWeightedSum ----------------------------
//
// this simply sums up all the active behaviors X their weights and
// truncates the result to the max available steering force before
// returning
//------------------------------------------------------------------------
Vector2D Flocking::CalculateWeightedSum()
{
if (On(separation))
{
m_vSteeringForce += Separation(m_pVehicle->World()->Agents()) * m_dWeightSeparation;
}
if (On(allignment))
{
m_vSteeringForce += Alignment(m_pVehicle->World()->Agents()) * m_dWeightAlignment;
}
if (On(cohesion))
{
m_vSteeringForce += Cohesion(m_pVehicle->World()->Agents()) * m_dWeightCohesion;
}
m_vSteeringForce.Truncate(m_pVehicle->MaxForce());
return m_vSteeringForce;
}
//---------------------- CalculateDithered ----------------------------
//
// this method sums up the active behaviors by assigning a probabilty
// of being calculated to each behavior. It then tests the first priority
// to see if it should be calcukated this simulation-step. If so, it
// calculates the steering force resulting from this behavior. If it is
// more than zero it returns the force. If zero, or if the behavior is
// skipped it continues onto the next priority, and so on.
//
// NOTE: Not all of the behaviors have been implemented in this method,
// just a few, so you get the general idea
//------------------------------------------------------------------------
Vector2D Flocking::CalculateDithered()
{
//reset the steering force
m_vSteeringForce.Zero();
if (On(separation) && RandFloat() < 0.2)
{
m_vSteeringForce += Separation(m_pVehicle->World()->Agents()) *
m_dWeightSeparation / 0.2;
if (!m_vSteeringForce.isZero())
{
m_vSteeringForce.Truncate(m_pVehicle->MaxForce());
return m_vSteeringForce;
}
}
if (On(allignment) && RandFloat() < 0.3)
{
m_vSteeringForce += Alignment(m_pVehicle->World()->Agents()) *
m_dWeightAlignment / 0.3;
if (!m_vSteeringForce.isZero())
{
m_vSteeringForce.Truncate(m_pVehicle->MaxForce());
return m_vSteeringForce;
}
}
if (On(cohesion) && RandFloat() < 0.6)
{
m_vSteeringForce += Cohesion(m_pVehicle->World()->Agents()) *
m_dWeightCohesion / 0.6;
if (!m_vSteeringForce.isZero())
{
m_vSteeringForce.Truncate(m_pVehicle->MaxForce());
return m_vSteeringForce;
}
}
return m_vSteeringForce;
}
/////////////////////////////////////////////////////////////////////////////// START OF BEHAVIORS
//---------------------------- Separation --------------------------------
//
// this calculates a force repelling from the other neighbors
//------------------------------------------------------------------------
Vector2D Flocking::Separation(const vector<Vehicle*> &neighbors)
{
Vector2D SteeringForce;
for (unsigned int a=0; a<neighbors.size(); ++a)
{
//make sure this agent isn't included in the calculations and that
//the agent being examined is close enough. ***also make sure it doesn't
//include the evade target ***
if(neighbors[a] != m_pVehicle)
{
Vector2D ToAgent = Vector2D(m_pVehicle->GetPosX(), m_pVehicle->GetPosY()) - Vector2D(neighbors[a]->GetPosX(), neighbors[a]->GetPosY());
//scale the force inversely proportional to the agents distance
//from its neighbor.
SteeringForce += Vec2DNormalize(ToAgent)/ToAgent.Length();
}
}
return SteeringForce;
}
//---------------------------- Alignment ---------------------------------
//
// returns a force that attempts to align this agents heading with that
// of its neighbors
//------------------------------------------------------------------------
Vector2D Flocking::Alignment(const vector<Vehicle*>& neighbors)
{
//used to record the average heading of the neighbors
Vector2D AverageHeading;
//used to count the number of vehicles in the neighborhood
int NeighborCount = 0;
//iterate through all the tagged vehicles and sum their heading vectors
for (unsigned int a=0; a<neighbors.size(); ++a)
{
//make sure *this* agent isn't included in the calculations and that
//the agent being examined is close enough ***also make sure it doesn't
//include any evade target ***
if(neighbors[a] != m_pVehicle)
{
AverageHeading += neighbors[a]->Heading();
++NeighborCount;
}
}
//if the neighborhood contained one or more vehicles, average their
//heading vectors.
if (NeighborCount > 0)
{
AverageHeading /= (double)NeighborCount;
AverageHeading -= m_pVehicle->Heading();
}
return AverageHeading;
}
//-------------------------------- Cohesion ------------------------------
//
// returns a steering force that attempts to move the agent towards the
// center of mass of the agents in its immediate area
//------------------------------------------------------------------------
Vector2D Flocking::Cohesion(const vector<Vehicle*> &neighbors)
{
//first find the center of mass of all the agents
Vector2D CenterOfMass, SteeringForce;
int NeighborCount = 0;
//iterate through the neighbors and sum up all the position vectors
for (unsigned int a=0; a<neighbors.size(); ++a)
{
//make sure *this* agent isn't included in the calculations and that
//the agent being examined is close enough ***also make sure it doesn't
//include the evade target ***
if(neighbors[a] != m_pVehicle)
{
CenterOfMass += Vector2D(neighbors[a]->GetPosX(), neighbors[a]->GetPosY());
++NeighborCount;
}
}
if (NeighborCount > 0)
{
//the center of mass is the average of the sum of positions
//CenterOfMass /= (double)NeighborCount;
CenterOfMass = Vector2D(EntityManager::Instance()->GetEntityByID(ent_Peon)->GetPosX(), EntityManager::Instance()->GetEntityByID(ent_Peon)->GetPosY());
//now seek towards that position
Vector2D DesiredVelocity = Vec2DNormalize(CenterOfMass - Vector2D(m_pVehicle->GetPosX(), m_pVehicle->GetPosY())) * m_pVehicle->MaxSpeed();
SteeringForce = DesiredVelocity - m_pVehicle->Velocity();
}
//the magnitude of cohesion is usually much larger than separation or
//allignment so it usually helps to normalize it.
return Vec2DNormalize(SteeringForce);
}
| true |
ed65fb36a01f80864513d9210b4de13609ec93d1 | C++ | iamsourav37/DataStructure | /C++/Linear_data_structure/dynamic_stack.cpp | UTF-8 | 2,942 | 4.15625 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Stack
{
private:
int top;
int length;
int *stack_array;
void initArray()
{
stack_array = new int[1];
length = 1;
}
void doubleArray()
{
int *temp = new int[length * 2];
if (temp == NULL)
{
cout << "\n\n\tStack Overflow";
exit(0);
}
length *= 2;
for (int i = 0; i < length / 2; i++)
{
temp[i] = stack_array[i];
}
stack_array = temp;
}
void shrinkArray()
{
int *temp = new int[length / 2];
length /= 2;
for (int i = 0; i < length; i++)
{
temp[i] = stack_array[i];
}
stack_array = temp;
}
bool isEmpty()
{
if (top == -1)
return true;
else
return false;
}
public:
Stack()
{ // default constructor
top = -1;
length = 0;
stack_array = NULL;
}
void push(int data)
{
if (length == 0)
initArray();
else if (top == length - 1)
doubleArray();
top = top + 1;
stack_array[top] = data;
}
void pop()
{
if (isEmpty())
{
cout << "\n\n\t Stack underflow";
return;
}
top = top - 1; // 1 2 0 0
if (top == (length / 2) - 1)
shrinkArray();
}
int peek()
{
if (isEmpty())
{
cout << "\n\n\t Stack underflow";
return -1;
}
return stack_array[top];
}
void display()
{
if (isEmpty())
{
cout << "\n\n\t Stack underflow";
return;
}
cout << "\n\n\t Stack Length : " << top + 1;
cout << "\n\n\t Length : " << length;
cout << "\n\n Stack : \n";
for (int i = top; i >= 0; i--)
{
cout << "\t" << stack_array[i] << endl;
}
}
};
int main()
{
int choice;
Stack stack = Stack();
while (true)
{
cout << "\n\t 1. Push" << endl;
cout << "\n\t 2. Pop" << endl;
cout << "\n\t 3. Peek" << endl;
cout << "\n\t 4. Display" << endl;
cout << "\n\t 5. Exit" << endl;
cout << "\n\n\t Enter Your Choice : " << endl;
cin >> choice;
switch (choice)
{
case 1:
cout << "\n\n\t Enter data : ";
int data;
cin >> data;
stack.push(data);
break;
case 2:
stack.pop();
break;
case 3:
cout << "\n\n\t Peek : " << stack.peek();
break;
case 4:
stack.display();
break;
case 5:
exit(0);
break;
default:
cout << "\n\n\t Wrong Choice";
break;
}
}
return 0;
} | true |
66b1c8b3ae9980c63fe9b2e9d046b4856ae41686 | C++ | rilex001/College | /Vezbe/for/v5zad1.cpp | UTF-8 | 177 | 2.578125 | 3 | [] | no_license | #include<stdio.h>
#include<math.h>
int main() {
int n, suma= 0;
scanf("%d", &n);
for(int i = 0; i < n; i++) {
suma += pow(i, 2);
}
printf("Suma %d", suma);
return 0;
}
| true |
e7ae5cf6ec7d2d2e22f114376e51a8fc5a10319d | C++ | hqber/Huffman-Decompression | /main.cpp | GB18030 | 3,047 | 3.03125 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include"Extract.h"
using namespace std;
int main()
{
int n;//Чֽ
HuffNode hufftree[512];//511
for (int a = 0; a < 512; a++)
{
hufftree[a].parent = -1;
hufftree[a].ch = NULL;
hufftree[a].count = -1;
hufftree[a].lch = -1;
hufftree[a].rch = -1;
}
while (1)
{
int opt, flag = 0; // ÿνѭҪʼflagΪ0
char ifname[256];
char ofname[256]; // ļ
printf(" =======================================\n");
cout << " ***Huffmanļѹ***" << endl;
printf(" =======================================\n");
printf(" 1ѹ \n");
printf(" 2ѹ \n");
printf(" 3˳ \n");
printf(" IJ \n");
scanf("%d", &opt);
if (opt == 3)
exit(1);
else
{
printf("ļ");
fflush(stdin); // ձֹgetsȡļ
gets(ifname);
printf("ɵļ");
fflush(stdin);
gets(ofname);
}
switch (opt)
{
case 1:
{
//ļֽڳ
FILE *file;
file = fopen(ifname, "r");
fseek(file, SEEK_SET, SEEK_END);
long flength = ftell(file);
fclose(file);
n = DuXuWenJian(hufftree, ifname);//ȡļֽƵЧֽڣƵʲΪ0
creat(hufftree, n);//ָ뺢Ӹױʾ
creat_hmcode(hufftree, n);//ɹ
//for (int d = 0; d < 2 * n - 1; d++)//
//{
// printf("%4d: %4u, %9d, %9d, %9d, %9d ", d, hufftree[d].ch, hufftree[d].count, hufftree[d].parent, hufftree[d].lch, hufftree[d].rch); /* ڲ */
// for (int f = 0; hufftree[d].bits[f] == '0' || hufftree[d].bits[f] == '1'; f++)
// printf("%c", hufftree[d].bits[f]);
// printf("\n");
//}
flag = compress(hufftree, n, flength, ifname, ofname); // ѹֵжǷļ
if (flag != -1)
{
cout << "\nԵ," << ifname << "ѹС\n";
cout << "˿," << ofname << "ѹϡ\n";
}
break;
}
case 2:
{
flag = extract(hufftree, ifname, ofname); // ѹֵжǷļ
if (flag != -1)
{
cout << "\nԵ," << ifname << "ڽѹС\n";
cout << "˿," << ofname << "ѹϡ\n";
}
break;
}
if (flag == -1)
printf("\nSorry ,ļ\"%s\"\n", ifname); // ־Ϊ-1ļ
else
printf("\nɣ\n"); //
system("pause");
system("CLS");
}
return 0;
}
} | true |
f5426d456af2bd79b00f6ee52d5ccefe73588a3f | C++ | pawan941394/CPP-Programming | /function/ex13.cpp | UTF-8 | 207 | 2.890625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int sum(int num){
int total =num*(num+1)/2;
cout<<total<<endl;
return total;
}
int main(){
int n;
cin>>n;
sum(n);
return 0;
} | true |
8e709cef4a114b081a1d929bcf578b479aea9c58 | C++ | glebshapa/Algorithms | /pref_func.cpp | UTF-8 | 896 | 3.421875 | 3 | [] | no_license | // Дана строка s[0 \ldots n-1]. Требуется вычислить для неё префикс-функцию, т.е. массив чисел \pi[0 \ldots n-1], где \pi[i] определяется следующим образом: это такая наибольшая длина наибольшего собственного суффикса подстроки s[0 \ldots i], совпадающего с её префиксом (собственный суффикс — значит не совпадающий со всей строкой). В частности, значение \pi[0] полагается равным нулю.
vector<int> prefix_function (string s) {
int n = (int) s.length();
vector<int> pi (n);
for (int i=1; i<n; ++i) {
int j = pi[i-1];
while (j > 0 && s[i] != s[j])
j = pi[j-1];
if (s[i] == s[j]) ++j;
pi[i] = j;
}
return pi;
}
| true |
40ac4efa0a24d6ff7279e9fa596baecd166464d3 | C++ | Jiaqi07/Usaco-Bronze-Silver-XCamp-Practice-Cpp | /XCamp200/XCamp 200 Midterm/nthnumber.cpp | UTF-8 | 369 | 3.25 | 3 | [] | no_license | /*
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{
int n, out;
cin >> n;
int *s;
s = new int[n];
s[0] = 0;
s[1] = 1;
s[2] = 1;
for(int i = 3; i < n; ++i){ //1: M, 2: O, 3: O, 4: D
s[i] = s[i - 3] + 2 * s[i-2] + s[i-1];
}
cout << s[n-1];
return 0;
}
*/ | true |
661e2a725286e0751e7e1f50f75d134d10958c48 | C++ | harrylyx/forPat | /leetcode/daily/minimumLengthEncoding.cpp | UTF-8 | 2,769 | 3.71875 | 4 | [] | no_license | #include <algorithm>
#include <iostream>
#include <string.h>
#include <vector>
using namespace std;
class Trie
{
private:
bool is_string = false;
Trie *next[26] = {nullptr};
public:
Trie() {}
void insert(const string &word) //插入单词
{
Trie *root = this;
for (const auto &w : word)
{
if (root->next[w - 'a'] == nullptr)
root->next[w - 'a'] = new Trie();
root = root->next[w - 'a'];
}
root->is_string = true;
}
bool search(const string &word) //查找单词
{
Trie *root = this;
for (const auto &w : word)
{
if (root->next[w - 'a'] == nullptr)
return false;
root = root->next[w - 'a'];
}
return root->is_string;
}
bool startsWith(string prefix) //查找前缀
{
Trie *root = this;
for (const auto &p : prefix)
{
if (root->next[p - 'a'] == nullptr)
return false;
root = root->next[p - 'a'];
}
return true;
}
};
int minimumLengthEncodingMine(vector<string> &words)
{
int record[words.size()];
memset(record, 0, sizeof(record));
for (unsigned int i = 0; i < words.size(); i++)
{
if (record[i] != 0)
continue;
for (unsigned int j = 0; j < words.size(); j++)
{
if (record[j] != 0 || i == j)
continue;
int a = words[i].length() - 1;
int b = words[j].length() - 1;
while (words[i][a] == words[j][b] && a >= 0 && b >= 0)
{
a--;
b--;
}
if (a == -1)
{
record[i] = 2;
break;
}
else if (b == -1)
{
record[i] = 1;
record[j] = 2;
}
}
if (record[i] == 0)
record[i] = 1;
}
int result = 0;
for (unsigned int i = 0; i < words.size(); i++)
{
if (record[i] == 1)
{
result += words[i].length() + 1;
}
}
return result;
}
bool cmp1(string a, string b) //int为数组数据类型
{
return a.length() > b.length(); //降序排列
}
int minimumLengthEncoding(vector<string> &words)
{
Trie trie;
sort(words.begin(), words.end(), cmp1);
int cnt = 0;
for (auto word : words)
{
reverse(word.begin(), word.end());
if (!trie.startsWith(word))
{
trie.insert(word);
cnt += word.length() + 1;
}
}
return cnt;
}
int main()
{
vector<string> words{"time", "me", "bell"};
cout << minimumLengthEncoding(words);
} | true |
7baa4562501d8cacc9ab5e9a2bd71372e2be020d | C++ | ariannmichael/PLP-Dirlididi | /PalavrasIngratas/PalavrasIngratas.cpp | UTF-8 | 483 | 3.28125 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
int main() {
int cont = 0;
bool ingrata = true;
string entrada;
while(cont < 3) {
cin >> entrada;
ingrata = true;
for(unsigned int i = 0; i < entrada.length(); i++) {
if(entrada[i] == 'a' || entrada[i] == 'e' || entrada[i] == 'i' || entrada[i] == 'o' || entrada[i] == 'u') {
ingrata = false;
break;
}
}
if(ingrata == true) {
cont++;
cout << entrada << endl;
}
}
return 0;
}
| true |
077b8fd1664dfb8f416a4c54a5608bc4be300424 | C++ | JoanStinson/SpaceInvaders | /Space Invaders/Space Invaders/ModuleAudio.h | UTF-8 | 614 | 2.53125 | 3 | [
"MIT"
] | permissive | #ifndef _MODULEAUDIO_H_
#define _MODULEAUDIO_H_
#include "Module.h"
#include <vector>
struct Mix_Chunk;
typedef struct _Mix_Music Mix_Music;
class ModuleAudio : public Module
{
public:
ModuleAudio(bool start_enabled = true);
~ModuleAudio();
bool Init() override;
bool CleanUp() override;
public:
bool PlayMusic(const char* path, float fade_time = 2.f);
void PauseMusic();
void ResumeMusic();
void StopMusic();
unsigned int LoadSfx(const char* path);
bool PlaySfx(unsigned int sfx, int repeat = 0);
private:
Mix_Music* music = nullptr;
std::vector<Mix_Chunk*> sfxs;
};
#endif // _MODULEAUDIO_H_ | true |
ea14283c4bb9b8651ed2adac865d6c334cdb84ea | C++ | SimulationEverywhere-Models/RT-DEVS-CAN-BUS | /data_structures/can_structure.hpp | UTF-8 | 1,502 | 2.78125 | 3 | [] | no_license | #ifndef __CAN_STRUCTURE_HPP__
#define __CAN_STRUCTURE_HPP__
#ifndef RT_ARM_MBED
#include <memory.h>
#include <iostream>
enum CANFormat {
CANStandard = 0,
CANExtended = 1,
CANAny = 2
};
typedef enum CANFormat CANFormat;
enum CANType {
CANData = 0,
CANRemote = 1
};
typedef enum CANType CANType;
struct CAN_Message
{
unsigned int id;
unsigned char data[8];
unsigned char len;
CANFormat format;
CANType type;
};
class CANMessage : public CAN_Message
{
public :
CANMessage()
{
id = 0U;
memset(data, 0,8);
len = 8U;
format = CANStandard;
type = CANRemote;
}
CANMessage(unsigned int _id, const unsigned char *_data, unsigned char _len = 8)
{
id = _id;
memcpy(data,_data,_len);
len = _len;
format = CANStandard;
type = CANRemote;
}
};
istream& operator>> (istream& is, CANMessage& msg) //overloading operators for cater for our model
{
is >> msg.id;
is >> msg.len;
for (int i = 0; i<msg.len ; i++)
{
is >> msg.data[i];
}
return is;
}
ostream& operator<<(ostream& os, const CANMessage& msg)
{
os << msg.id << " " << (unsigned int) msg.len;
for (int i = 0; i<msg.len ; i++)
{
os << " " << (unsigned int) msg.data[i];
}
os << " " << msg.format;
os << " " << msg.type;
return os;
}
#endif
#endif | true |
809bf0fe30c030e5de7d7e455b2c48aae5e7bc8e | C++ | TenFifteen/SummerCamp | /spw/174-dugeon-game/dungeon_game.cc | UTF-8 | 1,822 | 3.15625 | 3 | [] | no_license | #include <cstdio>
#include <climits>
#include <vector>
using namespace std;
#define min(a, b) ((a) < (b) ? (a) : (b))
/**
* Problem: Find the minimum health the knight should have, then when he pass
* the dugeon, he will always have health point more than one.
* Sovle: see detail in the discuss board.
* Tips: 1. in grid, we have two ways of thoughts, from left-top to right-bottom and backwards.
* 2. the knight at least have 1 after every battle.
* 3. non-context-related: every time we get the negative need, we just step into an
* new stage with no relation with the backwards.
*/
int calculateMinimumHP(vector<vector<int> >& dungeon)
{
int row = dungeon.size();
int col = dungeon[0].size();
vector<vector<int> > dp(row+1, vector<int>(col+1, INT_MAX));
dp[row][col-1] = dp[row-1][col] = 1;
for (int i = row-1; i >= 0; --i) {
for (int j = col-1; j >= 0; --j) {
int need = min(dp[i][j+1], dp[i+1][j]) - dungeon[i][j];
dp[i][j] = need <= 0 ? 1 : need;
}
}
return dp[0][0];
}
int main()
{
return 0;
}
class Solution {
public:
int calculateMinimumHP(vector<vector<int>>& dungeon) {
if (dungeon.size() <= 0) return 0;
int m = dungeon.size(), n = dungeon[0].size();
vector<vector<int>> dp(m, vector<int>(n, INT_MIN));
dp[m-1][n-1] = 1 - dungeon[m-1][n-1];
for (int i = m-2; i >= 0; --i) {
dp[i][n-1] = max(dp[i+1][n-1], 1) - dungeon[i][n-1];
}
for (int j = n-2; j >= 0; --j) {
dp[m-1][j] = max(dp[m-1][j+1], 1) - dungeon[m-1][j];
}
for (int i = m-2; i >= 0; --i) {
for (int j = n-2; j >= 0; --j) {
dp[i][j] = max(min(dp[i+1][j], dp[i][j+1]), 1) - dungeon[i][j];
}
}
return max(dp[0][0], 1);
}
};
| true |
c8de4af4ba426e39db16081e551c1fcb5327e6ea | C++ | oguzkaran/Arcelik-Eskisehir-Cpp-Dec-2020 | /src/SampleCpp/Date.hpp | UTF-8 | 681 | 3.203125 | 3 | [] | no_license | #ifndef DATE_HPP_
#define DATE_HPP_
#include <iostream>
class Date {
friend std::ostream& operator <<(std::ostream& os, const Date& r);
friend std::istream& operator >>(std::istream& is, Date& r);
private:
int m_day, m_month, m_year;
int m_dayOfWeek;
public:
Date() {}
Date(int day, int month, int year)
{
//...
m_day = day;
m_month = month;
m_year = year;
}
public:
//getters
int getDay() const { return m_day; }
int getMonth() const { return m_month; }
int getYear() const { return m_year; }
int getDayOfWeek() const { return m_dayOfWeek; }
//setters
void setDay(int value);
void setMonth(int value);
void setYear(int value);
};
#endif //DATE_HPP_
| true |
989cae3a60c7badf38567af4b45b1fe7e6fe5a6b | C++ | MLCGEE/carduino | /firmware/firmware.ino | UTF-8 | 2,154 | 2.546875 | 3 | [] | no_license | // CARDUINO v0.0.1
// github.com/bitlabio/carduino
void setup() {
// initialize the serial communication:
Serial.begin(115200);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
pinMode(9, OUTPUT);
}
int lastv = 0;
unsigned long count = 0;
unsigned long lasttime = 0;
void loop() {
// send the value of analog input 0:
int voltage = analogRead(A0);
unsigned long time= micros();
unsigned long timedelta = time - lasttime;
if ((voltage == 0) && (lastv > 0)) { count++;
//Serial.println(count);
//Serial.print("timedelta microseconds:");
//Serial.println(timedelta);
double rpm = timedelta;
rpm = (1.0 / (rpm * 4.0 / 1000000.0)) * 60.0 ;
Serial.print("{\"rpm\":");
Serial.print(rpm);
Serial.print(",\"count\":");
Serial.print(count);
Serial.print(",\"timedelta\":");
Serial.print(timedelta);
Serial.println("}");
lasttime = time;
engine(count%4, 250); //rotation and spark duration
}
if (timedelta > 100000) {
//oh oh nothing happening
double rpm = timedelta;
rpm = (1.0 / (rpm * 4.0 / 1000000.0)) * 60.0 ;
Serial.print("{\"rpm\":");
Serial.print(rpm);
Serial.print(",\"count\":");
Serial.print(count);
Serial.print(",\"timedelta\":");
Serial.print(timedelta);
Serial.println("}");
}
lastv = voltage;
//delayMicroseconds(10);
}
int nextpiston = 1;
void engine(unsigned long count, int duration) {
if (count == 0) {
digitalWrite(13-nextpiston, 1);
delayMicroseconds(duration);
digitalWrite(13-nextpiston, 0);
//FIRING ORDER
switch (nextpiston) {
case 1:
nextpiston = 3;
break;
case 2:
nextpiston = 1;
break;
case 3:
nextpiston = 4;
break;
case 4:
nextpiston = 2;
break;
default:
nextpiston = 1; //backup to 1. shouldnt be needed.
break;
}
// END ORDER
}
}
| true |
ab296b845c550ac49b005d98bb543e6750d8b753 | C++ | EmersonLucena/algorithms | /algorithms/Hash.cpp | UTF-8 | 1,396 | 2.578125 | 3 | [] | no_license | #include <bits/stdc++.h>
#define MAXN 250250
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pll;
struct myhash {
ll chash[MAXN][2];
ll mult[MAXN][2];
ll b1, M1, b2, M2;
myhash(ll b1 = 311, ll M1 = 1000000021, ll b2 = 317, ll M2 = 1000000009) :
b1(b1), M1(M1), b2(b2), M2(M2) { calc();}
void calc() {
mult[0][0] = mult[0][1] = 1;
for(ll i=1; i < MAXN; i++) {
mult[i][0] = (mult[i-1][0] * b1)%M1;
mult[i][1] = (mult[i-1][1] * b2)%M2;
}
}
// Preprocess new string in global string st
void compute(string &st) {
chash[0][0] = chash[0][1] = st[0] + 1;
for(int i=1; i<(int)st.size();i++) {
chash[i][0] = ((chash[i-1][0]*b1)%M1 + st[i] + 1)%M1;
chash[i][1] = ((chash[i-1][1]*b2)%M2 + st[i] + 1)%M2;
}
}
// Hash of substring [l, r] INCLUSIVE
pll substr(ll l, ll r) {
if(!l) return make_pair(chash[r][0], chash[r][1]);
ll p1 = (chash[r][0] - (chash[l-1][0] * mult[r-l+1][0])%M1 + M1)%M1;
ll p2 = (chash[r][1] - (chash[l-1][1] * mult[r-l+1][1])%M2 + M2)%M2;
return make_pair(p1, p2);
}
};
char s[MAXN];
string st;
int main() {
myhash h;
while(true) {
scanf(" %s", s);
st = s;
h.compute(st);
int l = 0, r = 0;
while(true) {
scanf("%d %d", &l, &r);
if(l == -1) break;
pll resp = h.substr(l, r);
printf("%s\n%lld\n%lld\n\n", st.substr(l, r - l + 1).c_str(), resp.first, resp.second);
}
}
return 0;
}
| true |
2d061d668de58863960307e330c54ff7ab74ba69 | C++ | mohmahkho/competitive-programming | /src/graph/get_connected_components.cc | UTF-8 | 665 | 2.8125 | 3 | [] | no_license | auto get_connected_components(const vector<vector<int>>& g) {
int n = (int) g.size();
int ncc = 0; // number of connected components
vector<int> cc(n, -1); // cc[u] = connected component id of u
vector<int> id(n); // id[u] = id of u in its cc
vector<int> sz; // sz[t] = size of connected component t
int id_cnt;
auto dfs = [&] (auto self, int u) -> void {
cc[u] = ncc;
id[u] = id_cnt++;
for(int v : g[u]) if(cc[v] == -1) {
self(self, v);
}
};
for(int u = 0; u < n; ++u) {
if(cc[u] == -1) {
id_cnt = 0;
dfs(dfs, u);
sz.push_back(id_cnt);
++ncc;
}
}
return make_tuple(ncc, cc, id, sz);
}
| true |
dcac9cf2e020c1679f49be9c68f83a792d004d00 | C++ | codegrande/syscall_exploit_CVE-2018-8897 | /io.cpp | UTF-8 | 2,114 | 2.53125 | 3 | [] | no_license | /*
* Module Name:
* io.cpp
*
* Abstract:
* Generic file I/O routines.
*
* Authors:
* Nick Peterson <everdox@gmail.com> | http://everdox.net/
* Nemanja (Nemi) Mulasmajic <nm@triplefault.io> | http://triplefault.io/
*
*/
#include "stdafx.h"
#include "io.h"
#include "mm.h"
/*
* Maps a PE file from disk into memory.
*/
bool IoMapImage(_In_ PWCHAR Path, _Inout_ PVOID& Mapping, _Inout_ size_t& Size)
{
if (!Path)
return false;
bool Success = false;
// Open the file on disk.
HANDLE FileHandle = CreateFileW(Path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (FileHandle != INVALID_HANDLE_VALUE)
{
HANDLE FileMappingHandle = CreateFileMappingW(FileHandle, NULL, (PAGE_READONLY | SEC_IMAGE), 0, 0, NULL);
if (FileMappingHandle)
{
// Map it to memory.
Mapping = MapViewOfFile(FileMappingHandle, FILE_MAP_READ, 0, 0, 0);
if (Mapping)
{
Size = MmGetRegionSize(Mapping);
Success = true;
}
CloseHandle(FileMappingHandle);
}
CloseHandle(FileHandle);
}
return Success;
}
/*
* Retrieves the start address and size of a PE section.
*/
PVOID IoGetImageSection(_In_ PVOID Base, _In_ const char* Name, _Inout_ size_t& Size)
{
if (!Name)
return NULL;
// Valid 'MZ' header?
PIMAGE_DOS_HEADER DosHeader = (PIMAGE_DOS_HEADER)Base;
if (!DosHeader || DosHeader->e_magic != IMAGE_DOS_SIGNATURE)
return NULL;
// Valid 'PE00' header?
PIMAGE_NT_HEADERS NtHeaders = (PIMAGE_NT_HEADERS)((uintptr_t)DosHeader + DosHeader->e_lfanew);
if (NtHeaders->Signature != IMAGE_NT_SIGNATURE)
return NULL;
// Loop through all the sections.
PIMAGE_SECTION_HEADER SectionHeader = IMAGE_FIRST_SECTION(NtHeaders);
for (WORD i = 0; i < NtHeaders->FileHeader.NumberOfSections; ++i)
{
// Does it match the section we're looking for?
if (!strncmp((const char*)SectionHeader->Name, Name, RTL_NUMBER_OF(SectionHeader->Name)))
{
Size = (size_t)SectionHeader->Misc.VirtualSize;
return (PVOID)((uintptr_t)Base + SectionHeader->VirtualAddress);
}
SectionHeader++;
}
// Failed to find the section.
return NULL;
} | true |
2bb3eca0a3025eb05ba38daa8b45fe234c9fc0fd | C++ | mpm-msc/snow | /src/core/rendering/GLFWWindow.cpp | UTF-8 | 2,564 | 2.703125 | 3 | [] | no_license | #include "GLFWWindow.hpp"
GLFWWindow::GLFWWindow() {
// GLFW INIT: ORDER IS IMPORTANT
glfwSetErrorCallback(error_callback);
if (!glfwInit()) exit(EXIT_FAILURE);
window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "OpenGL Project", NULL,
NULL);
if (!window) {
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, key_callback);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetCursorPos(window, WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSwapInterval(0);
// GLEW INIT
GLenum err = glewInit();
if (err != GLEW_OK) {
fprintf(stderr, "Error: '%s'\n", glewGetErrorString(err));
}
// During init, enable debug output
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback(debug::MessageCallback, 0);
}
float GLFWWindow::anglesize = 0.001f;
float GLFWWindow::rotation = 0.0f;
float GLFWWindow::stepsize = 0.05f;
GLFWwindow* GLFWWindow::window;
bool GLFWWindow::shouldClose() {
return !glfwWindowShouldClose(GLFWWindow::window);
}
void GLFWWindow::stop() {
glfwDestroyWindow(GLFWWindow::window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
void GLFWWindow::clear() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0.5, 0.5, 0.5, 0);
}
void GLFWWindow::swapBuffers() {
glfwSwapBuffers(window);
glfwPollEvents();
}
static void error_callback(int error, const char* description) {
fputs(description, stderr);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action,
int mods) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
else if (key == GLFW_KEY_Q) {
if (action == GLFW_PRESS) {
}
} else if (key == GLFW_KEY_E) {
if (action == GLFW_PRESS) {
}
} else if (key == GLFW_KEY_W) {
if (action == GLFW_PRESS) {
}
} else if (key == GLFW_KEY_S) {
if (action == GLFW_PRESS) {
}
} else if (key == GLFW_KEY_D) {
if (action == GLFW_PRESS) {
} else if (action == GLFW_RELEASE) {
}
} else {
ParticleRenderer::world.update(key, GLFWWindow::stepsize);
}
}
static void mouse_callback(GLFWwindow* window, double xpos, double ypos) {
double mouse_x = (xpos - WINDOW_WIDTH / 2) * GLFWWindow::anglesize;
double mouse_y = (-ypos + WINDOW_HEIGHT / 2) * GLFWWindow::anglesize;
ParticleRenderer::world.update(mouse_x, mouse_y);
glfwSetCursorPos(window, WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2);
}
| true |
271efcc75e6c2f305868a96e6836933e7a9abc5d | C++ | anik-chy/OnlineJudges | /UVA/11936 The Lazy Lumberjacks.cpp | UTF-8 | 341 | 2.625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define pb push_back
int main()
{
int t;
cin>>t;
while(t--)
{
int x,y,z;
cin >> x >> y >> z;
if(x+y>z && y+z>x && z+x>y)
cout << "OK" << endl;
else
cout << "Wrong!!" << endl;
}
return 0;
}
| true |
70fac86709c2a2c5079bba319a2f4fe93b389a46 | C++ | lijiaxin-dut/leetcode | /leetcode_train/Solution_6.cpp | GB18030 | 1,224 | 3.34375 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<set>
#include<algorithm>
#include<vector>
using namespace std;
//The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of
//rows like this: (you may want to display this pattern in a fixed font for better legibility)
//
//P A H N
//A P L S I I G
//Y I R
//һά
//ϵ뵽
class Solution_6 {
public:
string convert(string s, int numRows) {
int n = s.size();
string rs;
int col_number = n / (numRows * 2 - 2)*numRows + numRows;
vector<vector<char>>map(numRows, vector<char>(col_number));
int group_col = numRows - 1;
int current_col = 0;
int current_row = 0;
int index = 0;
while (true) {
while (current_row<numRows&&index<n)
map[current_row++][current_col] = s[index++];
current_col++;
current_row = current_row - 2;
while (current_row>0 && index<n)
map[current_row--][current_col++] = s[index++];
if (index == n)
break;
}
for (auto &one_row : map)
{
for (auto &one_char : one_row) {
if(one_char!='\0')
rs.push_back(one_char);
}
}
return rs;
}
};
//int main() {
// Solution_6 s;
// s.convert("PAYPALISHIRING", 3);
//} | true |
61e14fe3421877344dd516fe823de7a893e2fcb5 | C++ | gcohara/greesy | /src/peripherals/gpio.cpp | UTF-8 | 3,039 | 2.84375 | 3 | [] | no_license | #include "../../inc/peripherals/gpio.hpp"
#include "../../inc/peripherals/rcc.hpp"
#include <cstdint>
GPIO_PORT::GPIO_PORT(GPIOPortLetter const pl):
port_letter{ pl },
letter_number{ static_cast<int>(pl) },
base{ GPIOA_BASE + (0x100 * letter_number)},
port_mode_register{ base },
output_type_register{ base + 0x1 },
pullup_pulldown_register{ base + 0x3 },
input_data_register{ base + 0x4 },
output_data_register{ base + 0x5 },
alternate_function_low{ base + 0x8 },
alternate_function_high{ base + 0x9 }
{
RCC::enable_gpio_port_clock(*this);
status = PeripheralStatus::ON;
}
void GPIO_PORT::initialise_gp_output(GPIO_PIN const& pin) {
*port_mode_register &= ~(3 << (pin.pin_number * 2));
*port_mode_register |= (1 << (pin.pin_number * 2));
}
void GPIO_PORT::output_high(GPIO_PIN const& pin) {
*output_data_register |= (1 << pin.pin_number);
}
void GPIO_PORT::output_low(GPIO_PIN const& pin) {
*output_data_register &= ~(1 << pin.pin_number);
}
void GPIO_PORT::toggle_output(GPIO_PIN const& pin) {
*output_data_register ^= (1 << pin.pin_number);
}
void GPIO_PORT::initialise_gp_input(GPIO_PIN const& pin, GPIOInputPUPD const pupd) {
if (pupd == GPIOInputPUPD::PushDown) {
*pullup_pulldown_register |= (2 << (2 * pin.pin_number));
} else {
*pullup_pulldown_register |= (1 << (2 * pin.pin_number));
}
}
bool GPIO_PORT::read_input_pin(GPIO_PIN const& pin) {
return (*input_data_register & (1 << pin.pin_number));
}
GPIO_PIN::GPIO_PIN(GPIO_PORT & prt, int const pin_num):
pin_number{ pin_num }, port_number{ static_cast<int>(prt.port_letter)}, port{ prt } {}
void GPIO_PIN::initialise_gp_output() {
port.initialise_gp_output(*this);
}
void GPIO_PIN::initialise_gp_input(GPIOInputPUPD const pupd) {
port.initialise_gp_input(*this, pupd);
}
void GPIO_PIN::output_low() {
port.output_low(*this);
}
void GPIO_PIN::output_high() {
port.output_high(*this);
}
void GPIO_PIN::toggle_output() {
port.toggle_output(*this);
}
bool GPIO_PIN::read() {
return port.read_input_pin(*this);
}
void GPIO_PIN::initialise_analogue() {
*port.port_mode_register |= (3 << (2 * pin_number));
}
void GPIO_PIN::set_alternate_function(std::uint8_t const af_num) noexcept {
auto const pin_num{ this->pin_number };
auto const port{ this->port };
// Clear mode, then set to alternate function mode
*port.port_mode_register &= ~(3 << (pin_num * 2));
*port.port_mode_register |= (2 << (pin_num * 2));
if (pin_num >= 8) {
*port.alternate_function_high |= ((af_num % 16) << ((pin_num % 8) * 4));
}
else {
*port.alternate_function_low |= ((af_num % 16) << ((pin_num % 8) * 4));
}
}
void GPIO_PIN::set_pullup_pulldown(GPIOInputPUPD const pupd) noexcept {
auto const pin_num{ this-> pin_number };
auto const port{ this->port };
*port.pullup_pulldown_register &= ~(3 << (pin_num * 2));
*port.pullup_pulldown_register |= (static_cast<std::uint8_t>(pupd) << 2);
}
| true |
6b857b723708d33b3746161cfd5dc1f8d0f824bc | C++ | antman88/ExamExtraTasks | /ExamExtraTasks/MyVector.h | UTF-8 | 1,011 | 3.5 | 4 | [] | no_license | #pragma once
#include <iostream>
using namespace std;
//
class IteratorMyList
{
public:
virtual bool hasNext() = 0;
virtual int current() = 0;
virtual int begin() = 0;
virtual int end() = 0;
virtual void reset() = 0;
};
//
class MyVector : public IteratorMyList
{
private:
int size;
int *pArr;
int currIndex;
void printFromFirstToLast();
public:
MyVector(int size);
~MyVector();
void print()
{
printFromFirstToLast();
}
int getSize()
{
return this->size;
}
virtual bool hasNext()
{
if (this->currIndex < this->size - 1)
return true;
else
return false;
}
virtual int current()
{
int currValue = this->pArr[this->currIndex];
this->currIndex++;
return currValue;
}
virtual int begin()
{
return this->pArr[0];
}
virtual int end()
{
return this->pArr[this->size - 1];
}
virtual void reset()
{
this->currIndex = 0;
}
friend ostream& operator << (ostream& os, const MyVector& t);
int& operator[](int);
const int& operator[](int i) const;
}; | true |
57eeda78f332eca885071dad95991b4d9fb9fc0b | C++ | mamunhpath/leet-code | /merge-k-sorted-lists-16.cpp | UTF-8 | 1,049 | 3.234375 | 3 | [] | no_license | // https://leetcode.com/problems/merge-k-sorted-lists/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
typedef ListNode LN;
ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.size() == 0) return NULL;
int k = 1 + log2(lists.size());
for(int i = 0; i < k; i++){
int offset = (1 << i);
for(int j = 0; j + offset < lists.size(); j += 2*offset){
lists[j] = merge(lists[j], lists[j + offset]);
}
}
return lists[0];
}
LN* merge(LN* l1, LN* l2){
LN* head = new LN(-1), *temp = head;
while(l1 && l2){
(l1->val > l2->val) ? ((head->next = l2) && (l2 = l2->next)) : ((head->next = l1) && (l1 = l1->next));
head = head->next;
}
head->next = l1 ? l1 : l2;
return temp->next;
}
};
| true |
cbb114ea68e443cc7262fd86da804b297351f409 | C++ | myCigar/Cpp-Primer | /ch03/ex3_40.cpp | UTF-8 | 322 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
int main()
{
const char cstr1[] = {'h', 'e', 'l', 'l', 'o', '\0'};
const char cstr2[] = {'w', 'o', 'r', 'l', 'd', '!', '\0'};
char cstr3[20] = { };
strcat(cstr3, cstr1);
strcat(cstr3, " ");
strcat(cstr3, cstr2);
cout << cstr3 << endl;
return 0;
}
| true |
706b4a55b63ee1ebc5333855055a711919216f9d | C++ | alexyena/Cpp_term_application_tetris | /CppTermApplicationTetris/CppTermApplicationTetris/Board.h | UTF-8 | 506 | 2.640625 | 3 | [] | no_license | #pragma once
#include <bitset>
#include <iostream>
#define B_WIDTH 10
#define B_DEPTH 20
class Board
{
std::bitset<B_WIDTH> board[B_DEPTH];
public:
Board();
void setBoardPieceByCoordinate(int i, int j, bool value);
bool getBoardPieceByCoordinate(int i, int j);
bool isLineFull(int row_id);
bool isLastLineEmpty();
void deleteLine(int line);
void unifyUncollidedLines(int line);
int deleteFullLines();
void ClearLine(int row_id);
void clear();
~Board();
};
| true |
5f0ff18483bbf9929109e6d69c88fb087b2b533a | C++ | spadapet/ffcore | /util/Types/FixedInt.h | UTF-8 | 7,528 | 3.28125 | 3 | [] | no_license | #pragma once
namespace ff
{
// 24 bits of whole number and 8 bits of fraction
class FixedInt
{
public:
inline FixedInt() = default;
inline FixedInt(const FixedInt& rhs) = default;
inline FixedInt(int data);
inline FixedInt(float data);
inline FixedInt(double data);
inline FixedInt(bool data);
inline FixedInt(unsigned int data);
inline FixedInt(unsigned long long data);
inline FixedInt(long double data);
inline operator int() const;
inline operator float() const;
inline operator double() const;
inline operator bool() const;
inline FixedInt& operator=(const FixedInt& rhs) = default;
inline bool operator!() const;
inline bool operator==(const FixedInt& rhs) const;
inline bool operator!=(const FixedInt& rhs) const;
inline bool operator<(const FixedInt& rhs) const;
inline bool operator>(const FixedInt& rhs) const;
inline bool operator<=(const FixedInt& rhs) const;
inline bool operator>=(const FixedInt& rhs) const;
inline FixedInt operator-() const;
inline FixedInt operator+() const;
inline FixedInt operator++();
inline FixedInt operator++(int after);
inline FixedInt operator--();
inline FixedInt operator--(int after);
inline FixedInt& operator+=(const FixedInt& rhs);
inline FixedInt& operator-=(const FixedInt& rhs);
inline FixedInt& operator*=(const FixedInt& rhs);
inline FixedInt& operator/=(const FixedInt& rhs);
inline FixedInt operator+(const FixedInt& rhs) const;
inline FixedInt operator-(const FixedInt& rhs) const;
inline FixedInt operator*(const FixedInt& rhs) const;
inline FixedInt operator/(const FixedInt& rhs) const;
inline FixedInt operator%(const FixedInt& rhs) const;
inline FixedInt& operator*=(int rhs);
inline FixedInt& operator/=(int rhs);
inline FixedInt operator*(int rhs) const;
inline FixedInt operator/(int rhs) const;
inline FixedInt abs() const;
inline FixedInt ceil() const;
inline FixedInt floor() const;
inline FixedInt trunc() const;
inline FixedInt copysign(FixedInt sign) const;
inline void swap(FixedInt& rhs);
inline static FixedInt FromRaw(int data);
inline int GetRaw() const;
private:
inline static FixedInt FromExpanded(int64_t data);
inline int64_t GetExpanded() const;
static const int FIXED_COUNT = 8;
static const int FIXED_MAX = (1 << FIXED_COUNT);
static const int LO_MASK = FIXED_MAX - 1;
static const int HI_MASK = ~LO_MASK;
int _data;
};
}
ff::FixedInt::FixedInt(int data)
: _data(data << FIXED_COUNT)
{
}
ff::FixedInt::FixedInt(float data)
: _data((int)(data* FIXED_MAX))
{
}
ff::FixedInt::FixedInt(double data)
: _data((int)(data* FIXED_MAX))
{
}
ff::FixedInt::FixedInt(bool data)
: _data((int)data << FIXED_COUNT)
{
}
ff::FixedInt::FixedInt(unsigned int data)
: _data((int)(data << FIXED_COUNT))
{
}
ff::FixedInt::FixedInt(unsigned long long data)
: _data((int)(data << FIXED_COUNT))
{
}
ff::FixedInt::FixedInt(long double data)
: _data((int)(data* FIXED_MAX))
{
}
ff::FixedInt::operator int() const
{
return _data >> FIXED_COUNT;
}
ff::FixedInt::operator float() const
{
return (float)(double)*this;
}
ff::FixedInt::operator double() const
{
return (double)_data / FIXED_MAX;
}
ff::FixedInt::operator bool() const
{
return _data != 0;
}
bool ff::FixedInt::operator!() const
{
return !_data;
}
bool ff::FixedInt::operator==(const ff::FixedInt& rhs) const
{
return _data == rhs._data;
}
bool ff::FixedInt::operator!=(const ff::FixedInt& rhs) const
{
return _data != rhs._data;
}
bool ff::FixedInt::operator<(const ff::FixedInt& rhs) const
{
return _data < rhs._data;
}
bool ff::FixedInt::operator>(const ff::FixedInt& rhs) const
{
return _data > rhs._data;
}
bool ff::FixedInt::operator<=(const ff::FixedInt& rhs) const
{
return _data <= rhs._data;
}
bool ff::FixedInt::operator>=(const ff::FixedInt& rhs) const
{
return _data >= rhs._data;
}
ff::FixedInt ff::FixedInt::operator-() const
{
return FromRaw(-_data);
}
ff::FixedInt ff::FixedInt::operator+() const
{
return FromRaw(+_data);
}
ff::FixedInt ff::FixedInt::operator++()
{
return *this = (*this + ff::FixedInt(1));
}
ff::FixedInt ff::FixedInt::operator++(int after)
{
ff::FixedInt orig = *this;
*this = (*this + ff::FixedInt(1));
return orig;
}
ff::FixedInt ff::FixedInt::operator--()
{
return *this = (*this - ff::FixedInt(1));
}
ff::FixedInt ff::FixedInt::operator--(int after)
{
ff::FixedInt orig = *this;
*this = (*this - ff::FixedInt(1));
return orig;
}
ff::FixedInt& ff::FixedInt::operator+=(const ff::FixedInt& rhs)
{
return *this = (*this + rhs);
}
ff::FixedInt& ff::FixedInt::operator-=(const ff::FixedInt& rhs)
{
return *this = (*this - rhs);
}
ff::FixedInt& ff::FixedInt::operator*=(const ff::FixedInt& rhs)
{
return *this = (*this * rhs);
}
ff::FixedInt& ff::FixedInt::operator/=(const ff::FixedInt& rhs)
{
return *this = (*this / rhs);
}
ff::FixedInt ff::FixedInt::operator+(const ff::FixedInt& rhs) const
{
return FromRaw(_data + rhs._data);
}
ff::FixedInt ff::FixedInt::operator-(const ff::FixedInt& rhs) const
{
return FromRaw(_data - rhs._data);
}
ff::FixedInt ff::FixedInt::operator*(const ff::FixedInt& rhs) const
{
return FromExpanded((GetExpanded() * rhs.GetExpanded()) >> FIXED_COUNT);
}
ff::FixedInt ff::FixedInt::operator/(const ff::FixedInt& rhs) const
{
return FromExpanded((GetExpanded() << FIXED_COUNT) / rhs.GetExpanded());
}
ff::FixedInt ff::FixedInt::operator%(const ff::FixedInt& rhs) const
{
return FromRaw(_data % rhs._data);
}
ff::FixedInt& ff::FixedInt::operator*=(int rhs)
{
return *this = (*this * rhs);
}
ff::FixedInt& ff::FixedInt::operator/=(int rhs)
{
return *this = (*this / rhs);
}
ff::FixedInt ff::FixedInt::operator*(int rhs) const
{
return FromRaw(_data * rhs);
}
ff::FixedInt ff::FixedInt::operator/(int rhs) const
{
return FromRaw(_data / rhs);
}
ff::FixedInt ff::FixedInt::abs() const
{
return FromRaw(std::abs(_data));
}
ff::FixedInt ff::FixedInt::ceil() const
{
return FromRaw((_data & HI_MASK) + ((_data & LO_MASK) != 0) * FIXED_MAX);
}
ff::FixedInt ff::FixedInt::floor() const
{
return FromRaw(_data & HI_MASK);
}
ff::FixedInt ff::FixedInt::trunc() const
{
return FromRaw((_data & HI_MASK) + (_data < 0) * ((_data & LO_MASK) != 0) * FIXED_MAX);
}
ff::FixedInt ff::FixedInt::copysign(ff::FixedInt sign) const
{
return sign._data >= 0 ? abs() : -abs();
}
void ff::FixedInt::swap(ff::FixedInt& rhs)
{
std::swap(_data, rhs._data);
}
ff::FixedInt ff::FixedInt::FromRaw(int data)
{
ff::FixedInt value;
value._data = data;
return value;
}
int ff::FixedInt::GetRaw() const
{
return _data;
}
ff::FixedInt ff::FixedInt::FromExpanded(int64_t data)
{
ff::FixedInt value;
value._data = (int)data;
return value;
}
int64_t ff::FixedInt::GetExpanded() const
{
return (int64_t)_data;
}
inline ff::FixedInt operator "" _f(unsigned long long val)
{
return ff::FixedInt(val);
}
inline ff::FixedInt operator "" _f(long double val)
{
return ff::FixedInt(val);
}
namespace std
{
inline ff::FixedInt abs(ff::FixedInt val)
{
return val.abs();
}
inline ff::FixedInt ceil(ff::FixedInt val)
{
return val.ceil();
}
inline ff::FixedInt floor(ff::FixedInt val)
{
return val.floor();
}
inline ff::FixedInt trunc(ff::FixedInt val)
{
return val.trunc();
}
inline void swap(ff::FixedInt& lhs, ff::FixedInt& rhs)
{
lhs.swap(rhs);
}
inline ff::FixedInt copysign(ff::FixedInt val, ff::FixedInt sign)
{
return val.copysign(sign);
}
inline ff::FixedInt sqrt(ff::FixedInt val)
{
return std::sqrt((float)val);
}
}
| true |
e153362150657331201c7d5466527b418f330e6e | C++ | dhk1349/C_plusplus-Programing-study | /Kaprekars_Constant.cpp | UHC | 2,107 | 3.625 | 4 | [] | no_license | #include<iostream>
#include<cmath>
using namespace std;
/*
*/
int kap(int n);
int lower(int n);
int higher(int n);
void main() {
while (true) {
int n;
cout << "Type any 4digit number: ";
cin >> n;
if (n==0) {
break;
}
cout << "Untill above number reaches Kaprekars Constant, " << kap(n) << "times of calculation is needed. " << endl;
}
}
int kap(int n) {
int hi, lo;
int number = n;
int iter = 0;
while (true) {
hi = higher(number);
lo = lower(number);
if (number== (hi-lo)) {
break;
}
number = (hi-lo);
iter += 1;
}
return iter;
}
int lower(int n) {
//ټڸ ex.15234
int a, b, c, d;
a = n % 10; //1 ڸ
b = ((n % 100) - a)/10; //10 ڸ
c = ((n % 1000) - a - b * 10)/100; //100 ڸ
d = ((n % 10000) - a - b * 10 - c * 100)/1000; //1000 ڸ
//Ʒ a,b,c,d 迭 .
// Ʈ ݺ ° ξ
//Ʈ ٷ ϱ .
int code = 0;
while (code == 0) {
int changed = 0;
if (a>b) {
int temp = b;
b = a;
a = temp;
changed += 1;
}
if (b>c) {
int temp = c;
c = b;
b = temp;
changed += 1;
}
if (c>d) {
int temp = d;
d = c;
c = temp;
changed += 1;
}
if (changed == 0) {
code = 1;
}
}
return a*1000+b*100+c*10+d;
}
int higher(int n) {
int a, b, c, d;
a = n % 10; //1 ڸ
b = ((n % 100) - a) / 10; //10 ڸ
c = ((n % 1000) - a - b * 10) / 100; //100 ڸ
d = ((n % 10000) - a - b * 10 - c * 100) / 1000; //1000 ڸ
int code = 0;
while (code == 0) {
int changed = 0;
if (a<b) {
int temp = b;
b = a;
a = temp;
changed += 1;
}
if (b<c) {
int temp = c;
c = b;
b = temp;
changed += 1;
}
if (c<d) {
int temp = d;
d = c;
c = temp;
changed += 1;
}
if (changed == 0) {
code = 1;
}
}
return a * 1000 + b * 100 + c * 10 + d * 1;
}
| true |
65be504b7f8e5544302e05c0133609f422232338 | C++ | alexandretannus/aula-ed1-2021-2 | /aula02-alocacao-dinamica/07-malloc_calloc.cpp | UTF-8 | 496 | 3.25 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
int main() {
char *p, *pc;
int np = 5;
p = (char *) malloc(np * sizeof(char));
pc = (char *) calloc(np, sizeof(char));
printf("\n --- Malloc \n\n");
for (int i=0; i<np; i++) {
printf("endereco p[%d] = %d\n", i, &p[i]);
printf("valor p[%d] = %c\n\n", i, p[i]);
}
printf("\n --- Calloc \n\n");
for (int i=0; i<np; i++) {
printf("endereco pc[%d] = %d\n", i, &pc[i]);
printf("valor pc[%d] = %c\n\n", i, pc[i]);
}
return 0;
}
| true |