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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
0cbfb02002df1b5f37da71e5a42841cae2f36426 | C++ | NathanBruce/nathanbruce-CSCI20-Fall2017 | /lab32/lab32.cpp | UTF-8 | 7,200 | 3.84375 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
/*
Nathan Bruce
10/12/2017
This program calculates how much a user owes for taxes (or refunds they are entitled to).
It does this by reducing the tax rate by personal exemption and marital status, and then running the remainder through the appropriate tax bracket.
The program outputs the user's name, their taxes owed/due, Total Adjusted Income.
*/
//Create a function that will calculate all the tax brackets for people who are single
double Single_Tax_Calc(double income) { //
double temp_calc = 0; // create a temp variable to calculate tax amount
double tax = 0; // finalized tax amount. This is what will return
if (income > 0 && income < 9326) { //first tax bracket.
tax = income * 0.10;
}
else if (income > 9325 && income <= 37950) { //second tax bracket.
temp_calc = income * 0.15;
tax = 932.50 + temp_calc;
}
else if (income > 37950 && income <= 91900) { //three tax bracket.
temp_calc = income * 0.25;
tax = 5226.25 + temp_calc;
}
else if (income > 91900 && income <= 191650) { //four tax bracket.
temp_calc = income * 0.28;
tax = 18713.75 + temp_calc;
}
else if (income > 191650 && income <= 416700) { //five tax bracket.
temp_calc = income * 0.33;
tax = 46643.75 + temp_calc;
}
else if (income >= 416700) { //six tax bracket.
temp_calc = income * 0.396;
tax = 120910.25 + temp_calc;
}
cout << "\nYour taxes are: $" << tax << endl; //return the tax amount, will depend on the user's bracket.
return tax; //sends the tax value back into the main code
};
//Create a function that will calculate all the tax brackets for people who are married
double Married_Tax_Calc(double income) { //first tax bracket.
double temp_calc = 0;
double tax = 0;
if (income >= 0 && income <= 18650) { //second tax bracket.
tax = income * 0.10;
}
else if (income >= 18650 && income <= 75900) { //third tax bracket.
temp_calc = income * 0.15;
tax = 1865 + temp_calc;
}
else if (income > 75900 && income <= 153100) { //fourth tax bracket.
temp_calc = income * 0.25;
tax = 10452.50 + temp_calc;
}
else if (income > 153100 && income <= 233350) { //fifth tax bracket.
temp_calc = income * 0.28;
tax = 29752.50 + temp_calc;
}
else if (income >= 233350 && income <= 416700) { //six tax bracket.
temp_calc = income * 0.33;
tax = 52222.50 + temp_calc;
}
else if (income >= 416700) { //seven tax bracket.
temp_calc = income * 0.396;
tax = 112728 + temp_calc;
}
cout << "\nBecause you are married, your Gross Adjusted Income is: $" //output to the user letting them know what their GAI is
<< income - tax << "\n" << endl; //subtract the users income by the tax amount (based on tax bracket)
return tax; //return the tax amount to the main code
};
//initialize all the variables
//they're all succintly named
main() {
string user_name;
double user_income = 0.0;
double income_tax = 0.0;
double after_tax = 0.0;
double taxes_withheld = 0.0;
int married_status = 0;
int final_tax = 0;
int personal_exemption = 4050;
int single_deduction = 6350;
int married_deduction = 12700;
cout << "What is your name? "; //ask the user for their name
getline(cin, user_name); //getline so the user can add their first and last names (or even a middle name if they want to get crazy with it)
cout << "\nEnter your income to calculate the taxes: "; //collect users income
cin >> user_income;
cout << "\nEnter withheld tax amount: "; //collect withheld tax amount
cin >> taxes_withheld;
cout << "\nAre you married? type '1' for yes or '2' for no. "; //ask user their married status (rude)
cin >> married_status;
switch (married_status) { //create a switch loop. This will calculate different equations based on the user's marital status
case 1: //first case
user_income = user_income - ((personal_exemption * 2) + married_deduction); //determines the user income, deduces the two personal exemptions and marriage deduction before calculating tax
final_tax = Married_Tax_Calc(user_income); //run the married tax function
final_tax = final_tax - taxes_withheld; //subtract the taxes withheld
if (final_tax > 0) { //if the user is over 0, user owes money
cout << user_name <<"\n, you owe: $" << final_tax; //tell them how much they owe
}
else { //if not, must mean they get money back
final_tax = final_tax * -1; //turn the negative amount into positive
cout << user_name<< ": Congrats! Your tax refund will be: $" << final_tax; //tell user refund amount
}
break; //break loop if criteria is met
case 2:
user_income = user_income - (personal_exemption + single_deduction); //Same thing as before, this time with single status. Reduce by 1 personal exemption and single deduction
final_tax = Single_Tax_Calc(user_income); //calculate single tax
final_tax = final_tax - taxes_withheld; //reduce taxes withheld
if (final_tax > 0) { // over 0? you owe money
cout << user_name << ", you owe: $" << final_tax;
}
else {
final_tax = final_tax * -1; //under 0? you get money$
cout << user_name << "\n: Congrats! your tax refund will be: $" << final_tax;
}
break; //break if condition if fulfilled
default: //if neither? say this.
cout << endl << "Dontcha listen..?"; // snarky message? Check!
}
return 0;
} | true |
a27efb00d663c2c9f89bce07c6c46724271c2cb6 | C++ | In2ne1/Mine | /C++/模拟实现string类函数/main.cpp | UTF-8 | 598 | 2.9375 | 3 | [] | no_license | int main()
{
String s1("aaaaa");
cout << s1 << endl;
cout << s1.append(4, 'n') << endl;
cout << s1.append("bbb") << endl;
cout << s1.find('n') << endl;
String s2("Thanks for your help!");
cout << s2 << endl;
s2.insert("useful ", 15); //const char* str, pos
s2.insert("useful ", 7, 15); //const char* str, 前n, pos
cout << s2 << endl;
String s4("aaaabbbbccccdddd");
cout << s4 << endl;
cout << s4.erase(4, 4) << endl; //len, pos
cout << s4.erase(2) << endl; //pos
String s5("s'tahw pu ew 1en2");
cout << s5.reverse(s5) << endl;
system("pause");
return 0;
}
| true |
1cb34626d2e1568119ce8d1495c0de435270b1ef | C++ | TissueFluid/Algorithm | /LintCode/Route Between Two Nodes in Graph.cc | UTF-8 | 1,229 | 3.609375 | 4 | [] | no_license | // Route Between Two Nodes in Graph
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
using namespace std;
struct DirectedGraphNode {
int label;
vector<DirectedGraphNode *> neighbors;
DirectedGraphNode(int x) : label(x) {};
};
class Solution {
public:
/**
* @param graph: A list of Directed graph node
* @param s: the starting Directed graph node
* @param t: the terminal Directed graph node
* @return: a boolean value
*/
bool hasRoute(vector<DirectedGraphNode *> graph,
DirectedGraphNode* s, DirectedGraphNode* t) {
queue<DirectedGraphNode *> q;
unordered_map<DirectedGraphNode *, bool> visited;
for (const auto &item : graph) {
visited[item] = false;
}
q.push(s);
while (!q.empty()) {
auto front = q.front();
q.pop();
if (front->label == t->label) {
return true;
}
visited[front] = true;
for (const auto &item : front->neighbors) {
if (!visited[item]) {
q.push(item);
}
}
}
return false;
}
};
| true |
e520995844e4aa1a10749e8807d2e74ed5e01618 | C++ | sc-0571/cppPoc | /cppPoc/PartitionEqualSubset.cpp | UTF-8 | 1,924 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string.h>
using namespace std;
bool canPartition(vector<int>& nums) {
int half = 0;
for (int i=0; i< nums.size(); i++) half += nums[i];
if (half %2 != 0) return false;
half /=2;
int n = nums.size();
int MAX = n * 100;
int dp[n+1][MAX+1];
for(int i=0; i<=n; i++)
for(int j=0; j<=MAX; j++)
dp[i][j] = 0;
for (int i=1; i<= n; i++)
for(int j=nums[i-1]; j<= MAX; j++) {
dp[i][j] = max(dp[i-1][j], dp[i-1][j-nums[i-1]] + nums[i-1]);
}
for (int i=0; i<= n; i++) {
if (dp[i][half] == half) {
return true;
}
}
return false;
}
bool canPartitionKSubsets(vector<int>& nums, int k) {
int half = 0;
for (int i=0; i< nums.size(); i++) half += nums[i];
if (half %k != 0) return false;
half /=k;
int n = nums.size();
int MAX = 10000;
int dp[n+1][MAX+1];
for(int i=0; i<=n; i++)
for(int j=0; j<=MAX; j++)
dp[i][j] = 0;
for (int i=1; i<= n; i++)
for(int j=nums[i-1]; j<= MAX; j++) {
dp[i][j] = max(dp[i-1][j], dp[i-1][j-nums[i-1]] + nums[i-1]);
}
/*int r[10];
memset(r, sizeof(r), 0);
for(int j=1; j<= k; j++ )
for (int i=1; i<= n; i++) {
if (dp[i][half * k] == half*k) {
r[k-1]= 1;
}
}
for(int j=1; j<=k; j++)
if (r[k-1] == 0) return false;*/
return true;
}
int main() {
vector<int> nums = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
//vector<int> nums = {4,3,2,3,5,2,1};
string ret = canPartitionKSubsets(nums, 1)?"true":"false";
cout << "ret=" << ret << endl;
return 0;
}
| true |
2936d494367cdc24684a4e12aa8f8e51aca19b5b | C++ | tcagame/Attraction2016 | /Solution/Client/BulletImpact.cpp | UTF-8 | 1,125 | 2.890625 | 3 | [] | no_license | #include "BulletImpact.h"
#include "Effect.h"
const int POWER = 100;
const int WAIT_TIME = 8;
const int ANIMATION_TIME = 10;
const double RANGE = 3 * Bullet::BULLET_SCALE;
const double EFFECT_SCALE = 0.5 * Bullet::BULLET_SCALE;
BulletImpact::BulletImpact( const Vector& pos, const Vector& dir, int power )
: Bullet( Bullet::TYPE_IMPACT )
, _count( 0 ) {
_power = POWER * power;
_pos = pos;
_dir = dir;
Effect effect;
_effect_handle = effect.setEffect( Effect::EFFECT_PLAYER_ATTACK_IMPACT );
Vector effect_pos = pos + Vector( 0, 0, -0.2 ) * Bullet::BULLET_SCALE + _dir * 0.5 * Bullet::BULLET_SCALE;
effect.drawEffect( _effect_handle, Vector( EFFECT_SCALE, EFFECT_SCALE, EFFECT_SCALE ), effect_pos, dir );
}
BulletImpact::~BulletImpact( ) {
}
double BulletImpact::getLength( ) const {
return RANGE * ( _count - WAIT_TIME ) / ANIMATION_TIME;
}
bool BulletImpact::update( ) {
_count++;
if ( _count < WAIT_TIME ) {
return true;
}
if ( _count >= WAIT_TIME + ANIMATION_TIME ) {
return false;
}
double range = getLength( );
Vector pos = getPos( ) + _dir * range;
attackEnemy( pos, _power );
return true;
}
| true |
034a1af27eb9774430fd36628d0a014037dae7e2 | C++ | Asif-Al-Rafi/Project1 | /main.cpp | UTF-8 | 742 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include "SelectionSortUsArray.h"
#include "InsertionSortUsArray.h"
#include "MergeSortUsArray.h"
#include "BubbleSortUsArray.h"
using namespace std;
int main()
{
SelectionSort asif;
int arr[] = {10,33,27,14,35,19,48,44};
int size = 8;
asif.SelectionSorter(arr,size);
InsertionSort rafi;
int arr0[] = {10,33,27,14,35,19,48,44};
rafi.InsertionSorter(arr0,size);
MergeSort rauf;
int arr1[] = {10,33,27,14,35,19,48,44};
std::cout<<"\nPrint Merge sort : "<<std::endl;
rauf.MergeSorter(arr1,size);
BubbleSort asik;
int arr2[] = {10,33,27,14,35,19,48,44};
std::cout<<"\nPrint Bubble sort : "<<std::endl;
asik.BubbleSorter(arr2,size);
return 0;
}
| true |
280a26b1c4093c9bc1b415fc2386ccc208430451 | C++ | naknaknak/3D_Game_Portfolio | /Old_Version/map_8.3.0(피격추가)/Base_3D/Quest.h | UTF-8 | 603 | 2.609375 | 3 | [] | no_license | #pragma once
#include "image.h"
#include "TextDraw.h"
#include "Button.h"
enum QuestType
{
QUEST_START = 0,
QUEST_MIDDLE,
QUEST_END,
QUEST_NUM
};
class Quest
{
public:
private:
QuestType type = QUEST_START;
image* imageBack = nullptr;
TextDraw text_title;
TextDraw text_body;
Button buttonOk;
TextDraw text_buttonOK;
bool m_bShow = false;
public:
Quest( );
~Quest( );
void Initialize( );
void Destroy( );
void Update( );
void Render( );
void SetQuest(int questType);
void SelectOK(bool& ok) { buttonOk.ClickAction(ok); }
void ShowQuest(bool show) { m_bShow = show; }
};
| true |
b170cf59d028f4c3466feae1b79505383251071f | C++ | wayfinder/Wayfinder-Server | /Server/Modules/RouteModule/include/RedBlackNode.h | UTF-8 | 3,278 | 2.640625 | 3 | [] | no_license | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef REDBLACKNODE_H
#define REDBLACKNODE_H
#include "config.h"
#include "RoutingNode.h"
enum colorType { RED, BLACK };
/**
* Describes a node in the Red-Black Tree ADT.
* A special node is nullSentinel that replaces NULL for each tree.
*
*/
class RedBlackNode {
friend class RedBlackTree;
public:
/**
* Constructor for the RedBlackNode.
* @param node The node to be inserted.
*/
RedBlackNode(RoutingMap* theMap, RoutingNode *node);
/**
* Another constructor for the node.
* Only used to construct nullSentinel.
*/
RedBlackNode();
/**
* Sets the parent and children pointers of the current node
* to nullSentinel.
* @param nullSentinel The nullSentinel in the tree.
*/
inline void setNullSentinel(RedBlackNode* nullSentinel);
/**
* Dumps the itemID of the node to cout. Both hex and dec.
*/
inline void dump();
private:
/**
* The color of the node.
*/
colorType color;
/**
* The key of the node.
*/
uint32 key;
/**
* The left child of the node.
*/
RedBlackNode *leftChild;
/**
* The right child of the node.
*/
RedBlackNode *rightChild;
/**
* The parent of the node.
*/
RedBlackNode* parent;
/**
* The node in the map.
*/
RoutingNode* routingNode;
}; // RedBlackNode
/////////////////////////////////////////////////////////////
// Inline functions
/////////////////////////////////////////////////////////////
void RedBlackNode::setNullSentinel(RedBlackNode* nullSentinel)
{
leftChild = rightChild = parent = nullSentinel;
}
void RedBlackNode::dump()
{
if (routingNode != NULL)
cout << "ID " << hex << routingNode->getItemID() << dec << "("
<< REMOVE_UINT32_MSB( routingNode->getItemID() ) << ")" << endl;
}
#endif
| true |
c4f44ff2b1c407226c8ca088211184df7a3ed4fe | C++ | Stephen1993/ACM-code | /hdu1333之求素因子.cpp | GB18030 | 1,092 | 3 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
#include<map>
#include<iomanip>
#define INF 99999999
using namespace std;
const int MAX=20;
int prime_factor[MAX],factor_num[MAX];
bool flag=true;
int digit(int n){
int num=0;
while(n){
num+=n%10;
n=n/10;
}
return num;
}
int factor(int n){
int k=0;
for(int i=2;i*i<=n;++i){//.
if(n%i == 0){
int num=0;
while(!(n%i)){
n=n/i;
num++;
}
prime_factor[k]=i;//¼.
factor_num[k++]=num;//¼ӦӸ.
}
}
if(n!=1){
prime_factor[k]=n;
factor_num[k++]=1;
}
if(prime_factor[0] == n){flag=false;return 0;}//ʾ.
int sum=0;
for(int i=0;i<k;++i){//ӵλ.
sum+=factor_num[i]*digit(prime_factor[i]);
}
return sum;
}
int main(){
int n;
while(cin>>n,n){
while(n++){
flag=true;
if(flag && factor(n) == digit(n)){
cout<<n<<endl;
break;
}
}
}
return 0;
} | true |
3e9753592eeb746a410e5140168b64b28a2bd571 | C++ | Borysiakk/BatGUI | /Theme.cpp | UTF-8 | 2,200 | 2.59375 | 3 | [] | no_license | //
// Created by Borysiak on 28.07.2019.
//
#include "Theme.hpp"
#include "Widget.hpp"
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
namespace pt = boost::property_tree;
std::vector<std::string> Theme::WidgetNames =
{
{"Button"},
};
std::map<std::string,WidgetType> Theme::NameWidgetType =
{
{"Button",WidgetType::Button},
};
Theme::Theme(std::string fileName):fileName(fileName)
{
load();
}
WidgetConverter Theme::Create(WidgetType type)
{
Widget * object = nullptr;
std::array<Resource*,2> stock;
stock[0] = resources[WidgetType::Widget].get();
switch(type)
{
case WidgetType::Button:
{
object = new Button();
stock[1] = resources[WidgetType::Button].get();
object->loadResourceData(stock);
break;
}
}
return WidgetConverter(object);
}
void Theme::load()
{
pt::ptree root;
std::unique_ptr<Resource> resource;
pt::read_json(fileName,root);
std::string fontName;
auto && configure = root.get_child("ConfigureGlobal");
for(auto item :configure)
{
if(item.first == "FontGlobalName")
{
resource = std::make_unique<Resource>();
resource->addFontName(item.second.data());
resources[WidgetType::Widget] = std::move(resource);
}
}
for(auto && widgetName : WidgetNames )
{
resource = std::make_unique<Resource>();
for (auto && type :root.get_child(widgetName))
{
if (type.first == "Texture")
{
for (auto && texture : type.second)
{
std::string name = texture.first;
std::string part = texture.second.get<std::string>("Part");
std::string middle = texture.second.get<std::string>("Middle");
resource->addTextureData(name, part, middle);
}
}
else if (type.first == "Color")
{
//....
}
}
resources[NameWidgetType[widgetName]] = std::move(resource);
}
}
| true |
a4f30ea5bddc54564541a892d8b32cb29cb44639 | C++ | ivannatadash/Lab_OOP_01 | /Lab_OOP_iterator/Lab_OOP_iterator/Student.cpp | UTF-8 | 341 | 3.28125 | 3 | [] | no_license | #include "Student.h"
Student::Student(string l, string i)
{
lastname_name = l;
institute = i;
}
string Student::getLastname_name()
{
return lastname_name;
}
ostream& operator<< (ostream& ostr, const Student& st)
{
ostr << "Student: " + st.lastname_name + "\nInstitute: " + st.institute;
return ostr;
} | true |
da7b81c5d4f0b0dadb0f9323a2625b5b61c438d0 | C++ | coolguycoolstory/RaveTowers | /RaveTowerMaster_ESP8266_10APR2019.ino | UTF-8 | 14,215 | 2.515625 | 3 | [] | no_license | /*
This code and the overall design drew heavy inspiration from Hans's "MUSIC VISUALIZING Floor Lamps".
His code can be found here: https://github.com/hansjny/Natural-Nerd/tree/master/SoundReactive2.
Other inspiration came from haag991's code, found here: https://github.com/haag991/Spectrum_Visualizer
This is the RaveTowerMaster code. An audio signal is converted into multiple analog voltage values using an Adafruit Spectrum Shield,
and this data is sent along with commands to a set number of RaveTowerSlave units via a UDP Broadcast over WiFi.
Commands are toggled using push buttons, and current selections and system status are shown on a 128x64 OLED screen .
This code was written for the ESP8266 on the Arduino IDE; Using an ESP32 requires a small re-write to WiFi portions and pin assignments
shot, but I could not resolve an unacceptable delay between the source audio and the Slave unit LED displays. Resolving this
issue could mean more precise control of patterns and access to both audio channels.
The general flow of this code is:
__________
Setup
Wait for Set # of Clients to Connect
__________
Periodically Check if Clients are Connected.
If Clients Lost, Stop and Wait
__________
Read Analog Signals from Spectrum Shield
Check for Inputs from Controls
Send Data to Clients
__________
Update Display with Current Status when waiting or if inputs received.
*/
//USER INPUTS HERE///////////////
#define NumClients 4 //This is the number of RaveTowersSlaves. This must be correct.
//WI-FI SETUP/////////////////////
#include <ESP8266WiFi.h> // Include the Wi-Fi library
#include <WiFiUDP.h>
const char *ssid = "RaveTowerTime"; // The SSID (name) of the Wi-Fi network you want to connect to
const char *password = "6026971660"; // The password of the Wi-Fi network (blank between quotes if it's open).
WiFiUDP UDP; // this creates an instance of the WiFIUDP class to send and receive. UDP is "User Datagram Protocol", which is low latency and tolerant of losses.
//However: this type of connection DEPENDS on the destination (i.e. IP address) being correct, or it won't work.
bool Pings[NumClients]; //This is an array of true/falses for checking if clients are connected.
const uint8_t CheckTime = 5000; //Interval to check to see if a ping was received.
uint32_t LastReceived;
struct ClientPings {
uint8_t ClientID;
};
struct ClientPings Ping;
//PIN ASSIGNMENTS////////////////////
const uint8_t strobe = D3; //4 on the Spectrum Shield
const uint8_t reset = D4; //5 on the Spectrum Shield
const uint8_t audio = A0; //The ESP8266's only Analog Input. This means you only get the left or the right channel of audio.
const uint8_t ModePin = D5;
const uint8_t FuncPin = D0;
const uint8_t ColorPin = D6;
///BUTTON VARIABLES//////////////
uint32_t ModeLastChecked;
uint32_t ModeChecked;
bool ModeClicked = false;
bool ModeTrigger;
const uint8_t NumModes = 6; //THIS IS PLUGGED IN DOWN BELOW, and must be correct.
uint8_t CurrentMode;
uint32_t FuncLastChecked;
uint32_t FuncChecked;
bool FuncClicked = false;
bool FuncTrigger;
const uint8_t NumFuncs = 8; //THIS IS PLUGGED IN DOWN BELOW, and must be correct.
uint8_t CurrentFunc;
uint32_t ColorLastChecked;
uint32_t ColorChecked;
bool ColorClicked = false;
bool ColorTrigger;
const uint8_t NumColors = 4; //THIS IS PLUGGED IN DOWN BELOW, and must be correct.
uint8_t CurrentColor;
const uint8_t DoubleTapDelay = 20;
bool DoubleTapped;
//OLED SCREEN////////////////////////
#include <Wire.h>
#include <Adafruit_GFX.h> //Include the library for the OLED screen
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
//on ESP8266s: SCL is D1, SDA is D2
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
uint8_t ConnectionStatus;
const char* ConnectionStates[] = {"Waiting...","Sending!"};
const char* ModeNames1[] = {"VU Meter","Flames","Confetti","Strobe","Strobe","Lamp"}; //the length of these arrays must match the number of modes.
const char* ModeNames2[] = {"(Mirror)","(Mirror)"," ","(Small)","(Full)"," "};
const char* FuncNames1[] = {"63 Hz","160 Hz","400 Hz","1 kHz","2.5 kHz","6.25 kHz","16 kHz","Random"}; //the length of these arrays must match the number of functions.
const char* FuncNames2[] = {"(Bass)","(Bass)","(Mids)","(Mids)","(Mids)","(Highs)","(Highs)"," "};
const char* StrobeSpeedNames[] = {"60ms","70ms","80ms","90ms","100ms","110ms","120ms","130ms"};
const char* ColorNames1[] = {"Normal","Vaporwave","Outrun","Sunset"}; //the length of these arrays must match the number of colors.
const char* ColorNames2[] = {" "," "," "," "};
const char* FlameNames1[] = {"Normal","Icy Hot","Pink","Green"};
const char* FlameNames2[] = {" "," ","Flash","Magic"};
//////////////////////////////////////////////////////
uint8_t freq[10]; //This array is populated with the audio data from the Spectrum Shield, and the three commands. This is what is sent over WiFi.
uint8_t i;
//////////////////////////////////////////////////////
void setup() {
delay(500);
display.begin(SSD1306_SWITCHCAPVCC, 0X3C); //initialize the OLED screen
display.clearDisplay();
display.setTextSize(3);
display.setTextColor(WHITE);
display.setCursor(23, 7);
display.println("LET'S");
display.setCursor(30, 32);
display.println("RAVE");
display.display();
delay(2000);
display.clearDisplay();
pinMode(audio, INPUT);
pinMode(ModePin, INPUT);
pinMode(FuncPin, INPUT);
pinMode(ColorPin, INPUT);
pinMode(strobe, OUTPUT);
pinMode(reset, OUTPUT);
digitalWrite(reset, LOW);
digitalWrite(strobe, HIGH);
WiFi.persistent(false);
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid, password); //Start the access point.
UDP.begin(123); //this instructs the ESP to start listening for UDP packets on port 123.
//I include the following lines after every clearDisplay//
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0, 0);
display.println("Access Point");
display.print("\"");
display.print(ssid);
display.println("\"");
display.println("started");
display.println(" ");
display.println("IP Address:");
display.println(WiFi.softAPIP());
display.display();
display.clearDisplay();
delay(2000);
UpdateDisplay();
ResetPings();
WaitForClients(); //This will force the program to wait for connections instead of screaming UDP Packets into the void.
LastReceived = millis();
}
//WI-FI MANAGEMENT///////////////////////////////////////////////////
void ResetPings() { //Resets the pings so the program has to receive new pings to continue.
for (int i = 0; i < NumClients; i++) {
Pings[i] = false;
}
}
void WaitForClients() {
while(true) { //This infinite loop starts you waiting for packets, then starts you waiting for all clients. Could be a long time if Wifi is bad.
ReadPings();
if (CheckPings()) {
ConnectionStatus = 1;
UpdateDisplay();
return; //this allows you to escape the infinite loop if CheckPings() returns TRUE.
}
delay(CheckTime);
ResetPings(); //This forces all clients to try again if one client is taking too long.
}
}
void ReadPings() {
while(true) {
int packetSize = UDP.parsePacket();
if (!packetSize) {
break;
}
UDP.read((char*)&Ping, sizeof(struct ClientPings));
if (Ping.ClientID > NumClients) {
display.println("Error: invalid client_id received");
display.display();
continue;
}
Pings[Ping.ClientID - 1] = true;
}
}
bool CheckPings() { //This returns a true/false result for the "Wait for Clients" loop.
for (int i = 0; i < NumClients; i++) {
if (!Pings[i]) {
return false;
}
}
ResetPings();
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////
void loop() {
ReadSpectrum(); //Get audio data.
ReadControls(); //If buttons have been pressed, update commands.
SendData(); //Send data to clients.
if (millis() - LastReceived > CheckTime) { //Every check interval, Read Pings.
ReadPings();
if(!CheckPings()) { //If someone drops out, stop and wait.
ConnectionStatus = 0;
UpdateDisplay();
WaitForClients();
}
LastReceived = millis();
}
}
///////////////////////////////////////////////////////////////////////////////////////
void ReadSpectrum() {
digitalWrite(reset, HIGH);
digitalWrite(reset, LOW);
for(i=0; i <7; i++)
{
digitalWrite(strobe, LOW); //
delayMicroseconds(30); //
freq[i] = map(analogRead(audio),0,1023,0,255); //This populates the freq array with the 7 frequencies read by the Spectrum Shield.
digitalWrite(strobe, HIGH);
}
}
///////////////////////////////////////////////////////////////////////////////////////
void ReadControls() {
//////MODE PIN FIRST: freq[7]
i = digitalRead(ModePin);
if (i == 0) {
if (millis() - ModeChecked < DoubleTapDelay && ModeClicked == false ) {
DoubleTapped = true;
}
ModeTrigger = true;
ModeClicked = true;
ModeChecked = millis();
}
else if (i == 1) {
if (millis() - ModeChecked > DoubleTapDelay && ModeTrigger) {
if (!DoubleTapped) {
CurrentMode++; //Here the 7th byte in the freq array is the Mode. This will talk to the "switch" function on the receiving end.
CurrentColor = 0; //Resets the color to "normal" when a new mode is selected.
if (CurrentMode > NumModes-1) {
CurrentMode = 0; //loop around to 0 if you go too high.
}
UpdateDisplay();
freq[7] = CurrentMode;
freq[9] = CurrentColor;
}
ModeTrigger = false;
DoubleTapped = false;
}
ModeClicked = false;
}
/////////FUNCTION PIN SECOND: freq[8]
i = digitalRead(FuncPin);
if (i == 0) {
if (millis() - FuncChecked < DoubleTapDelay && FuncClicked == false ) {
DoubleTapped = true;
}
FuncTrigger = true;
FuncClicked = true;
FuncChecked = millis();
}
else if (i == 1) {
if (millis() - FuncChecked > DoubleTapDelay && FuncTrigger) {
if (!DoubleTapped) {
CurrentFunc++; //Here the 8th byte in the freq array is the Function. This will select the frequency band, or the ms delay for the strobes.
if (CurrentFunc > NumFuncs-1) {
CurrentFunc = 0; //loop around to 0 if you go too high.
}
UpdateDisplay();
freq[8] = CurrentFunc;
}
FuncTrigger = false;
DoubleTapped = false;
}
FuncClicked = false;
}
/////////COLOR PIN THIRD: freq[9]
i = digitalRead(ColorPin);
if (i == 0) {
if (millis() - ColorChecked < DoubleTapDelay && ColorClicked == false ) {
DoubleTapped = true;
}
ColorTrigger = true;
ColorClicked = true;
ColorChecked = millis();
}
else if (i == 1) {
if (millis() - ColorChecked > DoubleTapDelay && ColorTrigger) {
if (!DoubleTapped) {
CurrentColor++; //Here the 9th byte in the freq array is the Color. This toggles colors in different patterns.
if (CurrentColor > NumColors-1) {
CurrentColor = 0; //loop around to 0 if you go too high.
}
UpdateDisplay();
freq[9] = CurrentColor;
}
ColorTrigger = false;
DoubleTapped = false;
}
ColorClicked = false;
}
}
void SendData() {
for (i = 0; i<NumClients ; i++) {
IPAddress ip(192,168,4,2+i); //this identifies which IP address you're sending this packet to. All new connections to an access point connect sequentially.
UDP.beginPacket(ip, 124); //this targets the IP Address, and the port.
UDP.write((char*)&freq,sizeof(freq)); //the first item is what is sent (buffer), and the second item is the size of the packet
UDP.endPacket();
delayMicroseconds(1000/NumClients);
}
}
//UPDATE DISPLAY//
void UpdateDisplay() { //This should only update when a button is pressed, or connection is lost.
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0, 12);
display.setTextSize(2);
display.println("Mode:");
display.println("Freq:");
display.println("Color:");
display.setCursor(60, 11);
display.setTextSize(1);
display.println(ModeNames1[CurrentMode]);
display.setCursor(60, 20);
display.println(ModeNames2[CurrentMode]);
if(CurrentMode == 3 || CurrentMode == 5) { //These if and elses show N/A if speed doesn't matter (it technically does on Mode 3, but it's difficult to distinguish).
display.setCursor(60, 28);
display.println(" N/A ");
display.setCursor(60, 36);
display.println(' ');
}
else if (CurrentMode == 4) { //On full strobe, we have certain ms delays, so show those instead of the audio frequency.
display.setCursor(60, 28);
display.println(StrobeSpeedNames[CurrentFunc]);
display.setCursor(60, 36);
display.println(' ');
}
else {
display.setCursor(60, 28);
display.println(FuncNames1[CurrentFunc]);
display.setCursor(60, 36);
display.println(FuncNames2[CurrentFunc]);
}
if(CurrentMode == 1) {
display.setCursor(70, 44);
display.println(FlameNames1[0]);
display.setCursor(70, 52);
display.println(FlameNames2[0]);
}
else {
display.setCursor(70, 44);
display.println(ColorNames1[CurrentColor]);
display.setCursor(70, 52);
display.println(ColorNames2[CurrentColor]);
}
display.setCursor(0, 0);
display.print(ConnectionStates[ConnectionStatus]);
display.setCursor(70, 0);
display.print("Towers: ");
display.print(NumClients);
display.display();
}
| true |
8c322e3e103726d53c064ea21d5383a78dca457f | C++ | netvipec/AoC2018 | /C++/Day17/day17p1.cpp | UTF-8 | 9,233 | 3.1875 | 3 | [] | no_license | #include <bits/stdc++.h>
enum class Direction { Down, Up };
struct pos {
int x;
int y;
Direction d;
pos(int xx, int yy, Direction dd) : x(xx), y(yy), d(dd) {}
bool operator==(pos const& other) const { return std::tie(y, x, d) == std::tie(other.y, other.x, other.d); }
bool operator<(pos const& other) const { return std::tie(y, x, d) < std::tie(other.y, other.x, other.d); }
friend std::ostream& operator<<(std::ostream& os, pos const& p);
};
std::ostream& operator<<(std::ostream& os, pos const& p) {
os << p.x << "," << p.y << "," << (p.d == Direction::Down ? "Down" : "Up");
return os;
}
struct line {
char hv;
int hv_num;
char hv_range;
int hv_start;
int hv_end;
line(char hv, int hv_num, char hv_range, int hv_start, int hv_end)
: hv(hv), hv_num(hv_num), hv_range(hv_range), hv_start(hv_start), hv_end(hv_end) {}
friend std::ostream& operator<<(std::ostream& os, line const& l);
};
std::ostream& operator<<(std::ostream& os, line const& l) {
os << l.hv << "=" << l.hv_num << ", " << l.hv_range << "=" << l.hv_start << ".." << l.hv_end;
return os;
}
typedef std::vector<char> vec_char;
typedef std::vector<vec_char> vec_vec_char;
typedef std::vector<line> vec_input;
// trim from start (in place)
static inline void ltrim(std::string& s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { return !std::isspace(ch); }));
}
// trim from end (in place)
static inline void rtrim(std::string& s) {
s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return !std::isspace(ch); }).base(), s.end());
}
// trim from both ends (in place)
static inline void trim(std::string& s) {
ltrim(s);
rtrim(s);
}
static std::vector<std::string> split(std::string const& s, char delim) {
std::stringstream ss(s);
std::string item;
std::vector<std::string> elems;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
vec_input read_input(std::string const& file_path) {
vec_input input_values;
std::ifstream infile(file_path);
std::string line;
while (std::getline(infile, line)) {
// y=1388, x=546..564
// x=532, y=716..727
auto const parts = split(line, ',');
assert(parts.size() == 2);
auto const fnum_str = parts[0].substr(2);
auto const fnum = std::atoi(fnum_str.c_str());
auto idx = parts[1].find("..");
assert(idx != std::string::npos);
auto const snum_str0 = parts[1].substr(3, idx - 3);
auto const snum0 = std::atoi(snum_str0.c_str());
auto const snum_str1 = parts[1].substr(idx + 2);
auto const snum1 = std::atoi(snum_str1.c_str());
input_values.emplace_back(parts[0][0], fnum, parts[1][1], snum0, snum1);
// std::cout << input_values.back() << std::endl;
}
return input_values;
}
std::tuple<int, int, int, int> get_limits(vec_input const& input_values) {
int min_x = std::numeric_limits<int>::max();
int min_y = std::numeric_limits<int>::max();
int max_x = std::numeric_limits<int>::min();
int max_y = std::numeric_limits<int>::min();
std::for_each(std::cbegin(input_values), std::cend(input_values), [&](line const& l) {
if (l.hv == 'x') {
min_x = std::min(min_x, l.hv_num);
max_x = std::max(max_x, l.hv_num);
} else {
min_y = std::min(min_y, l.hv_num);
max_y = std::max(max_y, l.hv_num);
}
if (l.hv_range == 'x') {
min_x = std::min(min_x, l.hv_start);
max_x = std::max(max_x, l.hv_end);
} else {
min_y = std::min(min_y, l.hv_start);
max_y = std::max(max_y, l.hv_end);
}
});
--min_x;
++max_x;
return std::make_tuple(min_x, max_x, min_y, max_y);
}
void print_map(vec_vec_char const& map) {
std::for_each(std::cbegin(map), std::cend(map), [](vec_char const& row) {
std::for_each(std::cbegin(row), std::cend(row), [](char const& cell) { std::cout << cell; });
std::cout << std::endl;
});
std::cout << std::endl;
}
vec_vec_char get_map(vec_input const& input_values) {
auto [min_x, max_x, min_y, max_y] = get_limits(input_values);
vec_vec_char map(max_y + 1, vec_char(max_x - min_x + 1, '.'));
std::for_each(std::cbegin(input_values), std::cend(input_values), [=, &map](line const& l) {
if (l.hv == 'x') {
auto const x = l.hv_num - min_x;
auto const s_y = l.hv_start;
auto const e_y = l.hv_end + 1;
std::for_each(std::begin(map) + s_y, std::begin(map) + e_y, [=](vec_char& row) { row[x] = '#'; });
} else {
auto const y = l.hv_num;
auto const s_x = l.hv_start - min_x;
auto const e_x = l.hv_end - min_x + 1;
std::for_each(std::begin(map[y]) + s_x, std::begin(map[y]) + e_x, [=](char& cell) { cell = '#'; });
}
});
map[0][500 - min_x] = '+';
// std::cout << "X: " << min_x << " -> " << max_x << std::endl;
// std::cout << "Y: " << min_y << " -> " << max_y << std::endl;
// print_map(map);
std::set<pos> processed;
std::vector<pos> end_positions{pos{500 - min_x, 0, Direction::Down}};
std::vector<pos> new_end_positions;
auto it = end_positions.cend();
for (int counter = 0;; ++counter) {
std::for_each(std::cbegin(end_positions), it, [&](auto const& pp) {
auto p = pp;
for (;;) {
auto const res = processed.insert(p);
if (!res.second) {
return;
}
if (p.d == Direction::Down) {
if (p.y + 1 == static_cast<int>(map.size())) {
return;
}
if (map[p.y + 1][p.x] == '.' || map[p.y + 1][p.x] == '|') {
map[p.y + 1][p.x] = '|';
new_end_positions.emplace_back(p.x, p.y + 1, p.d);
return;
} else {
p.d = Direction::Up;
continue;
}
} else {
int start = p.x;
while (start > 0 && map[p.y][start - 1] != '#' && map[p.y + 1][start] != '.') {
--start;
}
int end = p.x;
while (end < max_x - min_x && map[p.y][end + 1] != '#' && map[p.y + 1][end] != '.') {
++end;
}
if (map[p.y][start - 1] == '#' && map[p.y][end + 1] == '#') {
std::fill(std::begin(map[p.y]) + start, std::begin(map[p.y]) + end + 1, '~');
new_end_positions.emplace_back(p.x, p.y - 1, p.d);
return;
} else {
std::fill(std::begin(map[p.y]) + start, std::begin(map[p.y]) + end + 1, '|');
if (map[p.y][start - 1] != '#') {
new_end_positions.emplace_back(start, p.y, Direction::Down);
}
if (map[p.y][end + 1] != '#') {
new_end_positions.emplace_back(end, p.y, Direction::Down);
}
return;
}
}
}
});
new_end_positions.insert(new_end_positions.end(), it, end_positions.cend());
if (new_end_positions.size() == 0) {
break;
}
std::swap(new_end_positions, end_positions);
new_end_positions.clear();
std::sort(std::begin(end_positions), std::end(end_positions));
end_positions.erase(std::unique(std::begin(end_positions), std::end(end_positions)), std::end(end_positions));
it = std::find_if(std::cbegin(end_positions), std::cend(end_positions),
[&](auto const& elem) { return elem.y != end_positions.front().y; });
}
return map;
}
void part1(vec_input const& input_values) {
auto [min_x, max_x, min_y, max_y] = get_limits(input_values);
auto const map = get_map(input_values);
// print_map(map);
// std::cout << std::endl;
int sum = std::accumulate(std::cbegin(map) + min_y, std::cend(map), 0, [](auto const& base, auto const& row) {
return base + std::count_if(std::cbegin(row), std::cend(row), [](char elem){
return elem == '|' || elem == '~';
});
});
std::cout << "Part1: " << sum << std::endl;
}
void part2(vec_input const& input_values) {
auto [min_x, max_x, min_y, max_y] = get_limits(input_values);
auto const map = get_map(input_values);
// print_map(map);
// std::cout << std::endl;
int sum = std::accumulate(std::cbegin(map) + min_y, std::cend(map), 0, [](auto const& base, auto const& row) {
return base + std::count(std::cbegin(row), std::cend(row), '~');
});
std::cout << "Part2: " << sum << std::endl;
}
int main() {
auto const input_values = read_input("input");
part1(input_values);
part2(input_values);
return 0;
}
| true |
165329ee9ecfa5b0e0cffd2eb637f50fd469dd49 | C++ | floriansimon1/xboy | /src/gameboy/cpu/instructions/dereference-combined-into-single-increment.cpp | UTF-8 | 1,095 | 2.59375 | 3 | [] | no_license | #include <sstream>
#include "dereference-combined-into-single-increment.hpp"
#include "../../../debug/register-string.hpp"
#include "../../gameboy.hpp"
DereferenceCombinedIntoSingleIncrement::DereferenceCombinedIntoSingleIncrement(
CpuRegisterPointer pointerRegister,
CpuRegisterPointer targetRegister,
const short sign,
bool low
):
ConstantTimeInstruction(8, 0, 1),
dereferenceInstruction(pointerRegister, targetRegister, low),
sign(sign)
{
}
void DereferenceCombinedIntoSingleIncrement::execute(Gameboy &gameboy, const uint8_t *data) const {
dereferenceInstruction.execute(gameboy, data);
gameboy.cpu.*(dereferenceInstruction.pointerRegister) += sign;
}
std::string DereferenceCombinedIntoSingleIncrement::toString() const {
std::ostringstream result;
const auto signChar = sign == -1 ? '-' : '+';
result << "LD " << registerString(dereferenceInstruction.targetRegister, true, dereferenceInstruction.low)
<< ", (" << registerString(dereferenceInstruction.pointerRegister, false, false) << signChar << ')';
return result.str();
}
| true |
51d39d37398e1b06458c0c3487965e2910130c4a | C++ | WitoldSobczak/PAMSI-lab | /Kolejka/Kolejka.cpp | WINDOWS-1250 | 1,575 | 3.671875 | 4 | [] | no_license | /** Funkcja glowna programu opartego na bibliotece STL Standard Template Library w programie uzywamy adapteras kolejki
* std::queue. okreslany mianem FIFO First In First Out.Adapter ten zawiera nastepujace funkcje ,ktore uzylem w programie:
*
* back Zwraca referencj na ostatni element w kolejce;
* empty Sprawdza czy kolejka jest pusta;
* front Zwraca referencj na pierwszy element w kolejce;
* pop Usuwa element z pocztku kolejki;
* push Umieszcza nowy element na kocu kolejki;
* size Zwraca liczb elementw znajdujcych si w kolejce;
*
*/
#include <iostream>
#include <queue>
#include "Kolejka.h"
using namespace std;
int wartosc;
int main()
{
kolejkaa baza;
int opcja;
do{
cout<<"0. Koniec programu."<<endl;
cout<<"1. Umie elementy w kolejce."<<endl;
cout<<"2. Wyswietl elementy koleki."<<endl;
cout<<"3. Wyswietlenie pierwszego i ostatniego elementu kolejki."<<endl;
cout<<"4. Umie element na stosie."<<endl;
cout<<"5. Usun pierwszy element kolejki."<<endl;
cout<<"6. Usun koncowy element kolejki."<<endl;
cout<<"Wybierz opcje: ";
cin>>opcja;
switch(opcja)
{
case 1:
baza.push(wartosc);
break;
case 2:
baza.wyswietl();
break;
case 3:
cout<<"Pierwszy element kolejki: ";
baza.wyswietl_poczatek();
cout<<"Koncowy element kolejki: ";
baza.wyswietl_koniec();
break;
case 4:
baza.push_jeden(wartosc);
break;
case 5:
baza.pop_poczatek();
break;
case 6:
baza.pop_koniec();
break;
default:
break;
}
}while(opcja!=0);
return 0;
}
| true |
876f86490d2f47822633c8a302b6f7f4a2c7ef0c | C++ | touyou/CompetitiveProgramming | /aoj/0125.cpp | UTF-8 | 1,284 | 2.578125 | 3 | [] | no_license | #include <cstdio>
int y1, m1, d1, y2, m2, d2;
int day[2][12]={
{31,28,31,30,31,30,31,31,30,31,30,31},
{31,29,31,30,31,30,31,31,30,31,30,31}
};
bool uruu(int year) {
if (year%400==0) return true;
else if (year%100==0) return false;
else if (year%4==0) return true;
else return false;
}
int main() {
while (scanf("%d%d%d%d%d%d",&y1,&m1,&d1,&y2,&m2,&d2)) {
if (y1==-1&&m1==-1&&d1==-1&&y2==-1&&m2==-1&&d2==-1) break;
long long res = 0, flag;
if (y1==y2) {
if (uruu(y1)) flag = 1;
else flag = 0;
if (m1==m2) res = d2-d1;
else {
for (int i=m1; i<m2-1; i++) res += day[flag][i];
res += day[flag][m1-1] - d1;
res += d2;
}
} else {
if (uruu(y1)) flag = 1;
else flag = 0;
for (int i=m1; i<12; i++) res += day[flag][i];
res += day[flag][m1-1] - d1;
if (y1+1<y2) for (int i=y1+1; i<y2; i++) {
if (uruu(i)) res += 366;
else res += 365;
}
if (uruu(y2)) flag = 1;
else flag = 0;
for (int i=0; i<m2-1; i++) res += day[flag][i];
res += d2;
}
printf("%lld\n", res);
}
}
| true |
0414747946b0075a859f0f614cfb2ca5f9de2152 | C++ | Lzyuuu/Cpp-Program | /Chapter 5/Interest/Interest/main.cpp | UTF-8 | 848 | 3.46875 | 3 | [] | no_license | //
// main.cpp
// Interest
//
// Created by Zhaoyu Lai on 2019/2/23.
// Copyright © 2019 Zhaoyu Lai. All rights reserved.
//
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
// initialization
double principle{1000.00}; // initial amount
double rate{0.05}; // interest rate
cout << setprecision(2) << fixed;
cout << "Original amount invested: " << principle << endl;
cout << " Annual interest rate: " << rate << endl;
// display headers
cout << "\nYear" << setw(20) << "Amount on deposit" << endl;
// calculate every year's amount
for (unsigned int year{1}; year <= 10; year++) {
// calculate
double amount = principle * pow(1.0 + rate, year);
// display
cout << setw(4) << year << setw(20) << amount << endl;
}
}
| true |
464887f77b1a30969156a29bf25ac16d744e46b9 | C++ | awnonbhowmik/TicTacToe-in-CPP | /TicTacToe.cpp | UTF-8 | 3,638 | 3.21875 | 3 | [] | no_license | #include<iostream>
#include "TicTacToe.h"
using namespace std;
void TicTacToe::ClearBoard()
{
system("CLS");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
Board[i][j] = ' ';
}
}
TicTacToe::TicTacToe()
{
ClearBoard();
}
void TicTacToe::PrintBoard(char Board[3][3])
{
cout << "\t\t | | \n";
cout << "\t\t "<<Board[0][0]<<" | "<<Board[0][1]<<" | "<<Board[0][2]<<" \n";
cout << "\t\t_____|_____|_____\n";
cout << "\t\t | | \n";
cout << "\t\t "<<Board[1][0]<<" | "<<Board[1][1]<<" | "<<Board[1][2]<<" \n";
cout << "\t\t_____|_____|_____\n";
cout << "\t\t | | \n";
cout << "\t\t "<<Board[2][0]<<" | "<<Board[2][1]<<" | "<<Board[2][2]<<" \n";
cout << "\t\t | | \n";
}
int TicTacToe::GetMoveX()
{
int positionX;
bool isValidInput = false;
while (isValidInput == false) {
cout << "Please enter your move (X-axis):";
cin >> positionX;
if (positionX < 1 || positionX > 3)
cout << "Invalid X coordinate" << endl;
else
isValidInput = true;
}
return positionX - 1;
}
int TicTacToe::GetMoveY()
{
int positionY;
bool isValidInput = false;
while (isValidInput == false) {
cout << "Please enter your move (Y-axis):";
cin >> positionY;
if (positionY < 1 || positionY > 3)
cout << "Invalid Y coordinate" << endl;
else
isValidInput = true;
}
return positionY - 1;
}
bool TicTacToe::placeMarker(int x,int y, char currentPlayer)
{
if (Board[x][y] != ' ')
return false;
Board[x][y] = currentPlayer;
return true;
}
void TicTacToe::Mark(int x, int y, char currentPlayer)
{
Board[x][y] = currentPlayer;
}
bool TicTacToe::checkWin()
{
//win conditions
//check rows "0 0 0" or "X X X"
for (int i = 0; i < 3; i++) {
if ((Board[i][0] == Board[i][1]) && (Board[i][1] == Board[i][2]) && Board[i][0] != ' ')
return true;
}
//check columns
// 0 X
// 0 X
// 0 X
for (int i = 0; i < 3; i++) {
if ((Board[i][0] == Board[i][1]) && (Board[i][1] == Board[i][2]) && Board[i][0] != ' ')
return true;
}
//check diagonals
// O X
// O X
// O X
// OR
// O X
// O X
// O X
if ((Board[0][0] == Board[1][1]) && (Board[1][1] == Board[2][2]) && Board[0][0] != ' ')
return true;
if ((Board[2][0] == Board[1][1]) && (Board[1][1] == Board[0][2]) && Board[1][1] != ' ')
return true;
//else return false
return false;
}
void TicTacToe::PlayGame()
{
//system("pause");
char Player1 = 'X';
char Player2 = 'O';
char currentPlayer = Player1;
bool isDone = false;
int x, y;
int turn = 0;
cout << "\t Tic-Tac-Toe GAME" << endl;
cout << "Player 1 = <X>\t Player 2 = <O>" << endl;
while (isDone == false) {
PrintBoard(Board);
cout << "Player " << currentPlayer << "'s turn" << endl;
x = GetMoveX();
y = GetMoveY();
if (placeMarker(x, y, currentPlayer) == false) {
cout << "That spot is taken!" << endl;
system("pause");
}
else
{
turn++;
if (checkWin() == true) {
system("CLS");
PrintBoard(Board);
cout << "Game over. " << currentPlayer << " wins!" << endl;
isDone = true;
system("pause");
}
else if (turn == 9) {
system("CLS");
PrintBoard(Board);
cout << "Its a tie!" << endl;
isDone = true;
system("pause");
}
else {
Mark(x, y, currentPlayer);
if (currentPlayer == Player1)
currentPlayer = Player2;
else
currentPlayer = Player1;
}
}
system("CLS");
}
} | true |
a5f4c97f99161f5fcaec41ece9e25e6879a5c964 | C++ | mke01/BasicC- | /Day 11/02 The this pointer/Source03.cpp | UTF-8 | 552 | 3.4375 | 3 | [] | no_license | struct Integer
{
int n;
void SetN(Integer *const This, int value)
{
Integer t;
// This = &t; // such assignment is prohibited
This->n = value;
}
};
void SetN(Integer *const This, int value);
int main()
{
Integer u;
u.SetN(&u, 5);
Integer v;
v.SetN(&v, 15);
return 0;
}
/*
When we executed above program and stepped into
SetN function, we noticed presence of the 'this' pointer
besides the 'This' pointer.
Also we noticed that they both were containing same address
which were the addresses of corresponding objects 'u' and
'v'.
*/ | true |
99382322ee45b17dbc91165201ce1b3360995cd5 | C++ | XPRIZE/GLEXP-Team-KitkitSchool | /mainapp/Classes/Games/StarFall/StarFall.cpp | UTF-8 | 1,283 | 2.703125 | 3 | [
"Apache-2.0",
"CC-BY-3.0",
"CC-BY-4.0",
"MIT"
] | permissive | //
// StarFall.cpp -- Bubble-falling typing game with a keyboard
// TodoSchool on Jul 22, 2016
//
// Copyright (c) 2016 Enuma, Inc. All rights reserved.
// See LICENSE.md for more details.
//
#include "StarFall.h"
#include "Models/StarFallWorksheet.h"
#include "Core/StarFallScene.h"
#include <numeric>
using todoschool::starfall::Worksheet;
StarFall::StarFall() {
}
StarFall::StarFall(int LevelID,
std::function<void()> OnSuccess,
std::function<void()> OnFail)
: LevelID(LevelID)
, OnSuccess(OnSuccess)
, OnFail(OnFail)
{
}
std::vector<int> StarFall::getCandidateLevelIDs() {
std::vector<int> IDs(Worksheet::size());
std::iota(IDs.begin(), IDs.end(), 1);
return IDs;
}
void StarFall::setLevelID(int LevelID) {
this->LevelID = LevelID;
}
void StarFall::setOnSuccess(std::function<void()> F) {
this->OnSuccess = F;
}
void StarFall::setOnFail(std::function<void()> F) {
this->OnFail = F;
}
cocos2d::Scene* StarFall::createScene() {
using namespace todoschool::starfall;
auto Sheet = Worksheet::forLevelID(LevelID);
auto It = StarFallScene::create();
It->TheWorksheet = Sheet;
It->LevelID = LevelID;
It->OnSuccess = OnSuccess;
It->OnFail = OnFail;
return It;
}
| true |
eda2ada2e44aac1bdc252b0db695313bbfbc3ed9 | C++ | preyta/leetcode_oj | /addtwonumber.cpp | UTF-8 | 592 | 3.21875 | 3 | [] | no_license | /**
* * Definition for singly-linked list.
* * struct ListNode {
* * int val;
* * ListNode *next;
* * ListNode(int x) : val(x), next(NULL) {}
* * };
* */
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
int carry=0;
ListNode result(0),*end=&result;
while(l1||l2||carry){
int digitSum=(l1?l1->val:0)+(l2?l2->val:0)+carry;
end->next=new ListNode(digitSum%10);
end=end->next;
carry=digitSum/10;
l1 = l1 ? l1->next : l1;
l2 = l2 ? l2->next : l2;
}
return result.next;
}
};
| true |
a9c45b7808725147d0f7e2dfedbac62deeecda7d | C++ | wyxTrustYs/Snake | /snake/snake/main.cpp | GB18030 | 2,838 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include "MyGame.h"
#include "MyMap.h"
#include "Print.h"
#include "Snake.h"
#include "SaveAndRead.h"
using namespace std;
int main() {
int option;
char name[10];
int num;
int flat;
Snake snake;
FullScreen();
while (true) {
system("cls");
WriteChar(35, 5, "̰Ϸ");
WriteChar(20, 10, "1ʼϷ");
WriteChar(30, 10, "2༭ͼ");
WriteChar(40, 10, "3ͼ");
WriteChar(50, 10, "4ȡ浵\n");
cin >> option;
switch (option)
{
case 1:
system("cls");
WriteChar(20, 10, "1ͳ淨");
WriteChar(28, 10, "2Ȥζ淨\n");
cin >> num;
flat = SetSpeed();
if (flat == 4) break;
FileToMap("init");
LoadMap();
snake.Init("player1");
switch (num)
{
case 1:
TraditionStart("init",snake);
break;
case 2:
FunnyStart("init",snake);
break;
default:
break;
}
break;
case 2:
// cout << "1ĵͼ\n2½ͼ\n" << endl;
system("cls");
WriteChar(20, 10, "1ĵͼ");
WriteChar(28, 10, "2½ͼ\n");
cin >> num;
switch (num)
{
case 1:
system("cls");
system("dir .\\map");
cin >> name;
FileToMap(name);
EditMap();
MapToFile(name);
break;
case 2:
// cout << "ͼ" << endl;
system("cls");
WriteChar(20, 10, "ͼ");
cin >> name;
NewMap();
MapToFile(name);
break;
default:
break;
}
break;
case 3:
{
system("cls");
system("dir .\\map");
cout << "ѡҪĵͼ" << endl;
cin >> name;
system("cls");
WriteChar(20, 10, "1ͳ淨");
WriteChar(28, 10, "2Ȥζ淨\n");
cin >> num;
char setlevel = SetSpeed();
FileToMap(name);
LoadMap();
snake.Init("player1");
switch (num)
{
case 1:
TraditionStart(name, snake);
break;
case 2:
FunnyStart(name, snake);
break;
default:
break;
}
break;
}
case 4:
{
char model;
char level;
char direction;
char *tmpname = NULL;
system("cls");
system("dir .\\data");
cin >> name;
snake.snake.clear();
tmpname = ReadingSave(name, snake);
direction = tmpname[strlen(tmpname) - 1];
tmpname[strlen(tmpname) - 1] = '\0';
level = tmpname[strlen(tmpname) - 1];
tmpname[strlen(tmpname) - 1] = '\0';
model = tmpname[strlen(tmpname) - 1];
tmpname[strlen(tmpname) - 1] = '\0';
strcpy(name, tmpname);
SetDirection(direction);
SetSpeed(level);
system("cls");
FileToMap(name);
LoadMap();
// SetSnake(snake);
switch (model)
{
case '1':
TraditionStart(name, snake);
break;
case '2':
FunnyStart(name, snake);
break;
default:
break;
}
break;
}
default:
break;
}
}
return 0;
} | true |
373bf84155492c45e5864cd63794ed3fed0b0d66 | C++ | r2kberlin/Ardunio | /Lichtsensor/Lichtsensor.ino | UTF-8 | 531 | 2.921875 | 3 | [] | no_license | int eingang= A7;
int LED = 5;
int sensorWert = 0;
void setup()//Hier beginnt das Setup.
{
Serial.begin(9600);
pinMode (LED, OUTPUT);
//Der analoge Pin muss nicht definiert werden.
}
void loop()
{
sensorWert=analogRead(eingang);
Serial.print("Sensorwert = " ); Serial.println(sensorWert);
if (sensorWert > 650) //Wenn der Sensorwert über 512 beträgt….
{
digitalWrite(LED, HIGH); //…soll die LED leuchten…
}
else
{
digitalWrite(LED, LOW); //….soll sie nicht leuchten.
}
delay (50);
}
| true |
13cdc1ac983c182e7531789b2bfde04c11820593 | C++ | morphixelf/delegate | /delegate_test.cpp | UTF-8 | 1,450 | 2.8125 | 3 | [
"MIT"
] | permissive | //---------------------------------------------------------------------------
// Created by Morphixelf
// https://github.com/morphixelf/
// The MIT License
//---------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
//---------------------------------------------------------------------------
#include "delegate.h"
typedef delegate<const char *, int, int> func_a;
typedef delegate<bool, const func_a &> func_b;
typedef delegate<void, bool> func_c;
//---------------------------------------------------------------------------
class Test
{
public:
const char *a(int x, int y)
{
printf("Test::a(%d,%d);\r\n",x,y);
return "abcdef";
}
bool b(const func_a &func) const
{
const char *s = func(123,456);
printf("Test::b(\"%s\");\r\n",s);
return true;
}
static void c(bool f)
{
printf("Test::c(%s);\r\n",(f?"true":"false"));
}
};
//---------------------------------------------------------------------------
int main(int argc, char *argv[])
{
Test obj;
func_a a = func_a::from_method<Test,&Test::a>(&obj);
func_b b = func_b::from_const_method<Test,&Test::b>(&obj);
func_c c = Test::c;
c( b( a ) );
system("pause");
return 0;
}
//---------------------------------------------------------------------------
//
//---------------------------------------------------------------------------
| true |
6d71bedec53263b33fdef03f1264c57cd4c98d2d | C++ | Delmurat/C | /2-1.cpp | UTF-8 | 167 | 2.75 | 3 | [] | no_license | #include<stdio.h>
int main()
{
int nArray[10]={1,2,3,4,5,6,7,8,9};
for(int i=0;i<10;i++)
{
printf("%d\n",nArray[i]*2);
}
return 0;
}
| true |
1180d61bee7d0d8055933c438a2fc20526ceff0b | C++ | BJas/InterviewBit | /backtracking/palindrome_partintioning.cpp | UTF-8 | 1,134 | 3.34375 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<vector>
#include<map>
using namespace std;
bool isPalindrome(string s) {
int i=0, j=s.size()-1;
while(i<j) {
if(s[i]!=s[j])
return false;
i++;
j--;
}
return true;
}
void getPalindrome(string s, vector<string> &subset, vector<vector<string> > &result, int index) {
if(index==s.size()) {
result.push_back(subset);
return;
}
string current = "";
for(int i=index; i<s.size(); i++) {
current += s[i];
cout<<current<<endl;
if(isPalindrome(current)) {
subset.push_back(current);
printf("Subset:\n");
for (size_t i = 0; i < subset.size(); i++) {
cout<<subset[i]<<" ";
}
printf("\n");
getPalindrome(s, subset, result, i+1);
printf("Pops\n");
subset.pop_back();
}
}
}
int main() {
string s;
cin>>s;
vector<string> subset;
vector<vector<string> > result;
getPalindrome(s, subset, result, 0);
cout<<"Result is:\n";
for(int i=0; i<result.size(); i++) {
for(int j=0; j<result[i].size(); j++) {
cout<<result[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
| true |
b5c2876073d2292e1433a37d21c6df89373424e5 | C++ | novo1985/Leetcode | /Pairs and Intervals/435. Non-overlapping Intervals.cpp | UTF-8 | 1,019 | 3.734375 | 4 | [] | no_license | /* Given a collection of intervals, find the minimum number of intervals you need to remove
* to make the rest of the intervals non-overlapping.*/
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
int eraseOverlapIntervals(vector<Interval>& intervals) {
if(intervals.empty()) { return 0; }
//sort intervals by Interval.start
sort(intervals.begin(), intervals.end(), [](const Interval& a, const Interval& b){
return a.start < b.start;
});
int count = 0;
int end = intervals[0].end;
for(int i = 1; i < intervals.size(); i++) {
if(intervals[i].start < end) {//overlap
count++;
end = min(end, intervals[i].end);
}else {//no overlap
end = intervals[i].end;
}
}
return count;
}
};
| true |
8aed6a0f050a67719913bcc541915d701cc2acdc | C++ | dreamspot4everyone/No-Exam | /Greedy/Job_Schduling.cpp | UTF-8 | 1,377 | 3.375 | 3 | [] | no_license | #include<iostream>
using namespace std;
struct job
{
int dead;
int profit;
};
void merge(job a[],int l,int mid,int r,int n)
{
int i=l,j=mid+1,k=l;
job z[r+1];
while(i<=mid && j<=r)
{
if(a[i].profit>=a[j].profit)
z[k++]=a[i++];
else
z[k++]=a[j++];
}
while(i<=mid)
z[k++]=a[i++];
while(j<=r)
z[k++]=a[j++];
for(int i=l;i<r;i++)
a[i]=z[i];
}
void merge_sort(job a[] , int l , int r , int n)
{
if(l<r)
{
int mid=(l+r)/2;
merge_sort(a,l,mid,n);
merge_sort(a,mid+1,r,n);
merge(a,l,mid,r,n);
}
}
void job_shed(job a[],int n)
{
int x[n]={0};
bool slot[n]={false};
for(int i=0;i<n;i++)
{
for(int j=min(n,a[i].dead);j>=1;--j)
{
if(slot[j]==false)
{
x[j]=a[i].profit;
slot[j]=true;
break;
}
}
}
int ans=0.0;
for(int i=0 ; i<n ; ++i)
ans+=x[i];
cout<<ans<<endl;
}
int main()
{
int n;
cout<<"Enter no of tasks: ";
cin>>n;
job a[n];
for(int i=0;i<n;i++)
{
cout<<"Enter "<<i+1<<" profit ";
cin>>a[i].profit;
cout<<"Enter "<<i+1<<" Deadline ";
cin>>a[i].dead;
}
merge_sort(a,0,n-1,n);
job_shed(a,n);
}
/*
Enter no of tasks: 4
2 1 2 1
100 10 15 27
127
for(int i=0 ; i<n ; ++i)
cin>>a[i].dead;
for(int i=0 ; i<n ; ++i)
cin>>a[i].profit;
*/
| true |
f1efcc7fed1565ace532aafb6c7d1fd9586d0da2 | C++ | truong225/Image-editor | /src/Filter.hpp | UTF-8 | 801 | 2.515625 | 3 | [] | no_license | #ifndef FILTER_HPP
#define FILTER_HPP
#include <QVector>
class Filter {
QVector <QVector <qreal> > kernel;
public:
Filter();
Filter(int width, int height);
Filter(const Filter &filter);
static Filter single(int width, int height);
static Filter single(const Filter &filter);
const qreal & at(int x, int y) const;
qreal & at(int x, int y);
int width() const;
int height() const;
Filter normalized() const;
Filter transposed() const;
Filter & operator =(const Filter &filter);
};
Filter operator -(const Filter &filter);
Filter operator +(const Filter &f, const Filter &g);
Filter operator -(const Filter &f, const Filter &g);
Filter operator *(qreal a, const Filter &f);
Filter operator *(const Filter &f, qreal a);
#endif // FILTER_HPP
| true |
8cb381b5f7969d431fcc3b77d36bb196e5fde309 | C++ | kohei-us/ray-tracing-practice | /constant_medium.cpp | UTF-8 | 1,598 | 2.578125 | 3 | [
"Unlicense"
] | permissive |
#include "constant_medium.h"
#include "material.h"
constant_medium::constant_medium(
const std::shared_ptr<hittable>& b, double density, const std::shared_ptr<texture>& t) :
boundary(b), phase_function(std::make_shared<isotropic>(t)), neg_inv_density(-1/density)
{}
constant_medium::constant_medium(
const std::shared_ptr<hittable>& b, double density, const color& c) :
boundary(b), phase_function(std::make_shared<isotropic>(c)), neg_inv_density(-1/density)
{}
bool constant_medium::hit(const ray &r, double t_min, double t_max, hit_record &rec) const
{
hit_record rec1, rec2;
if (!boundary->hit(r, -infinity, infinity, rec1))
return false;
if (!boundary->hit(r, rec1.t+0.0001, infinity, rec2))
return false;
if (rec1.t < t_min)
rec1.t = t_min;
if (rec2.t > t_max)
rec2.t = t_max;
if (rec1.t >= rec2.t)
return false;
if (rec1.t < 0)
rec1.t = 0;
const double ray_length = r.direction().length();
const double distance_inside_boundary = (rec2.t - rec1.t) * ray_length;
const double hit_distance = neg_inv_density * log(random_double());
if (hit_distance > distance_inside_boundary)
return false;
rec.t = rec1.t + hit_distance / ray_length;
rec.p = r.at(rec.t);
rec.normal = vec3(1,0,0); // arbitrary
rec.front_face = true; // also arbitrary
rec.mat_ptr = phase_function;
return true;
}
bool constant_medium::bounding_box(double time0, double time1, aabb &output_box) const
{
return boundary->bounding_box(time0, time1, output_box);
}
| true |
bbffb2d18383ddcc81d9915e1be3bc3412f97094 | C++ | oneapi-src/oneAPI-samples | /Publications/GPU-Opt-Guide/implicit-scaling/05_stream_cross_stack/stream_cross_stack.cpp | UTF-8 | 2,467 | 2.5625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | //==============================================================
// Copyright © 2022 Intel Corporation
//
// SPDX-License-Identifier: MIT
// =============================================================
// clang-format off
// Code for cross stack stream
#include <iostream>
#include <omp.h>
// compile via:
// icpx -O2 -fiopenmp -fopenmp-targets=spir64 ./stream_cross_stack.cpp
// run via:
// EnableWalkerPartition=1 ZE_AFFINITY_MASK=0 ./a.out
template <int cross_stack_fraction>
void cross_stack_stream() {
constexpr int64_t size = 256*1e6;
constexpr int64_t bytes = size * sizeof(int64_t);
int64_t *a = static_cast<int64_t*>(malloc( bytes ));
int64_t *b = static_cast<int64_t*>(malloc( bytes ));
int64_t *c = static_cast<int64_t*>(malloc( bytes ));
#pragma omp target enter data map( alloc:a[0:size] )
#pragma omp target enter data map( alloc:b[0:size] )
#pragma omp target enter data map( alloc:c[0:size] )
for ( int i = 0; i < size; ++i ) {
a[i] = i + 1;
b[i] = i - 1;
c[i] = 0;
}
#pragma omp target update to( a[0:size] )
#pragma omp target update to( b[0:size] )
#pragma omp target update to( c[0:size] )
const int num_max_rep = 100;
double time;
for ( int irep = 0; irep < num_max_rep+10; ++irep ) {
if ( irep == 10 ) time = omp_get_wtime();
#pragma omp target teams distribute parallel for simd
for ( int j = 0; j < size; ++j ) {
const int cache_line_id = j / 16;
int i;
if ( (cache_line_id%cross_stack_fraction) == 0 ) {
i = (j+size/2)%size;
}
else {
i = j;
}
c[i] = a[i] + b[i];
}
}
time = omp_get_wtime() - time;
time = time/num_max_rep;
#pragma omp target update from( c[0:size] )
for ( int i = 0; i < size; ++i ) {
if ( c[i] != 2*i ) {
std::cout << "wrong results!" << std::endl;
exit(1);
}
}
const int64_t streamed_bytes = 3 * size * sizeof(int64_t);
std::cout << "cross_stack_percent = " << (1/(double)cross_stack_fraction)*100
<< "%, bandwidth = " << (streamed_bytes/time) * 1E-9 << " GB/s" << std::endl;
}
int main() {
cross_stack_stream< 1>();
cross_stack_stream< 2>();
cross_stack_stream< 4>();
cross_stack_stream< 8>();
cross_stack_stream<16>();
cross_stack_stream<32>();
}
| true |
23977a8472d29f383a7582618c0b3bdd76b6a124 | C++ | NellyNi/top-k | /table.h | UTF-8 | 667 | 2.78125 | 3 | [] | no_license | #ifndef table_h
#define table_h
#include<vector>
#include<iostream>
#include<string>
#include<sstream>
#include "entry.h"
using namespace std;
class Table {
public:
//constructor
//Table(unsigned int max_entries);
//Table(unsigned int entries, std::istream& input);
Table();
//functions
void put(string key, int data);
void put(Entry e);
int search(string key);
void update_data(string key, int data);
void remove(string key);
friend ostream& operator<< (ostream& out, const Table &t);
private:
vector<vector<Entry> > values;
const int entries=16;
int length;
int hash(string key) const;
// static unsigned int accesses;
};
#endif | true |
55ee44a6e0debb7c14b6f51a2818d80cb8bc48fd | C++ | kesslp/CSS343 | /HW4/HW4/ClassicalCD.h | UTF-8 | 473 | 2.640625 | 3 | [] | no_license | #include "Item.h"
#pragma once
class ClassicalCD : public Item
{
friend ostream& operator<<(ostream&, const ClassicalCD&);
friend istream& operator>>(istream&, ClassicalCD&);
public:
ClassicalCD();
ClassicalCD(string, string, string, int);
bool operator<(const Item&);
bool operator>(const Item&);
bool operator==(const Item&);
bool operator!=(const Item&);
void display() const;
~ClassicalCD();
private:
string composer;
};
| true |
a7c0a71ec6da2008f60bab2be992b78669b194f5 | C++ | SeanWuLearner/leetcode | /src/q0560.h | UTF-8 | 1,078 | 3.40625 | 3 | [
"MIT"
] | permissive | #include <unordered_set>
/*Solution1: hashset the acc*/
class Solution1 {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_multiset<int> memo;
memo.insert(0);
int acc = 0, ans = 0;
for(auto i : nums){
acc += i;
ans += memo.count(acc - k);
memo.insert(acc);
}
return ans;
}
};
/*Solution 2: use hashmap, <acc, freq> instead of unordered_multiset*/
#include <unordered_map>
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int,int> memo;
memo[0] = 1;
int acc = 0, ans = 0;
for(auto i : nums){
acc += i;
ans += memo[acc - k];
memo[acc]++;
}
return ans;
}
};
TEST(TestSolution, test1) {
Solution s;
vector<int> q;
q = {1,1,1};
EXPECT_EQ(s.subarraySum(q,2), 2);
q = {1,2,3};
EXPECT_EQ(s.subarraySum(q, 3), 2);
q = {1,-1,0};
EXPECT_EQ(s.subarraySum(q, 0), 3);
q = {1};
EXPECT_EQ(s.subarraySum(q, 0), 0);
}
| true |
81de1e7ecc2c1f656a450188b2f2127263ebf698 | C++ | frc5024/PowerUP | /2017_11_27/SetCursorPos/cRobot.cpp | UTF-8 | 1,971 | 2.8125 | 3 | [] | no_license | #include "cRobot.h"
cRobot::cRobot()
{
this->m_pSPThingy = new cSecretPhysics();
this->mass = cRobot::DEFAULTROBOTMASSKG; // 50.0kg
this->m_pXMotor = new cMotor();
this->m_pYMotor = new cMotor();
this->m_physState.position.x = 0.0f;
this->m_physState.position.y = 20.0f;
// this->m_physState.velocity.x = 1.0;
// this->m_physState.velocity.y = 1.5;
return;
}
cRobot::~cRobot()
{
delete this->m_pSPThingy;
return;
}
double cRobot::SimulationTimeTick(void)
{
// Update through the integrator
// (And get the current time tick, with jitter)
double currentTickTime = this->m_pSPThingy->UpdateTick(this->m_physState);
// Accelerate the motors
this->m_pXMotor->SimulationTimeTick(currentTickTime, this->mass);
this->m_pYMotor->SimulationTimeTick(currentTickTime, this->mass);
// Adjust the velocity of the robot based on motor speed
this->m_physState.velocity.x = this->m_pXMotor->getCurrentSpeed();
this->m_physState.velocity.y = this->m_pYMotor->getCurrentSpeed();
return currentTickTime;
}
// This is effectively motor "force", really
void cRobot::setMotorSpeedX(float speed)
{
this->m_pXMotor->setTargetSpeed(speed);
return;
}
void cRobot::setMotorSpeedY(float speed)
{
this->m_pYMotor->setTargetSpeed(speed);
return;
}
void cRobot::setMotorSpeed(float Xspeed, float Yspeed)
{
this->m_pXMotor->setTargetSpeed(Xspeed);
this->m_pYMotor->setTargetSpeed(Yspeed);
return;
}
sPoint2D cRobot::getCurrentMotorSpeed(void)
{
sPoint2D curSpeed;
curSpeed.x = this->m_pXMotor->getCurrentSpeed();
curSpeed.y = this->m_pYMotor->getCurrentSpeed();
return curSpeed;
}
sPoint2D cRobot::getPosition(void)
{
return this->m_physState.position;
}
sPoint2D cRobot::getVelocity(void)
{
return this->m_physState.velocity;
}
sPoint2D cRobot::getAccel(void)
{
return this->m_physState.accel;
}
double cRobot::getElapsedTime(void)
{
return this->m_pSPThingy->getElapsedTime();
}
//static
const float cRobot::DEFAULTROBOTMASSKG = 50.0f; // 50kg
| true |
e0882771cc73461f6e8d0462d89f328d4a4d6aaa | C++ | nguardadov/EstructurasDinamicas | /grupo2-proyecto/pro/VentanaPrincipal.cpp | UTF-8 | 4,208 | 2.765625 | 3 | [] | no_license | #include "VentanaPrincipal.h"
#include "ClasePuntaje.h"
#include "ClaseJuego.h"
#include <SDL2/SDL_image.h>
#include <iostream>
#include <cstdlib>
VentanaPrincipal::VentanaPrincipal()
{
this -> windows=nullptr;
this ->windowSurface=nullptr;
this ->isRunning=true;
this->player1="";
this->player2="";
this->fondoPrin = NULL;
this->jugando = NULL;
this->puntos = NULL;
this->ayuda = NULL;
SDL_Init(SDL_INIT_VIDEO);
this-> windows = SDL_CreateWindow("'MI TIC TAC TOE'", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 600, 600, SDL_WINDOW_SHOWN);
}
int VentanaPrincipal::corriendo()
{
int flag=-1;
SDL_Event ev;
this ->windowSurface= SDL_GetWindowSurface(this-> windows);
this->fondoPrin = IMG_Load("fondoPrincipal.jpg");
this->jugando = IMG_Load("jugando.jpg");
this->puntos = IMG_Load("puntajes.jpg");
this->ayuda = IMG_Load("ayuda.jpg");
VentanaPrincipal::colocando(0, 0, fondoPrin);
VentanaPrincipal::colocando(310,100, jugando);
VentanaPrincipal::colocando(370,100, puntos);
VentanaPrincipal::colocando(430,100, ayuda);
while(this->isRunning)
{
while(SDL_PollEvent(&ev) != 0)
{
if(ev.type == SDL_QUIT)
{
flag=-1;
this ->isRunning =false;
}
else if(ev.type == SDL_MOUSEBUTTONDOWN)
{
if(ev.button.button == SDL_BUTTON_LEFT)
{
if(ev.button.x >=100 && ev.button.x<=500 && ev.button.y>=310 && ev.button.y<=360)
{
SDL_DestroyWindow(this->windows);
while (true)
{
lista l;
cout << "Ingrese el nombre del primer jugador: ";
cin >>this->player1;
if(!l.buscarjdor(player1))
{
break;
}
}
while (true)
{
lista l;
cout << "Ingrese el nombre del segundo jugador: ";
cin >>this->player2;
if(!l.buscarjdor(player2))
{
break;
}
}
flag= 1;
this->isRunning=false;
}
if(ev.button.x >=100 && ev.button.x<=500 && ev.button.y>=370 && ev.button.y<=420)
{
bool bandera=true;
while(bandera==true)
{
system("xdg-open archivoarreglado.txt");
bandera=false;
}
flag =1;
}
if(ev.button.x >=100 && ev.button.x<=500 && ev.button.y>=430 && ev.button.y<=480)
{
bool bandera=true;
while(bandera==true)
{
system("xdg-open instrucciones.pdf");
bandera=false;
}
flag =1;
}
}
}
SDL_UpdateWindowSurface(this->windows);
}
}
SDL_FreeSurface(this->fondoPrin);
SDL_FreeSurface(this->jugando);
SDL_FreeSurface(this->puntos);
SDL_FreeSurface(this->ayuda);
SDL_DestroyWindow(this->windows);
this->windows=nullptr;
SDL_Quit();
return flag;
}
void VentanaPrincipal::colocando(int x, int y, SDL_Surface*imagen1)
{
SDL_Rect destination;
destination.x = y;
destination.y = x;
SDL_BlitSurface(imagen1,NULL,this->windowSurface,&destination);
}
string VentanaPrincipal::getplayer1()
{
return this->player1;
}
string VentanaPrincipal::getplayer2()
{
return this->player2;
}
| true |
ec9e218cdf5deeca712b3ec98d8d69f603866613 | C++ | maeda-lab/Scaledown | /確認用/hirayama_IK_Serial/Serial_Binary_Communication/main.cpp | UTF-8 | 2,418 | 2.6875 | 3 | [] | no_license | // Aug 25, 2020
// Masahiro Furukawa
//
// Serial Binary Communication
#include <math.h>
#include <string>
#include <inttypes.h>
#include <stdlib.h>
#include <stdio.h>
#include <Windows.h>
#include "QueryPerformanceTimer.h"
#include "mbed_Serial_binary.h"
// Target Angle in deg
struct TargetAngle {
float J1_deg;
float J2_deg;
float J3_deg;
float J4_deg;
float J5_deg;
float J6_deg;
} tgtAng;
#define NUM_OF_HEADER 2
#define NUM_OF_BUF 26
int main()
{
// serial port
Com_Binary com;
unsigned char sbuf[4 * 6 + NUM_OF_HEADER];
unsigned char fbuf[4];
float fret;
// timer
QueryPerformanceTimer qpTime;
qpTime.setFps(60);
qpTime.wait();
tgtAng.J1_deg = 5.3f;
tgtAng.J2_deg = 5.2f;
tgtAng.J3_deg = -0.3f;
tgtAng.J4_deg = 40.0f;
tgtAng.J5_deg = 50.0f;
tgtAng.J6_deg = 60.0f;
// make float structure -> byte list
com.float2byte(&sbuf[0 + NUM_OF_HEADER], tgtAng.J1_deg);
com.float2byte(&sbuf[4 + NUM_OF_HEADER], tgtAng.J2_deg);
com.float2byte(&sbuf[8 + NUM_OF_HEADER], tgtAng.J3_deg);
com.float2byte(&sbuf[12 + NUM_OF_HEADER], tgtAng.J4_deg);
com.float2byte(&sbuf[16 + NUM_OF_HEADER], tgtAng.J5_deg);
com.float2byte(&sbuf[20 + NUM_OF_HEADER], tgtAng.J6_deg);
// header
sbuf[0] = '*';
sbuf[1] = '+';
// bytes -> float conversion test
memcpy(fbuf, &sbuf[0 + NUM_OF_HEADER], 4);
com.byte2float(&fret, fbuf);
std::printf("J1_deg is %3.3lf \n", fret);
memcpy(fbuf, &sbuf[4 + NUM_OF_HEADER], 4);
com.byte2float(&fret, fbuf);
std::printf("J2_deg is %3.3lf \n", fret);
memcpy(fbuf, &sbuf[8 + NUM_OF_HEADER], 4);
com.byte2float(&fret, fbuf);
std::printf("J3_deg is %3.3lf \n", fret);
memcpy(fbuf, &sbuf[12 + NUM_OF_HEADER], 4);
com.byte2float(&fret, fbuf);
std::printf("J4_deg is %3.3lf \n", fret);
memcpy(fbuf, &sbuf[16 + NUM_OF_HEADER], 4);
com.byte2float(&fret, fbuf);
std::printf("J5_deg is %3.3lf \n", fret);
memcpy(fbuf, &sbuf[20 + NUM_OF_HEADER], 4);
com.byte2float(&fret, fbuf);
std::printf("J6_deg is %3.3lf \n", fret);
std::printf("The byte list : %02x %02x ", sbuf[0], sbuf[1]);
// dump byte list
for (int j = 0; j < 6; j++){
for (int i = 0; i < 4; i++){
std::printf("%02x ", (unsigned char) sbuf[i + 4 * j + NUM_OF_HEADER]);
}
printf(" ");
}
printf("\n\nsizeof(sbuf) = <%d>\n",(int)sizeof(sbuf));
// test for 24byte sending while 2 seconds
for (int i = 0; i < 120; i++) {
com.send_bytes(sbuf, NUM_OF_BUF);
qpTime.wait();
}
return 0;
}
| true |
a516447ef4afceec2380cd54b122957d2bdc1c0b | C++ | Xavier-Baudry/Battleship_AI | /Battleship_CORE/Battleship_Core.h | ISO-8859-1 | 3,749 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <utility>
#include <tuple>
#include <string>
#include <windows.h>
using namespace std;
#ifndef Battleship_Core_H
#define Battleship_Core_H
#define NUM_OF_GAMES 10
//#define HUMAN_MODE
//#define DELAY
#define FAIL 0
#define MISS 1
#define HIT 2
#define HITNSUNK 3
#define CARRIER '5'
#define BATTLESHIP '4'
#define SUBMARINE '3'
#define CRUISER '2'
#define DESTROYER '1'
class Game_Board
{
int ship_stats[5];
public:
char my_ships[10][10];
char other_ships[10][10];
Game_Board();
void set_new_game();
int take_hit(pair<int, int> pos);
int update_radar(pair<int, int> pos, int success);
bool isDead();
bool place_ship(tuple<int, int, int> pos, char type);
void print_board();
};
class Player
{
public:
Game_Board my_board;
/******************************************************************************************/
/* METHODES OBLIGATOIRES */
/******************************************************************************************/
/*Les deux mthodes suivantes doivent etre dfini par la classe du AI sinon il ne*/
/*seras pas capable de jouer et l'engin traiteras le AI comme un joueur humain */
/*Le AI doit pouvoir retourner une paire du genre <i, j> qui indique au jeu ou tirer*/
/*Le parametre enemy_ship est un tableau de char avec les codes suivants: */
/* '.' = case vide */
/* 'O' = case touches */
/* 'X' = case manques */
virtual pair<int, int> fire_at(char enemy_ships[10][10]);
/*Le AI doit pouvoir retourner un tuple du genre <i, j, r> qui indique au placer un bateau*/
/*i et j sont les coordonns, r est la rotation 0 = vertical 1 = horizontal */
/*Les parametres sont les suivants: */
/* char type: Un char reprsentant le type de bateaux plac */
/* CARRIER = '5' (size: 5) */
/* BATTLESHIP = '4' (size: 4) */
/* SUBMARINE = '3' (size: 3) */
/* CRUISER = '2' (size: 3) */
/* DESTROYER = '1' (size: 2) */
/* my_ships: Un tableau de char reprsant les bateau du joeur */
/* Case vides = '.' */
/* Les autres cases on le numero du bateau assigner d'aprs */
/* la table prcdente (carrier '5', Battleship '4', ...) */
virtual tuple<int, int, int> set_boat_at(char type, char my_ship[10][10]);
/******************************************************************************************/
/* METHODES OPTIONNELS */
/******************************************************************************************/
/*Les mthodes suivantes ne sont pas obligatoires, elle permettent au AI de recevoir du */
/*feedback sur divers lments du jeu qui peuvent supporter la prise de dcision */
/*Le mthode suivante recois un hit reprsentant ce qui est arriv aprs avoir tirer */
/*Les valeures de status_code sont les suivantes: FAIL 0 */
/* MISS 1 */
/* HIT 2 */
/* HITNSUNK 3 */
/* *FAIL indique que le coup pris est invalide (out of bounds ou dj fait avant) */
virtual void receive_status_code(int status_code, char enemy_ships[10][10]);
/*Le mthode suivante recois un une pair indiquant ou l'enemy tirer pos(i,j) */
virtual void receive_hit_pos(pair<int, int> pos);
/*Le mthode indique qu'une nouvelle partie commencer */
virtual void new_game_started();
};
class Game_Engine
{
Player *A;
Player *B;
int num_of_turns;
public:
Game_Engine(Player *A, Player *B);
void main_game_loop();
void place_ships(Player *player);
};
#endif | true |
6b5f159fbb299a351d0f315254e69f2f5a726436 | C++ | MijaelTola/icpc | /atcoder/abc151F.cpp | UTF-8 | 635 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int n;
vector<pair<int,int> > v;
int main() {
cin >> n;
double cx = 0, cy = 0;
for (int i = 0; i < n; ++i) {
int x,y;
cin >> x >> y;
cx += x;
cy += y;
v.emplace_back(x,y);
}
cx /= n;
cy /= n;
auto dis = [](double a, double b, double x, double y) {
return sqrt((a - x) * (a - x) + (b - y) * (b - y));
};
double ans = 0;
for (int i = 0; i < n; ++i) {
double d = dis(v[i].first, v[i].second, cx, cy);
ans = max(ans, d);
}
printf("%.10lf\n", ans);
return 0;
}
| true |
a51d91096e4081136c0680fce7ff5da750342877 | C++ | jumbuna/data-structures-algorithms | /algs/searching/ExponentialSearch.h | UTF-8 | 532 | 2.75 | 3 | [
"MIT"
] | permissive | #pragma once
#include "BinarySearch.h"
//works on sorted data
//out performs binary search when value may appear toward the beginning
//logarithmic time complexity
//constant space complexity
namespace jumbuna {
template<class T>
int exponentialSearch(T *array, T value, size_t arraySize, int begin = 0) {
if(array[begin] != value) {
int i = 1+begin;
while(i < arraySize+begin && array[i] <= value) {
i *= 2;
}
return reBinarySearch(array, value, i/2, i > arraySize+begin ? arraySize+begin : i);
}
return begin;
}
} | true |
391071a77272bd26916a3f8670dd57702350f589 | C++ | jesusramirez95/Lab-Robotica | /ProyectoFinal/codigos/sensores.ino | UTF-8 | 3,033 | 2.875 | 3 | [] | no_license | #include <Servo.h>
char sensores[50] = {0};
const int trigPin = 8;
const int echoPin = 7;
long duration;
long distance;
int inByte = '0';
int SV1 = 0, SV2 = 0, US = 0;
Servo base; //Definir objetos servos
Servo shoulder;
Servo elbow;
Servo hand;
int hands = 0;
int elbows = 145;
int shoulders = 1;
int bases = 134;
int pos_base;
int pos_shoulder;
int pos_elbow;
char res;
void setup() {
Serial.begin(115200);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
hand.attach(10); //definir conexiones servo
elbow.attach(11);
shoulder.attach(12);
base.attach(13);
hand.write(0);
base.write(134);
shoulder.write(1);
elbow.write(145);
}
void loop() {
if (Serial.available()) {
inByte = Serial.read();
if (inByte == '1') { //recoger pieza
hands = 80;
shoulders = 72;
bases = 134;
base.write(bases);
delay(10);
hand.write(hands); //pinza cerrada
delay(10);
servo_move_shoulder(shoulders);
delay(1000);
Serial.println("nnnn");
}
else if (inByte == '2') { //abandonar pieza
hands = 80;
shoulders = 1;
bases = 50;
base.write(bases);
delay(10);
servo_move_shoulder(shoulders);
delay(1000);
hand.write(hands); //pinza cerrada
delay(1000);
Serial.println("nnnn");
}
else if (inByte == 's') {
SV1 = analogRead(A0);
delay(0.02);
SV2 = analogRead(A1);
delay(0.02);
digitalWrite(trigPin, LOW);
delay(10);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read pulse comes from HC-SR04 Echo pin
duration = pulseIn(echoPin, HIGH);
// Read echo pulse width
US = duration / 58;
delay(0.02);
String Sensores = String(SV1) + " " + String(SV2) + " " + String(US) + " ";
Serial.println(Sensores); //enviar string a raspberry pi
}
}
else {
base.write(134);
delay(10);
hand.write(0); //pinza cerrada
delay(10);
servo_move_shoulder(1);
}
}
int ultrasonido() {
digitalWrite(trigPin, LOW);
delay(10);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read pulse comes from HC-SR04 Echo pin
duration = pulseIn(echoPin, HIGH);
// Read echo pulse width
distance = duration / 58;
return distance;
}
void servo_move_shoulder(int x) {
if (pos_shoulder < x) {
for (int i = pos_shoulder; i <= x; i += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
shoulder.write(i); // tell servo to go to position in variable 'pos'
delay(15);
pos_shoulder = i;
}
}
else if (pos_shoulder > x) {
for (int i = pos_shoulder; i >= 0; i -= 1) { // goes from 180 degrees to 0 degrees
shoulder.write(i); // tell servo to go to position in variable 'pos'
delay(15);
pos_shoulder = i;
}
}
else {
shoulder.write(pos_shoulder);
delay(15);
}
}
| true |
a4a39d912a07ec19dec65e30ec6f5849326a52d1 | C++ | qinhx/algorithm | /DP/triangle/dp1.cpp | UTF-8 | 787 | 3.03125 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include <vector>
#include <cstring>
class Solution{
public:
int MaxSum(vector<vector<int> > t,int n){
vector<vector<int> > dp(n,vector<int>(n,0));
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i==0){
dp[i][j] = t[i][j];
}else {
if(j==0){
dp[i][j] = dp[i-1][j]+t[i][j];
}else{
dp[i][j] = max(dp[i-1][j]+t[i][j],dp[i-1][j-1]+t[i][j]);
}
}
}
}
int max =0;
for(int i=0;i<n;i++){
if(dp[n-1][i]>max)
max = dp[n-1][i];
}
return max;
}
};
int main(){
int n;
cin>>n;
vector<vector<int> > t(n,vector<int>(n,0));
int n1;
for(int i=0;i<n;i++){
for(int j=0;j<=i;j++){
cin>>n1;
t[i][j]=n1;
}
}
Solution solu;
cout<<solu.MaxSum(t,n)<<endl;
}
| true |
50a82fd62569c11ee1ab4928b23b89e3ad56b374 | C++ | ClementAbadie/Eggstia | /HTU21D_Humidity_Temperature.ino | UTF-8 | 654 | 2.6875 | 3 | [] | no_license |
#include "HTU21D_Humidity_Temperature.h"
void setup_HTU21D()
{
#ifdef DEBUG
Serial.println("HTU21D_setup");
#endif
myHumidity.begin();
}
void loop_HTU21D()
{
value_humidity = myHumidity.readHumidity() * HTU21D_HUMIDITY_CORRECTION_RAMP + HTU21D_HUMIDITY_CORRECTION_OFFSET;
value_temperature = myHumidity.readTemperature() * HTU21D_TEMPERATURE_CORRECTION_RAMP + HTU21D_TEMPERATURE_CORRECTION_OFFSET;
#ifdef DEBUG
Serial.println("HTU21D_loop");
Serial.print(" Temperature : ");
Serial.print(value_temperature, 1);
Serial.print(" C");
Serial.print(" Humidity : ");
Serial.print(value_humidity, 1);
Serial.println(" %");
#endif
}
| true |
d942168a00d0945997ca3ef66124007092d79694 | C++ | ajmarin/CTris | /Piece.h | UTF-8 | 458 | 2.546875 | 3 | [] | no_license | /**
* Piece
*/
#include "Block.h"
#include "Config.h"
#include "Defines.h"
#ifndef PIECE_CLASS
#define PIECE_CLASS
class Piece {
Block* parts[4];
Block* projection[4];
int row, col, type, rot;
static Piece* instance;
Piece(int r, int c, int type, int rotation);
void UpdateProjection();
public:
static Piece* CreatePiece();
bool CanMove(int drow, int dcol);
bool CanRotate();
void Fix();
bool Move(int drow, int dcol);
void Rotate();
};
#endif
| true |
df99c14beb719db25a7a0c393977bcdd25b487c6 | C++ | samiksha2325/pattern3 | /PATTERN3.CPP | UTF-8 | 409 | 2.515625 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int i,j,k,m;
for(i=1;i<=5;i++)
{
for(m=1;m<=i;m++)
{
printf("*");
}
for(j=9;j>=2*i;j--)
{
printf(" ");
}
for(k=1;k<=i;k++)
{
printf("*");
}
printf("\n");
}
for(i=1;i<=5;i++)
{
for(j=5;j>=i;j--)
{
printf("*");
}
for(k=2;k<2*i;k++)
{
printf(" ");
}
for(m=5;m>=i;m--)
{
printf("*");
}
printf("\n");
}
getch();
}
| true |
e38c0ab3b32c7f1be1eede9fe757b04cf813b618 | C++ | Ray-SunR/leetcode | /107. Binary Tree Level Order Traversal II/levelOrderBottom.cpp | UTF-8 | 1,416 | 3.65625 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int val, TreeNode* left = NULL, TreeNode* right = NULL)
: val(val)
, left(left)
, right(right){}
~TreeNode() { if (left) delete left; if (right) delete right; }
};
class Solution {
public:
vector<vector<int> > levelOrderBottom(TreeNode* root)
{
int ht = height(root);
vector<vector<int> > ret;
for (int i = ht; i >= 1; i--)
{
vector<int> level;
PrintLevel(root, i, level);
ret.push_back(level);
}
return ret;
}
private:
int height(TreeNode* root)
{
if (!root) { return 0; }
return 1 + max(height(root->left), height(root->right));
}
int max(int a, int b) { return a > b ? a : b; }
void PrintLevel(TreeNode* root, int level, vector<int>& ret)
{
if (!root) { return; }
if (level == 1) { ret.push_back(root->val); return; }
PrintLevel(root->left, level - 1, ret);
PrintLevel(root->right, level - 1, ret);
}
};
int main(void)
{
TreeNode* root = new TreeNode(3,
new TreeNode(9, NULL, NULL),
new TreeNode(20,
new TreeNode(15, NULL, NULL),
new TreeNode(7, NULL, NULL)));
Solution s;
vector<vector<int> > ret = s.levelOrderBottom(root);
for (int i = 0; i < ret.size(); i++)
{
for (int j = 0; j < ret[i].size(); j++)
{
cout << ret[i][j] << " ";
}
cout << endl;
}
delete root;
return 0;
} | true |
fb480188ea36325c7d74f9213eb6954b51b4b137 | C++ | mCRL2org/mCRL2 | /libraries/data/include/mcrl2/data/exists.h | UTF-8 | 2,380 | 2.78125 | 3 | [
"BSL-1.0"
] | permissive | // Author(s): Jeroen Keiren
// Copyright: see the accompanying file COPYING or copy at
// https://github.com/mCRL2org/mCRL2/blob/master/COPYING
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
/// \file mcrl2/data/exists.h
/// \brief The class exists.
#ifndef MCRL2_DATA_EXISTS_H
#define MCRL2_DATA_EXISTS_H
#include "mcrl2/data/abstraction.h"
namespace mcrl2
{
namespace data
{
/// \brief existential quantification.
///
class exists: public abstraction
{
public:
/// Constructor.
///
/// \param[in] d An aterm.
/// \pre d has the internal structure of an abstraction.
/// \pre d is an existential quantification.
explicit exists(const aterm& d)
: abstraction(d)
{
assert(is_abstraction(d));
assert(abstraction(d).binding_operator() == exists_binder());
}
/// Constructor.
///
/// \param[in] variables A nonempty list of binding variables (objects of type variable).
/// \param[in] body The body of the exists abstraction.
/// \pre variables is not empty.
template < typename Container >
exists(const Container& variables,
const data_expression& body,
typename atermpp::enable_if_container< Container, variable >::type* = nullptr)
: abstraction(exists_binder(), variables, body)
{
assert(!variables.empty());
}
/// Move semantics
exists(const exists&) noexcept = default;
exists(exists&&) noexcept = default;
exists& operator=(const exists&) noexcept = default;
exists& operator=(exists&&) noexcept = default;
}; // class exists
template <class... ARGUMENTS>
void make_exists(atermpp::aterm& result, ARGUMENTS... arguments)
{
make_abstraction(result, exists_binder(), arguments...);
}
//--- start generated class exists ---//
// prototype declaration
std::string pp(const exists& x);
/// \\brief Outputs the object to a stream
/// \\param out An output stream
/// \\param x Object x
/// \\return The output stream
inline
std::ostream& operator<<(std::ostream& out, const exists& x)
{
return out << data::pp(x);
}
/// \\brief swap overload
inline void swap(exists& t1, exists& t2)
{
t1.swap(t2);
}
//--- end generated class exists ---//
} // namespace data
} // namespace mcrl2
#endif // MCRL2_DATA_EXISTS_H
| true |
3446680f0cb52887b787bde4814748f18216979f | C++ | mirshahzad/C-basic | /Hello World My first program/Hello World My first program/Hello World My first program.cpp | UTF-8 | 438 | 3.125 | 3 | [] | no_license | // Hello World My first program.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
using namespace std;
int main()
{
int var1, var2, result;
cout<<"Please enter the first variable:";
cin>>var1;
cout<<endl<<"Please enter the second value";
cin>>var2;
result=var1+var2;
cout<<endl<<"Result is"<<result;
cout<<"Press any key to continue....";
getchar();
return 0;
}
| true |
849a70e4f49bb0c31b44d0ed8dbc917494664a73 | C++ | WenjingWangCarrie/CST8219-CPP | /Assignment 1/Animation.cpp | UTF-8 | 4,849 | 3.5 | 4 | [] | no_license | /***************************************************************
Filename: Animation.cpp
Version: 1.0
Student Name: Wenjing Wang
Student Number: 040812907
Course Name/Number: C++ Programming CST8219
Lab Section: 303
Assignment # : Assignment 1
Assignment Name: Animation Project in C++
Due Date: November 25, 2017
Submission Date: November 24, 2017
Professor's Name: Andrew Tyler
List of Source and Header Files: Animation.cpp and Animation.h
Purpose: To write the application that holds the data of an
animation application using a forward list in dynamic
memory for its data. It can be insert,
display and delete the Frames in the Animation.
*************************************************************/
#include "Frame.h"
#include "Animation.h"
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
/*****************************************
Function Name: Animation
Purpose: To initialize the variables in the struct Animation.
Function In parameters: N/A
Function Out parameters: N/A
Version: 1.0
Student Name: Wenjing Wang
*****************************************/
Animation::Animation() {
frames = nullptr;
}
/*****************************************
Function Name: InsertFrame
Purpose: To add a new Frame to Animation at a specified position.
Function In parameters: N/A
Function Out parameters: N/A
Version: 1.0
Student Name: Wenjing Wang
*****************************************/
void Animation::InsertFrame() {
char fname[100];
Frame *iterator;
iterator = new Frame;
int size = strlen(fname) + 1; // get the length of fileName
iterator->GetfileName() = new char[size]; // to allocate memory for fileName
cout << "Insert a Frame in the Animation\n" << endl;
cout << "Please enter the Frame filename: ";
cin >> fname; // catch user entered fname
strcpy(iterator->GetfileName(), fname); // copy user entered fname into fileName
Frame *current;
current = frames; // make the current pointer points to the Animation
int counter;
int index;
if (frames == nullptr) // if list is empty, insert into the first position
{
cout << "This is the first Frame in the list" << endl;
iterator->GetpNext() = frames;
frames = iterator;
return;
}
else // there are nodes in the list, to insert at user specified position
{
counter = 0;
current = frames;
while (current != nullptr) // calculate the length of the list
{
current = current->GetpNext();
counter++;
}
current = frames;
cout << "There is " << counter << " Frame(s) in the list. Please specify the position(<= " << counter << ") to insert at: ";
cin >> index;
if (index == 0) // go to the first poisition of list
{
iterator->GetpNext() = frames;
frames = iterator;
return;
}
int counts = 0;
current = frames;
Frame *prev;
while (counts < index) {
prev = current; // reassign the location of frame
current = current->GetpNext();
counts++;
}
prev->GetpNext() = iterator; // reassign the location of frame
iterator->GetpNext() = current;
return;
}
}
/*****************************************
Function Name: DeleteFrames
Purpose: To delete all the frames in the Animation.
Function In parameters: N/A
Function Out parameters: N/A
Version: 1.0
Student Name: Wenjing Wang
*****************************************/
void Animation::DeleteFrames() {
if (frames != nullptr) {
delete this->frames;
frames = nullptr;
cout << "Delete all the Frames from the Animation" << endl;
}
}
/*****************************************
Function Name: RunFrames
Purpose: To display all the frames in the Animation to show the
list of Frame details one after another at 1 second intervals.
Function In parameters: N/A
Function Out parameters: N/A
Version: 1.0
Student Name: Wenjing Wang
*****************************************/
void Animation::RunFrames() {
int counter = 0;
time_t startsec, oldsec, newsec;
Frame* iterator = frames;
if (frames == 0) {
cout << "No frames in the animation" << endl;
return;
}
cout << "Run the Animation" << endl;
startsec = oldsec = time(nullptr);
while (iterator)
{
newsec = time(nullptr);
if (newsec > oldsec)
{
cout << "Frame #" << counter++ << ", time = " << newsec - startsec << "sec" << endl;
cout << "Image file name = " << iterator->GetfileName() << endl;
iterator = iterator->GetpNext();
oldsec = newsec;
}
}
}
/*****************************************
Function Name: ~Animation
Purpose: To cleanup all the frames in the memory of struct Animation.
Function In parameters: N/A
Function Out parameters: N/A
Version: 1.0
Student Name: Wenjing Wang
*****************************************/
Animation::~Animation() {
DeleteFrames();
} | true |
e3a6344cacc9a6bec31ce6d2131ca3031d95fdc3 | C++ | artallo/problem-solving-in-cpp | /recursive-programming/recursion-dec-to-bin/main.cpp | UTF-8 | 2,196 | 3.5625 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <windows.h>
#include <cstdlib>
#include <string>
#include <algorithm>
// Переход на кириллицу:
void cyrillic() {
// Эти строки нужны для правильного отображения кириллицы:
SetConsoleOutputCP(1251);
SetConsoleCP(1251);
// Также надо изменить шрифт в консоли на Lucida Console.
// Для замены шрифта кликаете правой кнопкой на надписи «Командная строка» окна консоли.
// В открывшемся меню выбираете «Свойства».
// В появившемся окне выбираете вкладку «Шрифт» и там выбираете «Lucida Console».
}
// Рекурсивная функцию для перевода числа из десятичной системы счисления в двоичную:
std::string dec2bin(int num, std::string result) {
if (num > 0) { // пока десятичное число больше нуля:
// Делим число на 2.
// Если делится то добавляем к строке '0', а если не делится то добавляем '1'.
result.append(num % 2 == 0 ? "0" : "1");
return dec2bin(num / 2, result); // делим число на 2 и снова вызываем функцию dec2bin.
} else {
// Чтобы получить правильный результат, нужно все записанные выше нули и единицы представить в обратном порядке:
std::reverse(result.begin(), result.end());
return result;
}
}
int main(int argc, char** argv) {
int N; // число в десятичной системе счисления.
cyrillic();
std::cout << "Введите число в десятичной системе счисления: ";
std::cin >> N;
std::cout << "Число " << N << " в двоичной системе счисления = " << dec2bin(N, "") << std::endl;
system("pause");
return 0;
}
| true |
1af5b0a16efad6f5e132ed172ceed1b0e8a32a18 | C++ | gagan86nagpal/Interview-prep | /Array Rotation Inplace/main.cpp | UTF-8 | 872 | 3.390625 | 3 | [] | no_license | #include <iostream>
using namespace std;
// We are doing a[i] = a[i+d] , and incrementing i by d
// Here , we can get stuck in cycles
// THere are total g = gcd(n,d) cycles , hence repeating this procedure for (g-1) values of length each cycle gives
// us rotated array
// We are making this so much complex because of Linear time and Constant space
int gcd(int a,int b)
{
if(b==0)
return a;
return gcd(b,a%b);
}
int a[102];
void rotateByN(int si,int n,int d,int g)
{
int x =a[si];
int i=si;
int cnt=n/g -1;
while(cnt--)
{
a[i]=a[ (i+d)%n ];
i = (i+d)%n;
}
a[i]=x;
}
int main()
{
int n,d;
cin>>n>>d;
for(int i=0;i<n;i++)
cin>>a[i];
int g = gcd(n,d);
for(int i=0;i<g;i++)
rotateByN(i,n,d,g);
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<"\n";
return 0;
}
| true |
904d783a4d0520f9e3ebfe76b368500ffc7a7560 | C++ | scottlafetra/AlephEngine | /AlephEngine/Source/Rendering/MeshRenderer.inl | UTF-8 | 1,259 | 2.53125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "gmtl/Generate.h"
#include "../Core/Utility.h"
using namespace AlephEngine;
template <class T>
MeshRenderer<T>::MeshRenderer( AlephEngine::Entity* entity )
: Renderer( entity ), hasTexture( false )
{
shaderProgram = Shaders::GetGLProgram<T>();
}
template <class T>
void MeshRenderer<T>::SetVertices( const GLenum renderMode, GLint vertexCount, const GLfloat* vertices )
{
// Init render variables
this->renderMode = renderMode;
this->vertexCount = vertexCount;
this->vertices = new GLfloat[ vertexCount * ( T::GetVertexSize() / sizeof(float) ) ];
memcpy( this->vertices, vertices, T::GetVertexSize() * vertexCount );
vertexBuffer = T::AttachVertexArray( vertexCount, MeshRenderer<T>::vertices );
}
template <class T>
void MeshRenderer<T>::SetTexture( GLFWimage* texture, GLenum wrapMode )
{
hasTexture = true;
texureBuffer = T::AttachTexture( texture, wrapMode );
}
template <class T>
void MeshRenderer<T>::Render( gmtl::Matrix<float, 4, 4> view )
{
// Attach things
T::RebindVertexArray( vertexBuffer );
T::RebindTexture( texureBuffer, texureWrapMode );
glUseProgram( shaderProgram );
glUniformMatrix4fv( T::mvp_location, 1, GL_FALSE, (const GLfloat*) view.mData );
glDrawArrays( renderMode, 0, vertexCount );
} | true |
95c9b2d6b06c2665b501bc738e90be05d7b7cfc5 | C++ | kurogen/learning | /iguania/07_iguania/07_iguania/07_iguania.cpp | WINDOWS-1251 | 959 | 3.640625 | 4 | [] | no_license | // 07_iguania.cpp : Defines the entry point for the console application.
// if - else if
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int value;
cout << "Enter number: " << endl;
cin >> value;
if (value > 0)
{
cout << "Number positive" << endl;
cout << "You have entered number: " << value << endl;
if (value >= 100)
cout << "This number is more or equally 100" << endl;
else
cout << "This number is less 100" << endl;
}
else if (value == 0)
{
cout << "The number is not neither positive, nor negative" << endl;
cout << "You have entered number: " << value << endl;
}
else
{
cout << "Number negative" << endl;
cout << "You have entered number: " << value << endl;
if (value >= -100)
cout << "This number is more or equally -100" << endl;
else
cout << "This number is less -100" << endl;
}
system("PAUSE");
return 0;
} | true |
23b02f81e9b3555a820e63dffd665601ce6aeb23 | C++ | Juank23/DC-motor-positional-control | /Working_PID_Posi.ino | UTF-8 | 3,518 | 2.515625 | 3 | [
"Beerware"
] | permissive | #include <PID_v1.h>
int val;
int encoder0PinA = 2; //interrupt pin 0
int encoder0PinB = 3; //interrrupt pin 1
int encoder0Pos = 0; //initial encoder count on reset
int encoder0PinALast = LOW; //assume leading signal is low
int n = LOW;
int Trgt = 512; //Setpoint range
int STBY = 10; //standby
int AIN1 = 5; //Direction
int AIN2 = 6; //Direction
int Speed = 255;
int Set = A0; //analog pin for setpoint potentiometer
double kp = 5 , ki = 1 , kd = 0.01; // modify for optimal performance
double input = 0, output = 0, setpoint = 0;
PID Plant(&input, &output, &setpoint, kp, ki, kd, DIRECT);
void setup() { //Straightforward setup, self explanatory
pinMode (encoder0PinA,INPUT); //encoder phases need to be inputs to sense
pinMode (encoder0PinB,INPUT);
attachInterrupt(0, doEncoderA, CHANGE); //State change triggers interrupt to prevent loss of counts
attachInterrupt(1, doEncoderB, CHANGE);
Serial.begin (115200); //fast serial to speed loop
pinMode(AIN1, OUTPUT);
pinMode(AIN2, OUTPUT);
pinMode(Set, INPUT);
TCCR0B = (TCCR0B & 0b11111000) | 0x02;
Plant.SetMode(AUTOMATIC);
Plant.SetSampleTime(1);
Plant.SetOutputLimits(-255, 255);
}
/*void move_dir(int dir) { //Add functionality for telling motor to move at full speed in direction
move(1, dir); //motor 1, full speed
delay(1);
stop();
}*/
void loop() {
int Target = map(analogRead(Set),0, 1024, 0, Trgt); //map analog read value to range of counts 0-300
setpoint = Target;
input = encoder0Pos;
Plant.Compute();
pwmOut(output);
Serial.print(Target);// Prints target count
Serial.print(" ");
Serial.print(encoder0Pos); //Prints actual count
Serial.print(" ");
Serial.print(setpoint - input);
Serial.print(" ");
Serial.println(output);
}
void pwmOut(int out) { // to H-Bridge board
if (out > 0) {
analogWrite(AIN1, out); // drive motor CW
analogWrite(AIN2, 0);
}
else {
analogWrite(AIN1, 0);
analogWrite(AIN2, abs(out)); // drive motor CCW
}
}
void doEncoderA(){
// look for a low-to-high on channel A
if (digitalRead(encoder0PinA) == HIGH) {
// check channel B to see which way encoder is turning
if (digitalRead(encoder0PinB) == LOW) {
encoder0Pos = encoder0Pos + 1; // CW
}
else {
encoder0Pos = encoder0Pos - 1; // CCW
}
}
else // must be a high-to-low edge on channel A
{
// check channel B to see which way encoder is turning
if (digitalRead(encoder0PinB) == HIGH) {
encoder0Pos = encoder0Pos + 1; // CW
}
else {
encoder0Pos = encoder0Pos - 1; // CCW
}
}
//Serial.println (encoder0Pos, DEC);
// use for debugging - remember to comment out
}
void doEncoderB(){
// look for a low-to-high on channel B
if (digitalRead(encoder0PinB) == HIGH) {
// check channel A to see which way encoder is turning
if (digitalRead(encoder0PinA) == HIGH) {
encoder0Pos = encoder0Pos + 1; // CW
}
else {
encoder0Pos = encoder0Pos - 1; // CCW
}
}
// Look for a high-to-low on channel B
else {
// check channel B to see which way encoder is turning
if (digitalRead(encoder0PinA) == LOW) {
encoder0Pos = encoder0Pos + 1; // CW
}
else {
encoder0Pos = encoder0Pos - 1; // CCW
}
}
}
| true |
5f157563960c92c877c4e3e0b984458ecf295c34 | C++ | 116dariya/10 | /d.cpp | UTF-8 | 499 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <set>
using namespace std;
int main(){
set<char> s;
for(int i = 0; i < 8; ++i){
char c = char(i + 48);
s.insert(c);
}
string line;
cin >> line;
bool ok = true;
if(line[0] == '0'){
ok= false;
}
else{
for(int i = 0; i < line.length(); ++i){
char c = line[i];
if(s.find(c) == s.end()){
ok = false;
break;
}
}
}
if(ok == true){
cout << "YES";
}else{
cout << "NO";
}
return 0;
} | true |
ff46236c416c3dada4df65747ab5dd96cbe78974 | C++ | CrazyCodersCollective/EcoSim | /EcoSimGame/Source/StateNode.cpp | UTF-8 | 960 | 2.84375 | 3 | [] | no_license | #include "StateNode.h"
StateNode::StateNode()
{
}
StateNode::StateNode(PointerBag* pointerbag)
{
this->pointerBag = pointerbag;
this->master = this;
this->renderer = pointerbag->renderer;
}
StateNode::~StateNode()
{
}
void StateNode::render() {
for (int i = 0; i < children.size(); i++) {
states[i]->render();
}
}
void StateNode::SetState(int state) {
if (state < states.size()) {
this->StateNow = states[state];
}
else { printf("index out of range"); }
}
void StateNode::AddChild(RootNode* node) {
node->screen = this;
node->master = this;
node->renderer = renderer;
node->pointerbag = pointerBag;
states.push_back(node);//add sort insertion sort by z
}
bool StateNode::ChangeState(std::string& state) {
for (int i = 0; i < states.size(); i++)
{
if (states[i]->State == state)
{
if (states[i]->init) {
states[i]->StartUp();
states[i]->init = false;
}
SetState(i);
return true;
}
}
return false;
} | true |
af57d6e79c0bdfd41a73ca45069774066c057161 | C++ | chadaustin/renaissance | /ren2/ren/Global.h | UTF-8 | 662 | 2.75 | 3 | [
"MIT"
] | permissive | #pragma once
#include <memory>
#include <stdexcept>
#define REN_PTR(C) typedef std::shared_ptr<class C> C##Ptr
namespace ren {
inline void verify(bool condition) {
if (!condition) {
int* p = 0;
*p = 0;
fprintf(stderr, "verify failed\n");
throw std::runtime_error("verify failed");
}
}
template<typename T, typename U>
bool check_type(U* u) {
return (!u || dynamic_cast<T>(u) ? true : false);
}
template<typename T, typename U>
T checked_cast(U* u) {
verify(check_type<T, U>(u));
return static_cast<T>(u);
}
}
| true |
0d88ad45f6f55023f6474fd2ceadb20bf1cb2551 | C++ | alex-peng/AnimVis | /object.h | UTF-8 | 846 | 2.578125 | 3 | [] | no_license | #ifndef _OBJECT_H_
#define _OBJECT_H_
namespace AMT
{
typedef enum {
WIREFRAME = 0,
GOURAUD,
TEXTURED
} TRenderMode;
class CBoundingBox
{
public:
float center[3];
float size;
CBoundingBox() : size(0.0f) {};
};
class CRenderObject
{
public:
bool m_visiable;
bool m_VisiableTest;
bool m_ShaderReady;
float alpha; // For transparent display
float beginx, beginy; /* position of mouse */
float position[3];
float m_VisibiltyTime;
float quat[4];
CBoundingBox boundingBox;
CRenderObject( bool _visiable = true, float _alpha = 1.0f );
void ResetPosition();
virtual void draw() = 0;
virtual void destroyMyself() = 0;
virtual unsigned int getFaceNumber() = 0;
virtual void ChangeRenderMode(TRenderMode rm ) = 0;
virtual void SetShader() = 0;
virtual unsigned int getVisFaceNumber() { return getFaceNumber(); }
};
}
#endif | true |
84c4e023b24d2a28d97a21110d1bf49f75588b05 | C++ | GazRobinson/SFML_Gaz | /GityGenerator/GityGenerator/GSprite.h | UTF-8 | 1,409 | 2.75 | 3 | [] | no_license | #pragma once
#include <SFML\Graphics.hpp>
#include "Input.h"
#include "structs.h"
class GSprite : public sf::RectangleShape
{
public:
GSprite();
~GSprite();
virtual void Update(float dt);
sf::Vector2f GetLastPosition() { return lastPosition; };
void SetVelocity(sf::Vector2f vel);
void SetVelocity(float vx, float vy);
sf::Vector2f GetVelocity();
void SetCollider(bool colliderActive) { collider = colliderActive; };
void SetCollisionBox(float x, float y, float w, float h) { SetCollisionBox(sf::FloatRect(x, y, w, h)); };
void SetCollisionBox(sf::FloatRect newSize) { collisionBox = newSize; };
sf::FloatRect GetCollisionBox() {
return sf::FloatRect(collisionBox.left + getPosition().x, collisionBox.top + getPosition().y, collisionBox.width, collisionBox.height);
};
bool IsCollider() { return collider; };
virtual void CollisionResponse(GSprite* sp);
void SetInput(Input* in) { input = in; };
Line GetEdge(int edge);
void SetGravity(bool active) { useGravity = active; };
protected:
sf::Vector2f lastPosition;
sf::Vector2f velocity;
bool active;
sf::FloatRect collisionBox;
bool collider;
bool useGravity = true;
Input* input;
sf::Vector2f GetCenter() { return getPosition(); };
sf::Vector2f GetColCenter() { return sf::Vector2f(GetCollisionBox().left, GetCollisionBox().top) + sf::Vector2f(GetCollisionBox().width*0.5f, GetCollisionBox().height * 0.5f); };
};
| true |
6a8c139706a7e27b605c88ec129e4f074eb4f0da | C++ | kristenlau8/IoT-Light | /led/src/led.ino | UTF-8 | 5,081 | 2.921875 | 3 | [] | no_license | /*
* Project led
* Description:
* Author:
* Date:
*/
//citation: I followed some of the code from here: https://www.hackster.io/brandonsatrom/using-nativescript-to-build-particle-powered-mobile-apps-ea6e99
LEDStatus blinkLED;
int red = 255;
int green = 255;
int blue = 255;
int fadered = 0;
int fadegreen = 0;
int fadeblue = 0;
bool blinkEnabled = false;
int blink = 0;
//timers for when to turn on and off the light
Timer timerChange(1000, timerChangeHelp, TRUE);
Timer timerFade(1000, timerFadeHelp, TRUE);
void setup() {
// Put initialization like pinMode and begin functions here.
Serial.begin(9600);
blinkLED.setActive(true);
blinkLED.off();
//all my particle functions!!
Particle.function("lighton", lightOn);
Particle.function("lightoff", lightOff);
Particle.function("setred", setRed);
Particle.function("setgreen", setGreen);
Particle.function("setblue", setBlue);
Particle.function("fadered", setFadeRed);
Particle.function("fadegreen", setFadeGreen);
Particle.function("fadeblue", setFadeBlue);
Particle.function("fade", fade);
Particle.function("fadeoff", fadeOff);
Particle.function("timerchange", timerChangeFunc);
Particle.function("timerfade", timerFadeFunc);
Particle.function("setblink", setBlink);
Particle.function("setBlinkTime",setBlinkTime);
}
// loop() runs over and over again, as quickly as it can execute.
void loop() {
// The core of your code will likely live here.
}
//turns the light on to a specific color
int lightOn(String arg) {
// Set to false in case we're switching between modes
//RGB.control(false);
// Convert the R, G, B values to hex with some fancy bit shifting
long RGBHex = (red << 16) | (green << 8) | blue;
// Set the color, pattern and speed and activate our LED
blinkLED.on();
blinkLED.setColor(RGBHex);
if (blinkEnabled) {
blinkLED.setPattern(LED_PATTERN_BLINK);
if(blink==0) {
blinkLED.setSpeed(LED_SPEED_SLOW);
}
else if (blink==1) {
blinkLED.setSpeed(LED_SPEED_NORMAL);
}
else if (blink==2) {
blinkLED.setSpeed(LED_SPEED_FAST);
}
}
else {
blinkLED.setPattern(LED_PATTERN_SOLID);
}
return 1;
}
//turns the light off
int lightOff(String arg) {
blinkLED.off();
return 1;
}
//sets the red value
int setRed(String arg) {
red = atoi(arg);
return 1;
}
//sets the blue value
int setBlue(String arg) {
blue = atoi(arg);
return 1;
}
//sets the green value
int setGreen(String arg) {
green = atoi(arg);
return 1;
}
//sets the red value to fade to
int setFadeRed(String arg) {
fadered = atoi(arg);
return 1;
}
//sets the blue value to fade to
int setFadeBlue(String arg) {
fadeblue = atoi(arg);
return 1;
}
//sets the green value to fade to
int setFadeGreen(String arg) {
fadegreen = atoi(arg);
return 1;
}
//fades the light! Basically it gets as close as it can but because of ints may never get to the exact number from before.
int fade(String arg) {
int redDelta = (fadered-red)/50.0;
int goalRed = red + (redDelta*50);
int greenDelta = (fadegreen-green)/50.0;
int goalGreen = green + (greenDelta*50);
int blueDelta = (fadeblue-blue)/50.0;
int goalBlue = blue+(blueDelta*50);
while(red!=goalRed | blue!=goalBlue | green!=goalGreen) {
red = red+redDelta;
green = green+greenDelta;
blue = blue+blueDelta;
lightOn("");
Serial.println("r: "+String(red)+" g: "+String(green)+" b: "+String(blue));
delay(100);
}
if(red==0&&blue==0&&green==0) {
red = 255;
blue = 255;
green = 255;
}
return 1;
}
//fades the light off - this one will go 100% of the way off no matter what (always exactly reaches goal, which makes it different from the normal fade)
int fadeOff(String arg) {
float redDelta = (0-red)/50.0;
float greenDelta = (0-green)/50.0;
float blueDelta = (0-blue)/50.0;
while(red!=0 | blue!=0 | green!=0) {
if (red+redDelta<=0) {
red = 0;
}
else {
red = red+redDelta;
}
if (green +greenDelta<=0) {
green = 0;
}
else {
green = green+greenDelta;
}
if(blue+blueDelta<=0) {
blue=0;
}
else {
blue = blue+blueDelta;
}
lightOn("");
Serial.println("r: "+String(red)+" g: "+String(green)+" b: "+String(blue));
delay(100);
}
red = 255;
blue = 255;
green = 255;
return 1;
}
//starts the timer to change the light
int timerChangeFunc(String arg) {
int interval = atoi(arg);
timerChange.changePeriod(interval*1000);
}
//helper function that is called from the change light timer
void timerChangeHelp() {
lightOn("");
}
//starts the timer to fade the light
int timerFadeFunc(String arg) {
int interval = atoi(arg);
timerFade.changePeriod(interval*1000);
}
//helper function called from fade light timer
void timerFadeHelp() {
fade("");
}
//enables and disables blinking
int setBlink(String arg) {
if (arg=="true") {
blinkEnabled = true;
lightOn("");
}
else {
blinkEnabled = false;
lightOn("");
}
}
//sets the speed of the blinking
int setBlinkTime(String arg) {
blink = atoi(arg);
lightOn("");
}
| true |
c3b6f3fc35d47cca0e8460eeec64ed6309c79bb2 | C++ | mistervunguyen/starting-out-with-c-plus-plus-early-objects-solutions | /Programming Challenges/Chapter18/18_13.cpp | UTF-8 | 1,273 | 4.3125 | 4 | [] | no_license | // Chapter 18, Assignment 13, Stack-Based Fibonacci Function
#include <cstdlib>
#include <stack>
#include <iostream>
using namespace std;
// Prototype
int fibonacci(int n);
int main ( )
{
cout << "Enter a positive integer: ";
int number;
cin >> number;
cout << "The first " << number << " terms of the Fibonacci sequence are: \n";
for (int k = 0; k <= number; k++)
{
cout << fibonacci(k) << " " ;
}
return 0;
}
//**************************************************
// Computes the nth term of the Fibonacci sequence *
//**************************************************
int fibonacci(int n)
{
stack<int> fibStack;
// Stack the first two terms of the Fibonacci sequence
fibStack.push(1);
fibStack.push(1);
// Stack the rest of the terms from 2..n
for (int k = 2; k <= n; k++)
{
// pop last two elements off the stack
int t1 = fibStack.top();
fibStack.pop();
int t2 = fibStack.top();
fibStack.pop();
// put the first element popped back on the stack
fibStack.push(t1);
// push the sum of t1 and t1 onto the stack
fibStack.push(t1+t2);
}
// return top of the stack
return fibStack.top();
}
| true |
b34164908f21417eea66ea07b6e919359bd75b52 | C++ | samkimuel/problem-solving | /BaekjoonOJ/10869.cpp | UTF-8 | 381 | 3.09375 | 3 | [] | no_license | /**
* @file 10869.cpp
* @brief 사칙연산
* @author Sam Kim (samkim2626@gmail.com)
*/
#include <iostream>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int a, b;
cin >> a >> b;
cout << a + b << '\n';
cout << a - b << '\n';
cout << a * b << '\n';
cout << a / b << '\n';
cout << a % b << '\n';
return 0;
} | true |
f836ae9c64d4698563b77ce97ee2c9838240800a | C++ | Seiseigy/taller-2-paralela | /src/producto.cpp | UTF-8 | 253 | 2.703125 | 3 | [] | no_license | #include "../include/producto.h"
Producto::Producto(long _barCode, std::string _name, int _volume){
barCode = _barCode;
name = _name;
volume = _volume;
}
void Producto::addQuantity(int quantity){
this->count = this->count + quantity;
} | true |
15d32d904d03bab2d79fefb69a2d0e2a44f6f603 | C++ | neortls007idev/guildhall | /LD45/Code/Game/Tile.hpp | UTF-8 | 524 | 2.546875 | 3 | [] | no_license | #pragma once
#include "Engine/Math/IntVec2.hpp"
#include "Engine/Primitives/AABB2.hpp"
enum Tiletype
{
TILE_TYPE_INVALID = -1,
TILE_TYPE_GRASS = 0,
TILE_TYPE_WATER = 2,
TILE_TYPE_LAVA = 3,
NUM_TILE_TYPES = 4
};
struct Tile
{
public:
Tile( IntVec2 tileCoordinates, Tiletype type );
~Tile() {};
void Update( float deltaSeconds );
void Render() const;
int GetTileID( const Tile* tile ) const;
//int SetTileID( const Tile* tile );
public:
IntVec2 m_tileCoords;
Tiletype m_type = TILE_TYPE_INVALID;
}; | true |
cb7e5249c414bef1d7cdcb71cb634122f125a944 | C++ | thomasdelmoro21/laboratorio_di_programmazione | /test/UnreadMessageNotifierTest.cpp | UTF-8 | 779 | 2.609375 | 3 | [] | no_license | //
// Created by thomas on 18/09/20.
//
#include "gtest/gtest.h"
#include "../UnreadMessageNotifier.h"
#include "../Chat.h"
TEST(UnreadMessageNotifier, draw) {
User emma("Emma");
User chiara("Chiara");
User carlo("Carlo");
Chat b(emma, carlo);
Chat c(emma, chiara);
std::shared_ptr<Chat> ptrB = std::make_shared<Chat>(b);
std::shared_ptr<Chat> ptrC = std::make_shared<Chat>(c);
Message msg1(chiara, emma, "ciao");
Message msg2(chiara, emma, "Come stai?");
Message msg3(emma, chiara, "bene");
Message msg4(carlo, emma, "ciaoo");
emma.addChat(ptrB);
emma.addChat(ptrC);
ptrC->addMessage(msg1);
ptrC->addMessage(msg2);
ptrC->addMessage(msg3);
ptrB->addMessage(msg4);
ASSERT_EQ(emma.getUnreadMessages(), 3);
} | true |
a931c95d455c52676a6c801b43d159c09f6354e1 | C++ | avrdan/CyborgBattle | /CyborgBattle/Animation.h | UTF-8 | 445 | 2.65625 | 3 | [] | no_license | #pragma once
#include "Frame.h"
class Animation
{
public:
Animation(const std::string& name = "");
~Animation() {}
int getNextFrameNumber(int frameNumber) const;
Frame* getNextFrame(Frame* frame);
int getEndFrameNumber() const;
Frame* getFrame(int frameNumber);
const std::string& getName() const;
void loadAnimation(std::ifstream& file, std::list<DataGroupType>& groupTypes);
private:
std::string name;
std::list<Frame> frames;
};
| true |
08a71a0c6dce7df4b53b6167316089b5734ee1b5 | C++ | vanvule/ImageProcessing | /src/Lab3/Convolution.cpp | UTF-8 | 2,125 | 3.015625 | 3 | [] | no_license | #include "stdafx.h"
#include "Convolution.h"
Convolution::Convolution()
{
this->_kernel;
this->_kernelHeight = 0;
this->_kernelWidth = 0;
}
Convolution::~Convolution()
{
this->_kernel.clear();
this->_kernelHeight = 0;
this->_kernelWidth = 0;
}
vector<Kernel> Convolution::GetKernel()
{
return this->_kernel;
}
void Convolution::SetKernel(vector<float> kernel, int kWidth, int kHeight)
{//
int indexX[9] = { -1,-1,-1,0,0,0,1,1,1 };
int indexY[9] = { -1,0,1,-1,0,1,-1,0,1 };
for (int i = 0; i < kernel.size(); i++) {
Kernel K;
K.x = indexX[i];
K.y = indexY[i];
K.data = kernel[i];
this->_kernel.push_back(K);
}
this->_kernelHeight = kHeight;
this->_kernelWidth = kWidth;
}
int Convolution::DoConvolution(const Mat& sourceImage, Mat& destinationImage)
{
//link: https://www.stdio.vn/articles/phep-tich-chap-trong-xu-ly-anh-convolution-386
Mat Image = sourceImage;
if (Image.channels() == 1) {
int row = Image.rows;
int col = Image.cols;
// Tạo matrix để lưu giá trị pixel sau khi thực hiện tích chập.
destinationImage.create(Size(col, row), CV_8UC1);
for (int i = 0; i < row; i++)
{
// Lấy địa chỉ dòng của ảnh đích, để lưu kết quả vào.
uchar* data = destinationImage.ptr<uchar>(i);
for (int j = 0; j < col; j++)
{
// Lưu tổng giá trị độ xám của vùng ảnh tương ứng với kernel
int g_val = 0;
// Duyệt mask, giá trị pixel đích là tổ hợp tuyến tính của mask với ảnh nguồn.
for (int ii = 0; ii < _kernel.size(); ii++)
{
//_kernelIndex: mảng chỉ số truy cập nhanh
int index_r = i - _kernel[ii].x;
// Với pixel nằm ngoài biên, bỏ qua.
if (index_r < 0 || index_r > row - 1)
continue;
int index_c = j - _kernel[ii].y;
if (index_c < 0 || index_c > col - 1)
continue;
g_val += _kernel[ii].data * sourceImage.at<uchar>(index_r, index_c);
}
// Gán giá trị cho matrix đích.
data[j] = g_val;
}
}
return 1;
}
} | true |
05c6288e8c5a35e22760f24df64b948d2a1191b2 | C++ | ku3i/flatcat | /src/common/basic.cpp | UTF-8 | 2,797 | 2.921875 | 3 | [] | no_license | /* basic.cpp */
#include "basic.h"
#include <algorithm>
FILE*
open_file(const char* mode, const char* format, ...)
{
char filename[1024];
va_list args;
va_start(args, format);
vsnprintf(filename, 1024, format, args);
va_end(args);
FILE * fd = fopen(filename, mode);
if (NULL == fd)
{
perror("Error");
err_msg(__FILE__, __LINE__, "could not open file %s in mode %s.", filename, mode);
}
return fd;
}
namespace basic {
std::string
make_directory(const char *format, ...)
{
char foldername[256];
va_list args;
va_start(args, format);
vsnprintf(foldername, 256, format, args);
va_end(args);
int md = mkdir(foldername, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if (!md) sts_msg("created folder %s", foldername);
else if (errno != EEXIST) err_msg(__FILE__, __LINE__, "could not create folder %s.\n %s\n", foldername, strerror(errno));
return foldername;
}
Filelist list_directory(const char* target_dir, const char* filter)
{
const unsigned max_files = 1024;
std::vector<std::string> files_in_directory;
struct dirent *epdf;
DIR *dpdf;
if (0 == strcmp(target_dir,""))
dpdf = opendir("./");
else
dpdf = opendir(target_dir);
if (dpdf != NULL) {
while ((epdf = readdir(dpdf)) and (files_in_directory.size() < max_files)) {
if (strcmp(epdf->d_name, ".") and strcmp(epdf->d_name, "..") and (nullptr != strstr(epdf->d_name, filter)))
files_in_directory.emplace_back(epdf->d_name);
}
if (files_in_directory.size() > 1)
std::sort(files_in_directory.begin(), files_in_directory.end());
sts_msg("Read %u files in directory %s", files_in_directory.size(), target_dir);
for (std::size_t i = 0; i < std::min(std::size_t{10}, files_in_directory.size()); ++i)
sts_msg("\t%s", files_in_directory[i].c_str());
if (files_in_directory.size()>10)
sts_msg("\t...truncated.");
} else err_msg(__FILE__, __LINE__, "Could not open directory %s", target_dir);
return files_in_directory;
}
std::size_t get_file_size(FILE* fd)
{
// obtain file size
if (fd == nullptr) return 0;
fseek(fd, 0, SEEK_END);
long int file_size = ftell(fd);
rewind(fd);
return (file_size > 0) ? file_size : 0;
}
std::string get_timestamp(void) {
time_t t0 = time(NULL); // initialize time
struct tm * timeinfo = localtime(&t0); // get time info
char timestamp[256];
snprintf(
timestamp, 256, "%02d%02d%02d%02d%02d%02d",
timeinfo->tm_year-100, timeinfo->tm_mon + 1,
timeinfo->tm_mday, timeinfo->tm_hour,
timeinfo->tm_min, timeinfo->tm_sec
);
return timestamp;
}
} /* namespace basic */
| true |
21665136293201cc042be335ff049afa56c7ad6f | C++ | uvbs/GameProject | /libEngine/SList.h | UTF-8 | 2,540 | 3.453125 | 3 | [] | no_license | #ifndef SList_h__
#define SList_h__
#include <cassert>
template <class T>
class SList
{
struct Node;
public:
SList();
~SList();
int size() const { return mNum; }
bool empty() const { return mFirst != 0; }
void push_front( T const& val );
void push_back( T const& val );
T const& front() const { return mFirst->data; }
T& front() { return mFirst->data; }
T const& back() const { return mLast->data; }
T& back() { return mLast->data; }
void inverse();
void rotateFront();
void rotateBack();
public:
class Iterator
{
public:
Iterator(const SList&l):mCur( l.mFirst ){};
bool haveMore() const { return mCur != 0; }
T& getValue(){ assert( mCur ); return mCur->data; }
void next(){ mCur = mCur->link; }
private:
Node* mCur;//points to a node in list
};
Iterator getIterator(){ return Iterator( *this ); }
private:
Node* buyNode( T const& val ){ return new T( val ); }
struct Node
{
Node( T const& val ):data( val ){}
T data;
Node* link;
};
Node* getPrevNode( Node* node )
{
assert( node != mFirst );
Node* result = mFirst;
for(;;)
{
if ( result->link == node )
return result;
result = result->link;
}
assert( 0 );
return 0;
}
int mNum;
Node* mFirst;
Node* mLast;
};
template <class T>
SList<T>::SList()
{
mFirst = 0;
mLast = 0;
mNum = 0;
}
template <class T>
SList<T>::~SList()
{
Node* next;
for(;mFirst;mFirst = next)
{
next = mFirst->link;
delete mFirst;
}
}
template <class T>
void SList<T>::push_front( T const& val )
{
Node* newnode = buyNode( val );
++mNum;
if( mFirst )
{
newnode->link = mFirst;
mFirst = newnode;
}
else
{
mFirst = mLast = newnode;
}
}
template <class T>
void SList<T>::push_back( T const& val )
{
Node* newnode = buyNode( val );
newnode->link = 0;
++mNum;
if( mLast )
{
mLast->link = newnode;
mLast = newnode;
}
else
{
mFirst = mLast = newnode;
}
}
template <class T>
void SList<T>::inverse()
{
Node* p = mFirst;
Node* q = 0;
while(p)
{
Node* r = q;
q = p;
p = p->link;
q->link = r;
}
mFirst = q;
}
template <class T>
void SList<T>::rotateFront()
{
if ( mFirst == mLast )
return;
Node* node = mFirst;
mFirst = mFirst->link;
mLast->link = node;
mLast = node;
mLast->link = 0;
}
template <class T>
void SList<T>::rotateBack()
{
if ( mFirst == mLast )
return;
Node* node = getPrevNode( mLast );
mLast->link = mFirst;
mFirst = mLast;
mLast = node;
mLast->link = 0;
}
#endif // SList_h__
| true |
2465ba7fa4316f61b8d55a4190292a264fe1927e | C++ | alexandraback/datacollection | /solutions_1482494_1/C++/ckebabo/b.cc | UTF-8 | 1,332 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <vector>
#include <utility>
#include <set>
using namespace std;
int foo(vector<pair<int,int> > &v) {
int star = 0;
int cnt;
int a[1003] = {0,};
int aa = 0;
bool f;
sort(v.begin(), v.end(), greater<pair<int,int> >());
for(cnt=0;;cnt++) {
f = false;
// find level-2
for(int i=0;i<v.size();i++) {
if(a[i]<2 && star >= v[i].second) {
star += (a[i] ? 1 : 2);
a[i] = 2;
aa++;
if(aa == v.size()) return cnt+1;
f = true;
break;
}
}
if(f==true) continue;
f = false;
for(int i=0;i<v.size();i++) {
if(a[i]==0 && star >= v[i].first) {
star += 1;
a[i] = 1;
f = true;
break;
}
}
if(f==false) return -1;
}
return cnt;
}
int main() {
int T;
cin >> T;
for(int cs=1;cs<=T;cs++) {
int N;
cin >> N;
vector<pair<int,int> > v(N);
for(int i=0;i<N;i++) cin >> v[i].first >> v[i].second;
int ret = foo(v);
if(ret < 0) printf("Case #%d: Too Bad\n", cs);
else printf("Case #%d: %d\n", cs, ret);
}
return 0;
}
| true |
cfdd1569e224c7334ab04876a2b18b005c537290 | C++ | ecubillanleon/Simulacion | /Simulador.cpp | UTF-8 | 6,667 | 3.015625 | 3 | [] | no_license | #include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char nombre[20];
char apellido[20];
int cedula;
int activo;
int edad;
}registro;
#define TAMANO_REGISTRO sizeof(registro)
#define NOMBRE_ARCHIVO "archi.txt"
void v_inicializar(FILE *fp, char *c_archivo)
{
fp=fopen(c_archivo,"rb+");
if(fp==NULL)
printf("\n Error: Al abrir el archivo ");
fclose(fp);
fp=fopen(c_archivo,"wb+");
if(fp==NULL)
printf("\n Error: Al abrir el archivo ");
printf("\n Archivo Abierto ");
}
int i_buscar (FILE *fp, int i_clave, registro *r_registro)
{
registro r_reg;
if(fp==NULL)
return -1;
fseek(fp,0,SEEK_SET);
while (fread(&r_reg,TAMANO_REGISTRO,1,fp))
{
if(i_clave==r_reg.cedula && r_reg.activo==1)
{
strcpy(r_registro->nombre,r_reg.nombre);
strcpy(r_registro->apellido,r_reg.apellido);
//r_registro->edad=r_reg.edad;
r_registro->cedula=r_reg.cedula;
r_registro->activo=r_reg.activo;
fseek(fp,-TAMANO_REGISTRO,SEEK_CUR);
return 1;
}
}
return 0;
}
void v_agregar(FILE *fp)
{
if(fp==NULL)
printf("\n Error: ");
int n;
int i_clave;
char nombre[30];
char apellido[30];
int cedula;
//int edad;
registro r_registro;
printf("\n Cedula : ");
scanf("%d",&i_clave);
n=i_buscar(fp,i_clave,&r_registro);
printf(" %d ",n);
if(n==0)
{
printf("\n\n Nombre: ");
scanf("%s",nombre);
printf(" Apellido: ");
scanf("%s",apellido);
//printf(" Edad: ");
//scanf("%d",&edad);
strcpy(r_registro.nombre,nombre);
strcpy(r_registro.apellido,apellido);
//r_registro.edad = edad;
r_registro.cedula = i_clave;
r_registro.activo = 1;
fseek(fp,0,SEEK_END);
fwrite(&r_registro,TAMANO_REGISTRO,1,fp);
printf(" Activo: %d ",r_registro.activo);
printf("\n Registro agregado");
}
if(n==1)
{
printf("\n\n Error: Cedula Registrada ");
}
}
void v_imprimir(FILE *fp)
{
if(fp==NULL)
printf("\n Error: ");
registro r_registro;
printf("\nActivo \t\t Cedula \t\tApellido \t\t Nombre ");//\tEdad");
fseek(fp,0,SEEK_SET);
while(fread(&r_registro,TAMANO_REGISTRO,1,fp))
{
if(r_registro.activo == 1)
{
printf("\n %d",r_registro.activo);
printf("\t\t%d",r_registro.cedula);
printf("\t\t%s",r_registro.apellido);
printf("\t\t%s",r_registro.nombre);
//printf("\t\t%d",r_registro.edad);
}
}
}
int i_modificar(FILE *fp, int i_clave)
{
if(fp==NULL)
printf("\n Error: ");
int n;
registro r_registro;
n=i_buscar(fp,i_clave,&r_registro);
printf(" %d ",n);
if(n==0)
{
printf("\n\n Registro No Encontrado ");
return 0;
}
if(n==1)
{
printf("\n\n Nombre: ");
scanf("%s",r_registro.nombre);
printf(" Apellido: ");
scanf("%s",r_registro.apellido);
/*printf(" Edad: ");
scanf("%d",&r_registro.edad);
strcpy(r_registro.nombre,"X");
strcpy(r_registro.apellido,"X");*/
r_registro.activo = 1;
fwrite(&r_registro,TAMANO_REGISTRO,1,fp);
printf(" Activo: %d ",r_registro.activo);
printf("\n Registro Modificado ");
return 1;
}
if(n==-1)
{
printf("\n Error: Registro No Modificado ");
return -1;
}
fseek(fp,-TAMANO_REGISTRO,SEEK_CUR);
}
int i_eliminar(FILE *fp, int i_clave)
{
if(fp==NULL)
printf("\n Error: ");
int n;
registro r_registro;
n=i_buscar(fp,i_clave,&r_registro);
printf(" %d ",n);
if(n==0)
{
printf("\n\n Registro No Encontrado ");
return 0;
}
if(n==1)
{
//strcpy(r_registro.nombre,"Xooo");
//strcpy(r_registro.apellido,"Xooo");
r_registro.activo = 0;
fwrite(&r_registro,TAMANO_REGISTRO,1,fp);
printf("\n\n Registro Eliminado ");
return 1;
}
if(n==-1)
{
printf("\n Error: Registro No Borrado ");
return -1;
}
fseek(fp,TAMANO_REGISTRO,SEEK_SET);
}
void v_menu()
{
printf("\n\n\n\n\n\n\n\n\t\t\t 1. Inicializar ");
printf("\n\t\t\t 2. Imprimir Registro ");
printf("\n\t\t\t 3. Agregar Registro ");
printf("\n\t\t\t 4. Buscar Registro ");
printf("\n\t\t\t 5. Modificar Registro ");
printf("\n\t\t\t 6. Eliminar Registro ");
printf("\n\t\t\t 0. Salir ");
printf("\n\t\t\t Selecione su opcion: ");
}
int main()
{
int n;
int i_clave;
registro r_registro;
FILE *fp=fopen(NOMBRE_ARCHIVO,"rb+");
if(fp==NULL)
{
fp=fopen(NOMBRE_ARCHIVO,"wb+");
if(fp==NULL)
{
printf("\nError al abrir el archivo");
}
}
else
{
system("cls");
int opc;
do
{
v_menu();
scanf("%d",&opc);
system("cls");
switch(opc)
{
case 1: v_inicializar(fp,NOMBRE_ARCHIVO);break;
case 2: v_imprimir(fp);break;
case 3: v_agregar(fp);break;
case 4: i_buscar(fp,i_clave, &r_registro);break;
case 5:
{
printf("\n Cedula: ");
scanf("%d",&i_clave);
n=i_modificar(fp,i_clave);
printf("\n %d ",n);
break;
}
case 6:
{
printf("\n Cedula: ");
scanf("%d",&i_clave);
n=i_eliminar(fp,i_clave);
printf("\n %d ",n);
break;
}
}
}while(opc!=0);
}
fclose(fp);
getch();
}
| true |
5af8d7713f6b85e1c56b63db0e94f09900c55c8b | C++ | wfhendrix11/Software-Construction | /Lab4/RegularCash.hpp | UTF-8 | 540 | 2.78125 | 3 | [] | no_license | // Lab 4: Simple Cash Register Application with
// Inheritance and Vitual Functions
// File: RegularCash.hpp
// Description: RegularCash class abstraction.
#ifndef RegularCash_hpp
#define RegularCash_hpp
#include "RegularSale.hpp"
using namespace std;
// Name: RegularCash
// Description: Defines the RegularCash object.
class RegularCash : public RegularSale
{
private:
double amountReceived;
double change;
public:
RegularCash();
void process_payment();
void print_sale();
};
#endif // RegularCash.hpp | true |
226695636705b90e5fa47555ef24b87e74e93ef8 | C++ | ar43/NES_Emulator | /src/machine/ppu/ppuaddr.h | UTF-8 | 328 | 2.609375 | 3 | [] | no_license | #pragma once
#include <array>
class PpuAddr
{
public:
PpuAddr()
{
addr[0] = 0;
addr[1] = 0;
scroll_offset = 0;
w = nullptr;
}
int GetAddr();
void Write(uint8_t value, int *t, int *v);
void Add(uint8_t val);
void Clear();
int* w;
int* x;
int scroll_offset;
uint8_t* scrolladdr;
private:
uint8_t addr[2];
}; | true |
4cc0533be3989f2e6bb8731950b3c0d0f0f1f6d1 | C++ | sergiiGitHub/Demo | /Algorithm/e-olymp/0066.cpp | UTF-8 | 2,318 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <string>
#include <sstream>
using namespace std;
struct Schedule{
int start;
int end;
static const int hToM = 60;
private:
int getMinutes( string str ){
int h, m;
string toInt;
std::stringstream stream(str);
getline(stream, toInt, ':');
h = stoi( toInt );
getline(stream, toInt, ':');
m = stoi( toInt );
return h * hToM + m;
}
public:
friend ostream& operator<<(ostream& os, const Schedule& sc);
Schedule( string line ){
std::stringstream stream(line);
string string;
//start
stream >> string;
start = getMinutes(string);
//end
stream >> string;
end = getMinutes(string);
}
Schedule(){ }
};
ostream& operator<<(ostream& os, const Schedule& sc)
{
os << sc.start << ' ' << sc.end;
return os;
}
#define SIZE 1000
int N;
Schedule schedules[SIZE];
Schedule schedulesBuff[SIZE];
inline void justMerge( int left, int mid, int right)
{
int k = 0, i = left, j = mid + 1;
while (i <= mid && j <= right)
{
if ( schedules[i].end < schedules[j].end ){
schedulesBuff[k] = schedules[ i ];
++i;
} else {
schedulesBuff[k] = schedules[ j ];
++j;
}
++k;
}
while (i <= mid){
schedulesBuff[k++] = schedules[i++];
}
for (int q = 0; q < k; ++q){
schedules[q + left] = schedulesBuff[q];
}
}
inline void mergeSort( int left, int right)
{
if (right - left < 1) return;
int mid = (left + right) / 2;
mergeSort( left, mid);
mergeSort( mid + 1, right);
justMerge( left, mid, right);
}
int main()
{
//freopen ("input.txt", "r", stdin);
string input;
getline(std::cin, input);
stringstream stream(input);
stream >> N;
for ( int i = 0; i < N; ++i ){
std::getline( std::cin, input );
Schedule s( input );
schedules[ i ] = s;
}
mergeSort( 0, N - 1 );
int result = 1;
Schedule prev = schedules[0];
for ( int i = 1; i < N; ++i ){
if ( prev.end <= schedules[i].start ){
++result;
prev = schedules[i];
}
}
cout << result << endl;
return 0;
} | true |
ed1f4e09e36b8253c37c7e7b2ce2b55a7a6b4fa6 | C++ | SRatna/Parallel-computing-lab | /Lab 3/Exercise1/bfsqueue.cpp | UTF-8 | 5,808 | 2.984375 | 3 | [] | no_license | #include <stdlib.h>
#include <unistd.h>
#include <string>
#include <iostream>
#include <fstream>
#include "bfsqueue.h"
using namespace std;
/**
* Data structure for supporting the breadth first search. The data structure primarily implements
* a queue for configurations, connected with a set (bit set) storing the configurations that have
* already been visited.
*/
/**
* Constructor: Create a queue/bit set for configuration numbers between
* 0 and numConf-1.
*/
BFSQueue::BFSQueue(unsigned long numConf)
: file("sokoban.tmp", ios::out|ios::in|ios::trunc|ios::binary) // open a temporary file
{
if (!file.is_open()) {
cerr << "Cannot open tmp file 'sokoban.tmp'\n";
exit(1);
}
// Delete the file. However, it stays accessible until it is closed.
// When using the Windows OS, you may need to delete this statement.
unlink("sokoban.tmp");
// Allocate arrays and initialize them with NULL. This initialization is caused by the
// empty pair of parentheses () at the end of the 'new' operator.
queue_length = qIndex1(numConf-1) + 1;
queue[0] = new Entry *[queue_length]();
queue[1] = new Entry *[queue_length]();
bitset_length = bsIndex1(numConf-1) + 1;
bitset = new volatile unsigned int*[bitset_length]();
wrPos = 0;
rdLength = 0;
depth = 0;
file_length = 0;
}
/**
* Destructur: deallocate memory.
*/
BFSQueue::~BFSQueue()
{
for (unsigned int i=0; i<queue_length; i++) {
delete[] queue[0][i];
delete[] queue[1][i];
}
for (unsigned int i=0; i<bitset_length; i++) {
delete[] bitset[i];
}
delete[] queue[0];
delete[] queue[1];
delete[] bitset;
file.close();
}
/**
* Increase the tree depth by one. The previous write queue becomes the read queue for the
* new tree depth. The old read queue is stored in a temporary file to determine the solution
* path at the end.
*/
void BFSQueue::pushDepth()
{
unsigned int wr = depth % 2;
unsigned int n1 = qIndex1(wrPos);
unsigned int n2 = qIndex2(wrPos);
// Export the old read queue to a file.
for (unsigned int i=0; i<n1; i++)
file.write((char *)queue[wr][i], BLOCKSIZE * sizeof(Entry));
if (n2 > 0)
file.write((char *)queue[wr][n1], n2 * sizeof(Entry));
file_length += ((unsigned long)BLOCKSIZE) * n1 + n2;
depth++;
rdLength = wrPos;
wrPos = 0;
}
/**
* Checks if the given configuration is already contained in the bit set. If not, the
* configuration is entered in the bit set and the configuration, the index of the predecessor
* configuration and the number of the moved box are added to the write queue.
*/
bool BFSQueue::lookup_and_add(unsigned long conf, unsigned int predIndex, unsigned int box)
{
unsigned int bitmask = 1 << bsBitPos(conf);
unsigned int i1 = bsIndex1(conf);
unsigned int i2 = bsIndex2(conf);
// If necessary, allocate an array at the second level and initialize it with 0
if (bitset[i1] == NULL)
bitset[i1] = new unsigned int[BLOCKSIZE]();
// If the configuration is in the bit set: we are done
if ((bitset[i1][i2] & bitmask) != 0)
return false;
// if(__sync_fetch_and_and(bitset[i1][i2], bitmask) != 0)
// return false;
// add the configuration to the bit set
bitset[i1][i2] |= bitmask;
// Append the configuration, the index of the predecessor configuration and the
// number of the moved box at the end of the write queue.
unsigned int wr = depth % 2;
unsigned int n1 = qIndex1(wrPos);
unsigned int n2 = qIndex2(wrPos);
// If necessary, allocate an array at the second level and initialize it
if (queue[wr][n1] == NULL)
queue[wr][n1] = new Entry[BLOCKSIZE]();
// Write the new entry at position wrPos into the write queue
queue[wr][n1][n2].set(conf, wrPos + (rdLength - predIndex), box);
// Increment the write position
wrPos++;
return true;
}
/**
* Return the length of the read queue.
*/
unsigned int BFSQueue::length()
{
return rdLength;
}
/**
* Return the i-th entry in the read queue (configuration as return value;
* moved box in *box).
*/
unsigned long BFSQueue::get(unsigned int i, unsigned int * box)
{
unsigned int rd = (depth-1) % 2;
Entry *e = &queue[rd][qIndex1(i)][qIndex2(i)];
if (box != NULL)
*box = e->box;
return e->config;
}
/**
* Return the solution path as an array of configurations. The parameter conf is the
* solution configuration, predIndex the index of the predecessor configuration. In *path_length
* the length of the path is returned. The result is allocated dynamically and should be
* deallocated using delete[].
*/
unsigned long * BFSQueue::getPath(unsigned long conf, unsigned int predIndex,
unsigned int * path_length)
{
unsigned long * path = new unsigned long[depth+1];
path[depth] = conf;
unsigned int pos = rdLength - predIndex - 1;
long abspos = file_length * sizeof(Entry); // XX
// Iterate the path in reversed order
for (int k = depth-1; k>=0; k--) {
Entry e;
// Search the entry for the predecessor configuration in the file and load it
file.seekg(-((int)pos+1)*sizeof(Entry), ios::cur);
file.read((char *)&e, sizeof(Entry));
path[k] = e.config;
pos = e.pred;
}
*path_length = depth+1;
return path;
}
/**
* Returns information about RAM and hard disk usage.
*/
void BFSQueue::statistics()
{
unsigned int size = 2*queue_length*sizeof(Entry *)/1024;
for (unsigned int i=0; i<queue_length; i++) {
if (queue[0][i] != NULL)
size += BLOCKSIZE/1024*sizeof(Entry);
if (queue[1][i] != NULL)
size += BLOCKSIZE/1024*sizeof(Entry);
}
cout << "Used " << size << " KBytes for arrays\n";
size = bitset_length*sizeof(unsigned int *)/1024;
for (unsigned int i=0; i<bitset_length; i++) {
if (bitset[i] != NULL)
size += BLOCKSIZE/1024*sizeof(unsigned int);
}
cout << "Used " << size << " KBytes for bit set\n";
size = file_length*sizeof(Entry)/1024;
cout << "Used " << size << " KBytes for temp file\n";
}
| true |
be74a8b5f37073500767e2baaa6557960732a5e7 | C++ | zhanglei/tikv-cpp | /test/pd_client_test.cc | UTF-8 | 771 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | #include <string>
#include "pd_client.h"
#include "logging.h"
#define CATCH_CONFIG_MAIN
#include "3rd_party/catch/catch.hpp"
TEST_CASE("get region by key") {
tikv::pd_client pd("pd://localhost:2379");
tikv::region_info region;
tikv::resp r = pd.get_region("hello", ®ion);
REQUIRE(r.ok());
}
TEST_CASE("get stores") {
tikv::pd_client pd("pd://localhost:2379");
tikv::region_info region;
std::vector<tikv::store_info> ret;
tikv::resp r = pd.get_all_stores(&ret);
LOG("store count:" << ret.size());
REQUIRE(r.ok());
REQUIRE(ret.size() > 0);
tikv::store_info info;
r = pd.get_store_by_id(ret[0].id, &info);
LOG("store" << ret[0].id << ":" << info.addr);
REQUIRE(r.ok());
REQUIRE(info.addr.size() > 0);
}
| true |
5d77bacca4ac5152833ed10af6cf77fa8152bb45 | C++ | wangzilong2019/text | /蓝桥杯算法练习/采药.cpp | GB18030 | 582 | 2.53125 | 3 | [] | no_license | #include<stdio.h>
#define max(a, b) a>b ? a:b
#define MAX 1000
int v[MAX], t[MAX];
int main () {
int i, j, T, M;
int c[MAX][MAX] = {0};
//ҩʱɽҩĿ
scanf("%d %d", &T, &M);
//ÿҩĵIJժʱͼֵ
for (i = 1; i <= M; i++) {
scanf("%d %d", &t[i], &v[i]);
}
for (i = 1; i <= M; i++) {
for (j = 1; j <= T; j++) {
//жϵiҩǷԲժ
if (t[i] <= j) {
c[i][j] = max(c[i-1][j], c[i-1][j-t[i]] + v[i]);
} else {
c[i][j] = c[i-1][j];
}
}
}
printf("%d", c[M][T]);
return 0;
}
| true |
fe501319ac0ad0cded05c9c8e370d8cc90303cf3 | C++ | LDlornd/OI-Memory | /洛谷/P1000~P1999/P1000~P1099/P1012 拼数/P1012 拼数.cpp | UTF-8 | 416 | 2.703125 | 3 | [] | no_license | #include<cstdio>
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
struct num
{
string s;
int len;
};
num k[20];
int CMP(const num &a,const num &b)
{
string i=a.s+b.s,j=b.s+a.s;
if(i<=j) return 0;
else return 1;
}
int main()
{
int n;
cin>>n;
for(int i=0;i<n;++i)
{
cin>>k[i].s;
k[i].len=k[i].s.length();
}
sort(k,k+n,CMP);
for(int i=0;i<n;++i)
cout<<k[i].s;
return 0;
}
| true |
9fbd613bb8ed7bf5aff9189df9698d6b9b93665b | C++ | tarawa/cntt2016-hw1 | /TC-SRM-554-div1-250/bx2k.cpp | UTF-8 | 391 | 3.25 | 3 | [] | no_license | #include<bits/stdc++.h>
class TheBrickTowerEasyDivOne
{
public:
int find(int rc, int rh, int bc, int bh)
{
if(rc==bc)
{
if(rh==bh)return rc*2;//去除二式等于三式的情况
else return rc*3;
}
else//a!=b的情况会多出一种
{
if(rh==bh)return std::min(rc,bc)*2+1;//去除二式等于三式的情况
else return std::min(rc,bc)*3+1;
}
}
}; | true |
cc07c08b3ae8ede2cc3980594faa7b06709ff679 | C++ | hongh815/C_code_collection | /C++_project/c++9차_namespace_std/std10-3.cpp | UTF-8 | 830 | 3.890625 | 4 | [] | no_license |
#include <cstdio>
#include <iostream>
//다음과 같은 int 배열을 오름차순으로 정렬한 후 화면에 결과를 출력하는 프로그램을 작성하세요.
//단, 화면에 배열 내용을 출력할 때는 반드시 ‘범위 기반 For 문’을 사용합니다.
// Int aList[5] = { 10, 20, 30, 40, 50};
void arrDesc(int*);
int main() {
int number[5] {69,793,25,498,245};
int* pnum;
pnum = &number[0];
arrDesc(pnum);
std::cout << "Int aList[5] = {";
for( auto n : number) {
std::cout << n << ", ";
n++;
}
std::cout << "}" << std::endl;
}
void arrDesc(int* number) {
int temp;
for(int i = 0 ; i < 5 ; i ++) {
for(int j = 0 ; j < 4-i ; j ++) {
if(number[j]>number[j+1]) {
temp = *(number + j);
*(number + j) = *(number + (j+1));
*(number + (j+1)) = temp;
}
}
}
}
| true |
1fe0e70aa0ef760986b3e06269b96fdf6955dba3 | C++ | thiagosantos346/URI-OJ | /Volume 15 (1500 - 1599)/1503/1503.cpp | UTF-8 | 2,692 | 2.59375 | 3 | [] | no_license | #include "bits/stdc++.h"
using namespace std;
#define endl '\n'
bool comp(const string &a, const string &b) {
return (a.length() > b.length());
}
class PalindromicTree {
class no {
public:
int inicio, fim, length, suffixEdge;
vector<int> insertEdge = vector<int>(26, 0);
no() { }
no (int length, int suffixEdge) { this->length = length, this->suffixEdge = suffixEdge; }
};
public:
no raiz1 = no(-1, 1), raiz2 = no(0, 1);
vector<no> tree;
int noAtual = 1;
int pos = 2;
string s;
PalindromicTree(string s) {
tree = vector<no>(s.length()+3);
tree[1] = raiz1, tree[2] = raiz2;
this->s = s;
for (int i = 0; i < s.length(); i++)
insere(i);
}
void buscaX(int idx, int &atual) {
for (; idx-tree[atual].length < 1 || s[idx] != s[idx-tree[atual].length-1];
atual = tree[atual].suffixEdge);
}
void insere(int idx) {
int aux = noAtual;
buscaX(idx, aux);
if (tree[aux].insertEdge[s[idx]-'a'] != 0) {
noAtual = tree[aux].insertEdge[s[idx]-'a'];
return;
}
pos++;
tree[aux].insertEdge[s[idx]-'a'] = pos;
tree[pos].length = tree[aux].length + 2;
tree[pos].fim = idx;
tree[pos].inicio = idx - tree[pos].length + 1;
aux = tree[aux].suffixEdge;
noAtual = pos;
if (tree[noAtual].length == 1) {
tree[noAtual].suffixEdge = 2;
return;
}
buscaX(idx, aux);
tree[noAtual].suffixEdge = tree[aux].insertEdge[s[idx]-'a'];
}
vector<string> palSubstr() {
//imprime();
vector<string> pal;
for (int i = 3; i <= pos; i++) {
string aux = "";
for (int j = tree[i].inicio; j <= tree[i].fim; j++) aux += s[j];
pal.push_back(aux);
}
return pal;
}
void imprime() {
for (int i = 3; i <= pos; i++) {
for (int j = tree[i].inicio; j <= tree[i].fim; j++)
cout << s[j];
cout << endl;
}
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
string s;
while (cin >> n) {
int menor = INT_MAX, menorPos = 0;
vector<vector<string>> v(n);
for (int i = 0; i < n; i++) {
cin >> s;
v[i] = PalindromicTree(s).palSubstr();
if (v[i].size() < menor) menor = v[i].size(), menorPos = i;
}
sort(v[menorPos].begin(), v[menorPos].end(), comp);
bool nenhum = 1;
for (int i = 0; i < v[menorPos].size(); i++) {
bool flag = 1;
for (int j = 0; j < n; j++) {
if (j != menorPos) {
if (find(v[j].begin(), v[j].end(), v[menorPos][i]) == v[j].end()) {
flag = 0;
break;
}
}
}
if (flag) {
nenhum = 0;
cout << v[menorPos][i].length() << endl;
break;
}
}
if (nenhum) cout << "0\n";
}
return 0;
} | true |
dc0acc47ece4dca0b10d824009cd10ef828f01d6 | C++ | caiafrazao/SoccerRobot | /Delta.cpp | UTF-8 | 336 | 2.828125 | 3 | [] | no_license | #include "Delta.h"
Delta::Delta(float alpha, float beta)
{
this->alpha = alpha;
this->beta = beta;
this->spike = alpha;
}
float Delta::pertinencia(float u)
{
float mi = 0.0;
if (u < alpha) mi = 1.0;
if ((u >= alpha) && (u <= beta)) mi = (beta - u)/(beta - alpha);
if (u > beta) mi = 0.0;
return mi;
}
| true |
87fa8264110885c98cb6b3f506642d618acdb614 | C++ | rainlong/learning_DP | /example/STRUCTURAL/Proxy/subject.h | UTF-8 | 622 | 2.921875 | 3 | [] | no_license | #pragma once
#include <iostream>
// 真实的需求
// 抽象出方法, 没有成员变量(就好像没有特定的目的) - “我知道该怎么做, 但我做是为了什么是不知道”
// 对需求的实现而言, 需要实现方法,并且明确对象
// 对代理而言, 需要知道实际的实现, 然后调用它, 所以真正执行的是具体主题的行为, 而实际暴露给外界的是代理对象
class Subject
{
public:
virtual ~Subject() {}
virtual void request() = 0;
// { std::cout << "我只知道该怎么做" << std::endl; }
protected:
Subject() {}
private:
}; | true |
373dd8490fb4a56d43904a7a192cf8a6d4d8d6a9 | C++ | miketsop/Udemy_DesignPatternsInModernCpp | /Builder/HtmlBuilder.cpp | UTF-8 | 503 | 2.96875 | 3 | [] | no_license | #include "HtmlBuilder.h"
using namespace std;
HtmlBuilder::HtmlBuilder(string root_name)
{
root = new HtmlElement(root_name, "");
}
HtmlBuilder &HtmlBuilder::addChild(string child_name, string child_text)
{
HtmlElement e{child_name, child_text};
root->elements.emplace_back(e);
return *this;
}
HtmlElement HtmlBuilder::build()
{
return *root;
}
string HtmlBuilder::str() const { return root->str(0); }
// operator HtmlBuilder::HtmlElement() const
// {
// return root;
// }
| true |
68af4a7c84c2cd358106d93cd825b19e960c9e99 | C++ | joseph-isaacs/CppSocket | /CppSocket.Test/Source/CountedParserTest.cpp | UTF-8 | 4,346 | 2.984375 | 3 | [] | no_license | #ifndef CATCH_CONFIG_MAIN
#define CATCH_CONFIG_MAIN
#endif
#include "CountedDataParser.hpp"
#include "catch.hpp"
std::string packIntToString(size_t number)
{
std::string str_in;
str_in.resize(4);
str_in[0] = (number >> 24) & 0xFF;
str_in[1] = (number >> 16) & 0xFF;
str_in[2] = (number >> 8) & 0xFF;
str_in[3] = number & 0xFF;
return str_in;
}
TEST_CASE("Testing the CountedDataParser for interger between 0 and UINT32_MAX and in parts", "[CountedDataParser][setCountedData][appendCountedData]")
{
CppSocket::CountedDataParser p;
uint32_t len = 1;
std::string str = packIntToString(htonl(len));
p.setCountedData(&str);
REQUIRE(p.getLength() == len);
len = 0;
str = packIntToString(htonl(len));
p.setCountedData(&str);
REQUIRE(p.getLength() == len);
len = UINT32_MAX;
str = packIntToString(htonl(len));
p.setCountedData(&str);
REQUIRE(p.getLength() == len);
CppSocket::CountedDataParser par;
uint32_t numbe = 23423432;
uint32_t number = htonl(numbe);
std::string str_in;
str_in.resize(1);
str_in[0] = (number >> 24) & 0xFF;
par.appendCountedData(&str_in);
REQUIRE(par.getLength() != numbe);
str_in.clear();
str_in.resize(1);
str_in[0] = (number >> 16) & 0xFF;
par.appendCountedData(&str_in);
REQUIRE(par.getLength() != numbe);
str_in.clear();
str_in.resize(2);
str_in[0] = (number >> 8) & 0xFF;
str_in[1] = number & 0xFF;
par.appendCountedData(&str_in);
REQUIRE(par.getLength() == numbe);
CppSocket::CountedDataParser pars;
uint32_t nu = 8089089;
uint32_t numb = htonl(nu);
std::string str_ins;
str_ins.resize(3);
str_ins[0] = (numb >> 24) & 0xFF;
str_ins[1] = (numb >> 16) & 0xFF;
str_ins[2] = (numb >> 8) & 0xFF;
pars.setCountedData(&str_ins);
REQUIRE(pars.getLength() != nu);
str_ins.clear();
str_ins.resize(1);
str_ins[0] = numb & 0xFF;
pars.appendCountedData(&str_ins);
REQUIRE(pars.getLength() == nu);
}
TEST_CASE("Testing the CountedDataParser for intergers with data", "[CountedDataParser][setCountedData]")
{
CppSocket::CountedDataParser p;
std::string data = "this is a test string";
uint32_t len = data.length();
std::string str = packIntToString(htonl(len));
str.append(data);
p.setCountedData(&str);
REQUIRE(p.getLength() == len);
REQUIRE(p.getRemaining() == 0);
REQUIRE(*p.getDataPacket() == data);
data = "this is VERY VERY LONG test string";
data.append(std::string(100000, 'a'));
len = data.length();
str = packIntToString(htonl(len));
str.append(data);
p.setCountedData(&str);
REQUIRE(p.getLength() == len);
REQUIRE(p.getRemaining() == 0);
REQUIRE(*p.getDataPacket() == data);
std::string first, firstLen, second, secondLen, third, thirdLen, all;
first = "this is a test string";
firstLen = packIntToString(htonl(first.length()));
second = "this is a second part of a test string";
secondLen = packIntToString(htonl(second.length()));
third = "this is a third part of a test string";
thirdLen = packIntToString(htonl(third.length()));
all.append(firstLen);
all.append(first);
all.append(secondLen);
all.append(second);
all.append(thirdLen);
all.append(third);
p.setCountedData(&all);
REQUIRE(p.getLength() == first.length());
REQUIRE(p.getRemaining() == 0);
REQUIRE(p.checkAllData() == true);
REQUIRE(*p.getDataPacket() == first);
REQUIRE(p.getLength() == second.length());
REQUIRE(p.getRemaining() == 0);
REQUIRE(p.checkAllData() == true);
REQUIRE(*p.getDataPacket() == second);
REQUIRE(p.getLength() == third.length());
REQUIRE(p.getRemaining() == 0);
REQUIRE(p.checkAllData() == true);
REQUIRE(*p.getDataPacket() == third);
}
TEST_CASE("Testing the CountedDataParser for intergers with data in parts", "[CountedDataParser][setCountedData]")
{
CppSocket::CountedDataParser p;
std::string first, firstLen, second, total;
first = "this is a test string";
second = " with i final part.";
uint32_t totalLen = first.length() + second.length();
firstLen = packIntToString(htonl(totalLen));
total.append(firstLen);
total.append(first);
//total.append(second);
p.appendCountedData(&total);
REQUIRE(p.getLength() == totalLen);
REQUIRE(p.getRemaining() != 0);
REQUIRE(p.checkAllData() == false);
p.appendCountedData(&second);
REQUIRE(p.getLength() == totalLen);
REQUIRE(p.getRemaining() == 0);
REQUIRE(p.checkAllData() == true);
REQUIRE(*p.getDataPacket() == std::string(first + second));
} | true |
6ce9e32b091c7ee518a5f591ec072e7a5cae436c | C++ | gregormilligan/GregorMilliganProgrammingExamples | /Genetic ALgorithm/CarAI/CarAI/AItargetwall.h | UTF-8 | 597 | 3 | 3 | [] | no_license | #pragma once
#include <iostream>
const int wallPop = 15; // this is the number of walls spawned
class AItargetwall
{
public:
float x = 10;
float y = 10;
float width = 10;
float height = 10;
AItargetwall();
AItargetwall(float wx, float wy, float wwidth, float wheight);
};
AItargetwall::AItargetwall(float wx, float wy, float wwidth, float wheight)
{
x = wx, y = wy;
width = wwidth; height = wheight;
}
//random wall generation
AItargetwall::AItargetwall()
{
x = (rand() % 5) + 10;
y = (rand() % 5) + 50;
width = (rand() % 10);
height = (rand() % 10);
} | true |
acdd527acb139a1204d92c1f59f3bc684e688ca0 | C++ | hal2069/Faasm | /tests/test/knative/test_knative_handler.cpp | UTF-8 | 5,436 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | #include <catch/catch.hpp>
#include "utils.h"
#include <knative/KnativeHandler.h>
#include <scheduler/GlobalMessageBus.h>
#include <util/json.h>
using namespace Pistache;
namespace tests {
TEST_CASE("Test valid knative invocations", "[knative]") {
cleanSystem();
// Note - must be async to avoid needing a result
message::Message call;
call.set_isasync(true);
std::string user;
std::string function;
SECTION("C/C++") {
user = "demo";
function = "echo";
SECTION("With input") {
call.set_inputdata("foobar");
}
SECTION("No input") {
}
}
SECTION("Typescript") {
user = "ts";
function = "echo";
call.set_istypescript(true);
SECTION("With input") {
call.set_inputdata("foobar");
}
SECTION("No input") {
}
}
SECTION("Python") {
user = PYTHON_USER;
function = PYTHON_FUNC;
call.set_pythonuser("python");
call.set_pythonfunction("hello");
call.set_ispython(true);
}
call.set_user(user);
call.set_function(function);
const std::string &requestStr = util::messageToJson(call);
// Handle the function
knative::KnativeHandler handler;
const std::string responseStr = handler.handleFunction(requestStr);
// Check function count has increased and bind message sent
scheduler::Scheduler &sch = scheduler::getScheduler();
REQUIRE(sch.getFunctionInFlightCount(call) == 1);
REQUIRE(sch.getBindQueue()->size() == 1);
message::Message actualBind = sch.getBindQueue()->dequeue();
REQUIRE(actualBind.user() == call.user());
REQUIRE(actualBind.function() == call.function());
// Check actual call has right details including the ID returned to the caller
message::Message actualCall = sch.getFunctionQueue(call)->dequeue();
REQUIRE(actualCall.user() == call.user());
REQUIRE(actualCall.function() == call.function());
REQUIRE(actualCall.id() == std::stoi(responseStr));
}
TEST_CASE("Test empty knative invocation", "[knative]") {
knative::KnativeHandler handler;
std::string actual = handler.handleFunction("");
REQUIRE(actual == "Empty request");
}
TEST_CASE("Test empty JSON knative invocation", "[knative]") {
message::Message call;
call.set_isasync(true);
std::string expected;
SECTION("Empty user") {
expected = "Empty user";
call.set_function("echo");
}
SECTION("Empty function") {
expected = "Empty function";
call.set_user("demo");
}
knative::KnativeHandler handler;
const std::string &requestStr = util::messageToJson(call);
std::string actual = handler.handleFunction(requestStr);
REQUIRE(actual == expected);
}
TEST_CASE("Check getting function status from knative", "[knative]") {
cleanSystem();
scheduler::GlobalMessageBus &bus = scheduler::getGlobalMessageBus();
// Create a message
message::Message msg = util::messageFactory("demo", "echo");
std::string expectedOutput;
SECTION("Running") {
expectedOutput = "RUNNING";
}
SECTION("Failure") {
std::string errorMsg = "I have failed";
msg.set_outputdata(errorMsg);
msg.set_returnvalue(1);
bus.setFunctionResult(msg);
expectedOutput = "FAILED: " + errorMsg;
}
SECTION("Success") {
std::string errorMsg = "I have succeeded";
msg.set_outputdata(errorMsg);
msg.set_returnvalue(0);
bus.setFunctionResult(msg);
expectedOutput = "SUCCESS: " + errorMsg;
}
msg.set_isstatusrequest(true);
knative::KnativeHandler handler;
const std::string &requestStr = util::messageToJson(msg);
std::string actual = handler.handleFunction(requestStr);
REQUIRE(actual == expectedOutput);
}
void checkFlushMessageShared(const std::string &host, const message::Message &msg) {
scheduler::SharingMessageBus &sharingBus = scheduler::SharingMessageBus::getInstance();
const message::Message actual = sharingBus.nextMessageForHost(host);
REQUIRE(actual.isflushrequest());
}
TEST_CASE("Test broadcasting flush message", "[knative]") {
cleanSystem();
// Set up some dummy hosts and add to global set
std::string thisHost = util::getSystemConfig().endpointHost;
std::string hostA = "host_a";
std::string hostB = "host_b";
scheduler::Scheduler &sch = scheduler::getScheduler();
sch.addHostToGlobalSet(hostA);
sch.addHostToGlobalSet(hostB);
message::Message msg;
msg.set_isflushrequest(true);
knative::KnativeHandler handler;
const std::string &requestStr = util::messageToJson(msg);
std::string actual = handler.handleFunction(requestStr);
checkFlushMessageShared(thisHost, msg);
checkFlushMessageShared(hostA, msg);
checkFlushMessageShared(hostB, msg);
}
} | true |
61b7cc2e5a5b30319640c6daf2bc641002298ab7 | C++ | shuaipeng123/SatSolver | /Proposition.h | UTF-8 | 301 | 2.6875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Proposition
{
// Access specifier
public:
int index_i;
int index_k;
// Data Members
int position;
// Member Functions()
int getPosition()
{
cout << "position is: " << position;
return position;
}
};
| true |
2672118a248568385dee2d69e15bd81653054297 | C++ | pranjalg8/Competitive-Code | /Trees/iterativePostorder.cpp | UTF-8 | 697 | 3.078125 | 3 | [] | no_license | void iterativePostorder(Node* root)
{
stack<pair<Node*, int> > st;
st.push(make_pair(root, 0));
while (!st.empty()) {
struct Node* temp = st.top().first;
int b = st.top().second;
st.pop();
if (temp == NULL)
continue;
if (b == 0) {
st.push(make_pair(temp, 1));
if (temp->left != NULL)
st.push(make_pair(temp->left, 0));
}
else if (b == 1) {
st.push(make_pair(temp, 2));
if (temp->right != NULL)
st.push(make_pair(temp->right, 0));
}
else
cout << temp->data << " ";
}
} | true |
72c64969738d14cfa2c6c809448f231a20f8ab61 | C++ | wangjing99/ve280 | /proj 4/p4/game.cpp | UTF-8 | 6,765 | 3.09375 | 3 | [] | no_license | //
// Created by DELL on 2019/7/6.
//
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cassert>
#include "player.h"
using namespace std;
int main(int argc, char *argv[]){
try{
Pool pool=Pool();
Pool *pool_ptr=&pool;
Board board=Board();
Board *board_ptr=&board;
Piece *sel_piece;
Square *sel_square;
string compare=argv[1];//find the first player
string h_str="h";
string m_str="m";
Player *player_1=getHumanPlayer(board_ptr,pool_ptr);
Player *player_2=getHumanPlayer(board_ptr,pool_ptr);
//cout<<"1="<<argv[1]<<endl<<"2="<<argv[2]<<endl<<"3="<<argv[3]<<endl;
if(compare==h_str){
player_1=getHumanPlayer(board_ptr,pool_ptr);
}else if(compare==m_str){
player_1=getMyopicPlayer(board_ptr,pool_ptr,(unsigned int)atoi(argv[3]));
}else{
cout<<"invalid player 1"<<endl;
}
compare=argv[2];//find the second player
if(compare==h_str){
player_2=getHumanPlayer(board_ptr,pool_ptr);
}else if(compare==m_str){
player_2=getMyopicPlayer(board_ptr,pool_ptr,(unsigned int)atoi(argv[3]));
}else{
cout<<"invalid player 2"<<endl;
}
int round=0;
cout<<board.toString()<<endl;
cout<<pool.toString()<<endl;
for(round=0;round<8;round++){
cout<<"Player 1's turn to select a piece:"<<endl;
sel_piece=&player_1->selectPiece();
cout<<sel_piece->toString()<<" selected.\n"<<endl;
cout<<"Player 2's turn to select a square:"<<endl;
sel_square=&player_2->selectSquare(*sel_piece);
cout<<sel_square->toString()<<" selected.\n"<<endl;
board.place(*sel_piece,*sel_square);
cout<<board.toString()<<endl;
cout<<pool.toString()<<endl;
if(board.isWinning(*sel_piece,*sel_square)){
cout<<"Player 2 has won!"<<endl;
break;
}
cout<<"Player 2's turn to select a piece:"<<endl;
sel_piece=&player_2->selectPiece();
cout<<sel_piece->toString()<<" selected.\n"<<endl;
cout<<"Player 1's turn to select a square:"<<endl;
sel_square=&player_1->selectSquare(*sel_piece);
cout<<sel_square->toString()<<" selected.\n"<<endl;
board.place(*sel_piece,*sel_square);
cout<<board.toString()<<endl;
cout<<pool.toString()<<endl;
if(board.isWinning(*sel_piece,*sel_square)){
cout<<"Player 1 has won!"<<endl;
break;
}
if(round==7){
cout<<"It is a draw."<<endl;
break;
}
}
}
catch (UsedPieceException &error){
cout<<"UsedPieceException "<<endl;
//cout<<error.what()<<endl;
}
catch (SquareException &error){
cout<<"SquareException catched "<<endl;
//cout<<error.what()<<endl;
}
}/*Player *h_p=getHumanPlayer(board_ptr,pool_ptr);
Player *m_p=getMyopicPlayer(board_ptr,pool_ptr,(unsigned int)atoi(argv[3]));
string hm="h";
string compare=argv[1];
int round=0;
if(compare==hm){
cout<<board.toString()<<endl;
cout<<pool.toString()<<endl;
for(round=0;round<8;round++){
cout<<"Player 1's turn to select a piece:"<<endl;
sel_piece=&h_p->selectPiece();
cout<<sel_piece->toString()<<" selected."<<endl;
cout<<"Player 2's turn to select a square:"<<endl;
sel_square=&m_p->selectSquare(*sel_piece);
cout<<sel_square->toString()<<" selected."<<endl;
board.place(*sel_piece,*sel_square);
cout<<board.toString()<<endl;
cout<<pool.toString()<<endl;
if(board.isWinning(*sel_piece,*sel_square)){
cout<<"Player 2 has won!"<<endl;
break;
}
cout<<"Player 2's turn to select a piece:"<<endl;
sel_piece=&m_p->selectPiece();
cout<<sel_piece->toString()<<" selected."<<endl;
cout<<"Player 1's turn to select a square:"<<endl;
sel_square=&h_p->selectSquare(*sel_piece);
cout<<sel_square->toString()<<" selected."<<endl;
board.place(*sel_piece,*sel_square);
cout<<board.toString()<<endl;
cout<<pool.toString()<<endl;
if(board.isWinning(*sel_piece,*sel_square)){
cout<<"Player 1 has won!"<<endl;
break;
}
if(round==7){
cout<<"It is a draw."<<endl;
break;
}
}
}else{
cout<<board.toString()<<endl;
cout<<pool.toString()<<endl;
for(round=0;round<8;round++){
cout<<"Player 1's turn to select a piece:"<<endl;
sel_piece=&m_p->selectPiece();
cout<<sel_piece->toString()<<" selected."<<endl;
cout<<"Player 2's turn to select a square:"<<endl;
sel_square=&h_p->selectSquare(*sel_piece);
cout<<sel_square->toString()<<" selected."<<endl;
board.place(*sel_piece,*sel_square);
cout<<board.toString()<<endl;
cout<<pool.toString()<<endl;
if(board.isWinning(*sel_piece,*sel_square)){
cout<<"Player 2 has won!"<<endl;
break;
}
cout<<"Player 2's turn to select a piece:"<<endl;
sel_piece=&h_p->selectPiece();
cout<<sel_piece->toString()<<" selected."<<endl;
cout<<"Player 1's turn to select a square:"<<endl;
sel_square=&m_p->selectSquare(*sel_piece);
cout<<sel_square->toString()<<" selected."<<endl;
board.place(*sel_piece,*sel_square);
cout<<board.toString()<<endl;
cout<<pool.toString()<<endl;
if(board.isWinning(*sel_piece,*sel_square)){
cout<<"Player 1 has won!"<<endl;
break;
}
if(round==7){
cout<<"It is a draw."<<endl;
break;
}
}
}*/ | true |
9c37492b7f3dd82bef83aef177d261def022a022 | C++ | amolr/MusicPlayer | /MusicPlayerTest/PlayTrackUnitTest.cpp | UTF-8 | 1,926 | 3.03125 | 3 | [] | no_license | #include "stdafx.h"
#include "CppUnitTest.h"
#include "MusicPlayer.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace MusicPlayerTest
{
//Unit test for all Play track operations
TEST_CLASS(PlayTrackUnitTest)
{
public:
// play a song when ordinal is less than 0
TEST_METHOD(PlayTrackOrdinalLessThanZero)
{
MusicPlayer* player = new MusicPlayer();
const int ordinal = -1;
const int number_of_songs = 3;
player->CreatePlaylist(number_of_songs);
Assert::IsFalse(player->PlayTrackNumber(ordinal));
}
// play a song when ordinal is equal to 0
TEST_METHOD(PlayTrackOrdinalEqualZero)
{
MusicPlayer* player = new MusicPlayer();
const int ordinal = 0;
const int number_of_songs = 3;
player->CreatePlaylist(number_of_songs);
Assert::IsFalse(player->PlayTrackNumber(ordinal));
}
// play a song when ordinal is greater than 0
TEST_METHOD(PlayTrackOrdinalGreaterThanZero)
{
MusicPlayer* player = new MusicPlayer();
const int ordinal = 2;
const int number_of_songs = 3;
player->CreatePlaylist(number_of_songs);
Assert::IsTrue(player->PlayTrackNumber(ordinal));
}
// play a song when ordinal is greater than playlist size
TEST_METHOD(PlayTrackOrdinalGreaterThanSize)
{
MusicPlayer* player = new MusicPlayer();
const int ordinal = 4;
const int number_of_songs = 3;
player->CreatePlaylist(number_of_songs);
Assert::IsFalse(player->PlayTrackNumber(ordinal));
}
// Change the playing track
TEST_METHOD(PlayTrackOrdinalChange)
{
MusicPlayer* player = new MusicPlayer();
int ordinal = 2;
const int number_of_songs = 4;
player->CreatePlaylist(number_of_songs);
player->PlayTrackNumber(ordinal);
Assert::AreEqual(player->GetCurrentPlayingIndex(), ordinal-1);
ordinal = 4;
player->PlayTrackNumber(ordinal);
Assert::AreEqual(player->GetCurrentPlayingIndex(), ordinal-1);
}
};
} | true |
3053a9bff2a15e63a5ee2f7b46337d90f5b75759 | C++ | pawel02/SpareTime | /SpareTime/Builder/Builder2.cpp | UTF-8 | 2,263 | 3.4375 | 3 | [] | no_license | //#include <iostream>
//#include <string>
//#include <vector>
//#include <sstream>
//#include <memory>
//
//struct HtmlBuilder;
//
//struct HtmlElement
//{
// std::string name;
// std::string text;
// std::vector<HtmlElement> elements;
// const size_t indent_size = 2;
//
// HtmlElement() {}
//
// HtmlElement(const std::string& n, const std::string& t)
// :name(n), text(t)
// {}
//
// std::string str(size_t indent = 0) const
// {
// std::ostringstream oss;
// std::string i(indent_size * indent, ' ');
// oss << i << "<" << name << ">" << "\n";
//
// if(text.size() > 0)
// oss << std::string(indent_size * (indent + 1), ' ') << text << "\n";
//
// //call recursively on all children
// for (const auto& e : elements)
// {
// oss << e.str(indent + 1);
// }
//
// oss << i << "</" << name << ">\n";
// return oss.str();
// }
//
// static HtmlBuilder build(const std::string& root_name);
// static std::unique_ptr<HtmlBuilder> create(const std::string& root_name);
//};
//
//struct HtmlBuilder
//{
// HtmlBuilder(std::string root_name)
// {
// root.name = root_name;
// }
//
// HtmlBuilder& add_child(std::string child_name, std::string child_text)
// {
// HtmlElement e{ child_name, child_text };
// root.elements.emplace_back(e);
//
// return *this;
// }
//
// HtmlBuilder* add_child2(std::string child_name, std::string child_text)
// {
// HtmlElement e{ child_name, child_text };
// root.elements.emplace_back(e);
//
// return this;
// }
//
// HtmlElement root;
//
// operator HtmlElement() { return root; }
//
// std::string str() const { return root.str(); };
//};
//
//HtmlBuilder HtmlElement::build(const std::string& root_name)
//{
// return HtmlBuilder{ root_name };
//}
//
//std::unique_ptr<HtmlBuilder> HtmlElement::create(const std::string& root_name)
//{
// return std::make_unique<HtmlBuilder>( root_name );
//}
//
//int main()
//{
// /*HtmlBuilder builder{ "ul" };
// builder.add_child("li", "Hello")
// .add_child("li", "World");*/
//
// HtmlElement e = HtmlElement::build("ul").add_child("li", "Hello")
// .add_child("li", "world");
//
// HtmlElement ee = *HtmlElement::create("ul")->add_child2("li", "Hello")
// ->add_child2("li", "world");
//
// std::cout << e.str() << "\n";
//
// std::cin.get();
// return 0;
//} | true |
37a054e6b115902e183bdc4b53d608fd9d663b80 | C++ | Soulliom/anoroguelike | /src/InputManager.cpp | UTF-8 | 26,130 | 2.734375 | 3 | [
"MIT"
] | permissive | #include "../include/InputManager.h"
#include "../include/GameManager.h"
#include "../include/Player.h"
#include "../include/SceneManager.h"
/* Setters / Getters */
int InputManager::getSelectStateX() {
return selectState.x;
}
int InputManager::getSelectStateY() {
return selectState.y;
}
InputManager::SelectState InputManager::getSelectState() {
return selectState;
}
//Reset selectState structs
void InputManager::resetSelectState() {
selectState.x = 0;
selectState.y = 0;
}
/* Pauses, Inputs, Navigations.*/
void InputManager::pause(std::string t_text, const unsigned int t_seconds, const unsigned int t_key) {
//Sleep
Sleep(t_seconds * 1000);
//Collects spammed keys pressed during sleep
while (_kbhit()) {
_getch();
}
//Print text
std::cout << std::endl << t_text << std::endl;
//If correct key is pressed continue. (Unless NULL then continue otherwise)
bool b_contin = false;
while (!b_contin) {
int but = _getch();
if (t_key != NULL) {
if (t_key == but) {
b_contin = true;
}
}
else {
b_contin = true;
}
}
}
void InputManager::output(std::string t_text, const unsigned int t_seconds) {
//Sleep
Sleep(t_seconds * 1000);
//Collects spammed keys pressed during sleep
while (_kbhit()) {
_getch();
}
//Print text
std::cout << std::endl << t_text;
}
std::string InputManager::stringInput(std::string t_text) {
//define, get, return string output - print text param
std::string output;
std::cout << "\n" << t_text << "\n";
std::cin >> output;
return output;
}
int InputManager::intInput(std::string t_text) {
//define, get, check and return output - print text param
int output = 0;
std::cout << "\n" << t_text << "\n";
std::cin.clear();
std::cin >> output;
if (output > 0) {
return output;
}
else {
while (std::cin.fail()) {
//If invalid, return false, pause and clear cin
pause("ERROR: No negative numbers or characters! Press [Space] to continue", 1, SPAC);
std::cin.clear();
std::cin.ignore(256, '\n');
return 0;
}
}
return 0;
}
/* Menu Navigation Functions */
void InputManager::upDownNav(unsigned int t_input, const int t_max) {
if (t_input == WKEY) {
selectState.y--;
if (selectState.y < 0) {
selectState.y = t_max;
}
}
if (t_input == SKEY) {
selectState.y++;
if (selectState.y > t_max) {
selectState.y = 0;
}
}
}
void InputManager::leftRightNav(unsigned int t_input, const int t_max) {
if (t_input == AKEY) {
selectState.x--;
if (selectState.x < 0) {
selectState.x = t_max;
}
}
if (t_input == DKEY) {
selectState.x++;
if (selectState.x > t_max) {
selectState.x = 0;
}
}
}
/* Inputs for Specific Scenes*/
void InputManager::seedInput() {
resetSelectState();
bool b_contin = false;
while (!b_contin) {
g_Scene.seed(g_Input.getSelectStateY(), g_Game.seed);
int keyPress = _getch();
g_Input.upDownNav(keyPress, 2);
switch (selectState.y) {
case 0: // Randomize Seed
if (keyPress == SPAC) {
g_Game.seed = rand() % 99999999 + 1111;
}
break;
case 1: // Input Custom Seed
if (keyPress == SPAC) {
g_Game.seed = intInput("Enter seed, then press [Enter]");
}
break;
case 2: // Continue
if (keyPress == SPAC) {
selectState.y = 0;
b_contin = true;
}
break;
}
}
resetSelectState();
}
/* WEAPONS */
void InputManager::weapons() {
bool b_contin = false;
resetSelectState();
while (!b_contin) {
g_Scene.weapons(selectState.y);
int keyPress = _getch();
g_Input.upDownNav(keyPress, 3);
switch (g_Input.getSelectStateY()) {
case 0: //Melee Shop
if (keyPress == SPAC) {
g_Input.melee();
}
break;
case 1: //Ranged Shop
if (keyPress == SPAC) {
g_Input.ranged();
}
break;
case 2: //Magic Shop
if (keyPress == SPAC) {
g_Input.magic();
}
break;
case 3: //Continue
if (keyPress == SPAC) {
b_contin = true;
}
}
}
resetSelectState();
}
void InputManager::melee() {
resetSelectState();
bool b_contin = false;
while (!b_contin) {
g_Scene.melee(selectState.y, g_Item.v_Weapons);
int keyPress = _getch();
upDownNav(keyPress, 3);
switch (selectState.y) {
case 0: //Rapier
if (keyPress == SPAC) {
b_contin = viewWeapons(g_Item.v_Weapons.at(0));
}
else if (keyPress == ENTR) {
b_contin = buyWeapons(g_Item.v_Weapons.at(0));
}
break;
case 1: //Claymore
if (keyPress == SPAC) {
b_contin = viewWeapons(g_Item.v_Weapons.at(1));
}
else if (keyPress == ENTR) {
b_contin = buyWeapons(g_Item.v_Weapons.at(1));
}
break;
case 2: //Small Shield
if (keyPress == SPAC) {
b_contin = viewWeapons(g_Item.v_Weapons.at(3));
}
else if (keyPress == ENTR) {
b_contin = buyWeapons(g_Item.v_Weapons.at(3));
}
break;
case 3: //Continue
if (keyPress == SPAC) {
b_contin = true;
}
break;
}
}
resetSelectState();
}
void InputManager::ranged() {
resetSelectState();
bool b_contin = false;
while (!b_contin) {
g_Scene.ranged(selectState.y, g_Item.v_Weapons);
int keyPress = _getch();
upDownNav(keyPress, 1);
switch (selectState.y) {
case 0: //Recurve Bow
if (keyPress == SPAC) {
b_contin = viewWeapons(g_Item.v_Weapons.at(5));
}
else if (keyPress == ENTR) {
b_contin = buyWeapons(g_Item.v_Weapons.at(5));
}
break;
case 1: //Continue
if (keyPress == SPAC) {
b_contin = true;
}
break;
}
}
resetSelectState();
}
void InputManager::magic() {
resetSelectState();
bool b_contin = false;
while (!b_contin) {
g_Scene.magic(selectState.y, g_Item.v_Weapons);
int keyPress = _getch();
upDownNav(keyPress, 2);
switch (selectState.y) {
case 0: //Saphire Staff
if (keyPress == SPAC) {
b_contin = viewWeapons(g_Item.v_Weapons.at(8));
}
else if(keyPress == ENTR){
b_contin = buyWeapons(g_Item.v_Weapons.at(8));
}
break;
case 1: //Book of Creation
if (keyPress == SPAC) {
b_contin = viewWeapons(g_Item.v_Weapons.at(11));
}
else if (keyPress == ENTR) {
b_contin = buyWeapons(g_Item.v_Weapons.at(11));
}
break;
case 2: //Continue
if (keyPress == SPAC) {
b_contin = true;
}
break;
}
}
resetSelectState();
}
bool InputManager::viewWeapons(Items::Weapon t_wep) {
g_Scene.viewWeapon(t_wep);
pause("Press [Space] to Continue!", 2, SPAC);
return false;
}
bool InputManager::buyWeapons(Items::Weapon t_wep){
//Add weapon to inventory, subtract gold by cost
if (g_Player.gold >= t_wep.cost) {
g_Player.gold -= t_wep.cost;
g_Player.aquireWep(t_wep);
pause("You bought a weapon! Press [Space] to continue!", 0, SPAC);
return true;
}
else {
pause("NOT ENOUGH GOLD: Press [Space] to Continue!", 0, SPAC);
return false;
}
}
void InputManager::wepInv()
{
resetSelectState();
bool b_contin = false;
while (!b_contin) {
if (!g_Player.v_Wep.empty()) {
g_Scene.viewWepInv(selectState.y, selectState.x);
int keyPress = _getch();
upDownNav(keyPress, 4);
switch (selectState.y) {
case 0: // Wep Select
leftRightNav(keyPress, g_Player.v_Wep.size() - 1);
break;
case 1: // Wep Inspect
if (keyPress == SPAC) {
g_Scene.viewWeapon(g_Player.v_Wep.at(selectState.x));
pause("Press [Space] to continue", 1, SPAC);
}
break;
case 2: //Equip weapon
if (keyPress == SPAC) {
g_Player.selectWep(g_Player.v_Wep.at(selectState.x));
}
break;
case 3: // Delete Weapon
// Delete g_Item
if (keyPress == SPAC) {
if (g_Player.v_Wep.at(selectState.x) == g_Player.selectedWep[0]) {
g_Player.selectedWep[0] = g_Item.v_Weapons.at(12);
}
else if (g_Player.v_Wep.at(selectState.x) == g_Player.selectedWep[1]) {
g_Player.selectedWep[1] = g_Item.v_Weapons.at(12);
}
g_Player.v_Wep.erase(g_Player.v_Wep.begin() + selectState.x);
b_contin = true;
}
break;
case 4: // Continue
//Reset g_Input and b_contin
if (keyPress == SPAC) {
selectState.x = 0;
selectState.y = 0;
b_contin = true;
}
break;
}
}
else { //If g_Player wep inv empty
pause("You do not have any Weapons. Press [Space] to continue", 0, SPAC);
b_contin = true;
}
}
resetSelectState();
}
/* ARMORS */
void InputManager::armors() {
resetSelectState();
bool b_contin = false;
while (!b_contin) {
g_Scene.armors(selectState.y, g_Item.v_Armors);
int keyPress = _getch();
upDownNav(keyPress, 2);
switch (selectState.y) {
case 0: //Light Armor
if (keyPress == SPAC) {
b_contin = viewArmors(g_Item.v_Armors.at(0));
}
else if (keyPress == ENTR) {
b_contin = buyArmors(g_Item.v_Armors.at(0));
}
break;
case 1: //Medium Armor
if (keyPress == SPAC) {
b_contin = viewArmors(g_Item.v_Armors.at(1));
}
else if (keyPress == ENTR) {
b_contin = buyArmors(g_Item.v_Armors.at(1));
}
break;
case 2: //Continue
if (keyPress == SPAC) {
b_contin = true;
}
break;
}
}
resetSelectState();
}
bool InputManager::viewArmors(Items::Armor t_arm) {
g_Scene.viewArmor(t_arm);
pause("Press [Space] to Continue!", 1, SPAC);
return false;
}
bool InputManager::buyArmors(Items::Armor t_arm) {
//Add weapon to inventory, subtract gold by cost
if (g_Player.gold >= t_arm.cost) {
g_Player.gold -= t_arm.cost;
g_Player.aquireArm(t_arm);
pause("You bought armor! Press [Space] to continue!", 0, SPAC);
return true;
}
else {
pause("NOT ENOUGH GOLD: Press [Space] to Continue!", 0, SPAC);
return false;
}
}
void InputManager::armInv() {
resetSelectState();
bool b_contin = false;
while (!b_contin) {
if (!g_Player.v_Arm.empty()) {
g_Scene.viewArmInv(selectState.y, selectState.x);
int keyPress = _getch();
upDownNav(keyPress, 4);
switch (selectState.y) {
case 0: // Armor Select
leftRightNav(keyPress, g_Player.v_Arm.size() - 1);
break;
case 1: // Armor Inspect
if (keyPress == SPAC) {
g_Scene.viewArmor(g_Player.v_Arm.at(selectState.x));
pause("Press [Space] to continue", 1, SPAC);
}
break;
case 2: //Equip Armor
if (keyPress == SPAC) {
g_Player.selectArm(g_Player.v_Arm.at(selectState.x));
}
break;
case 3: // Delete Armor
// Delete g_Item
if (keyPress == SPAC) {
if (g_Player.v_Arm.at(selectState.x) == g_Player.selectedArm) {
g_Player.selectedArm = g_Item.v_Armors.at(3); //Armor is now empty armor
}
g_Player.v_Arm.erase(g_Player.v_Arm.begin() + selectState.x);
b_contin = true;
}
break;
case 4: // Continue
//Reset g_Input and b_contin
if (keyPress == SPAC) {
resetSelectState();
b_contin = true;
}
break;
}
}
else { //If g_Player wep inv empty
pause("You do not have any Armors. Press [Space] to continue", 0, SPAC);
b_contin = true;
}
}
resetSelectState();
}
/* CONSUMABLES */
void InputManager::consume() {
resetSelectState();
bool b_contin = false;
while (!b_contin) {
g_Scene.consume(selectState.y, g_Item.v_Consumes);
int keyPress = _getch();
upDownNav(keyPress, 2);
switch (selectState.y) {
case 0: //Lesser healing potion
if (keyPress == SPAC) {
b_contin = viewCon(g_Item.v_Consumes.at(0));
}
else if (keyPress == ENTR) {
b_contin = buyCon(g_Item.v_Consumes.at(0));
}
break;
case 1: //Healing potion
if (keyPress == SPAC) {
b_contin = viewCon(g_Item.v_Consumes.at(1));
}
else if (keyPress == ENTR) {
b_contin = buyCon(g_Item.v_Consumes.at(1));
}
break;
case 2: //Continue
if (keyPress == SPAC) {
b_contin = true;
}
break;
}
}
resetSelectState();
}
bool InputManager::viewCon(Items::Consumable t_con) {
g_Scene.viewConsume(t_con);
pause("Press [Space] to Continue!", 2, SPAC);
return false;
}
bool InputManager::buyCon(Items::Consumable t_con) {
//Add weapon to inventory, subtract gold by cost
if (g_Player.gold >= t_con.cost) {
g_Player.gold -= t_con.cost;
g_Player.aquireCon(t_con);
pause("You bought a Consumable! Press [Space] to continue!", 0, SPAC);
return true;
}
else {
pause("NOT ENOUGH GOLD: Press [Space] to Continue!", 0, SPAC);
return false;
}
}
void InputManager::conInv() {
resetSelectState();
bool b_contin = false;
while(!b_contin)
if (!g_Player.v_Con.empty()) {
g_Scene.viewConInv(selectState.y, selectState.x);
int keyPress = _getch();
upDownNav(keyPress, 4);
switch (selectState.y) {
case 0: // Consume Select
leftRightNav(keyPress, g_Player.v_Con.size() - 1);
break;
case 1: // Consume Inspect
if (keyPress == SPAC) {
g_Scene.viewConsume(g_Player.v_Con.at(selectState.x));
pause("Press [Space] to continue", 2, SPAC);
}
break;
case 2: //Use Consume
if (keyPress == SPAC) {
g_Player.useConsume(g_Player.v_Con.at(selectState.x), selectState.x);
b_contin = true;
}
break;
case 3: // Delete Consume
// Delete g_Item
if (keyPress == SPAC) {
g_Player.v_Con.erase(g_Player.v_Con.begin() + selectState.x);
b_contin = true;
}
break;
case 4: // Continue
//Reset g_Input and b_contin
if (keyPress == SPAC) {
selectState.x = 0;
selectState.y = 0;
b_contin = true;
}
break;
}
}
else { //If g_Player consumables inv empty
pause("You do not have any Consumables. Press [Space] to continue", 0, SPAC);
b_contin = true;
}
resetSelectState();
}
//Inventory Input/Scene
void InputManager::inventory() {
resetSelectState();
bool b_contin = false;
while (!b_contin) {
g_Scene.viewInventory(selectState.y);
int keyPress = _getch();
upDownNav(keyPress, 3);
switch (selectState.y) {
case 0: // Weapons Inventory
if (keyPress == SPAC) {
wepInv();
b_contin = false;
}
break;
case 1: // Armor
if (keyPress == SPAC) {
g_Input.armInv();
b_contin = false;
}
break;
case 2: // Consumables
if (keyPress == SPAC) {
g_Input.conInv();
b_contin = false;
}
break;
case 3: // Continue
if (keyPress == SPAC) {
b_contin = true;
}
break;
}
}
resetSelectState();
}
bool InputManager::wander() {
if (bState == e_gameState::INSPECT) {
g_Scene.wander(selectState.x);
int keyPress = _getch();
g_Input.leftRightNav(keyPress, 2);
switch (selectState.x) {
case 0: // Actions (move forward)
if (keyPress == SPAC) {
bState = e_gameState::ACTION;
}
break;
case 1: // Inventory (Prompts inventory)
if (keyPress == SPAC) {
inventory();
}
break;
case 2: // Other (g_Game Exit, Tutorials)
if (keyPress == SPAC) {
if (other()) {
return true;
}
}
break;
}
}
else if (bState == e_gameState::ACTION) {
g_Scene.action(selectState.x);
int keyPress = _getch();
g_Input.leftRightNav(keyPress, 2);
switch (selectState.x) {
case 0: // Change View
if (keyPress == SPAC) {
bState = e_gameState::INSPECT;
}
break;
case 1: // Onwards
if (keyPress == SPAC) {
//Player stuff
//Speed
g_Player.speed = g_Player.maxSpeed;
//Stress
g_Player.stress += 1;
if (g_Player.clas == Character::e_Class::RANGER) {
g_Player.selectedWep.at(0).uses = 2;
}
else {
g_Player.selectedWep.at(0).uses = 1;
}
g_Player.selectedWep.at(1).uses = 1;
if (g_Player.clas == Character::e_Class::WARRIOR) {
if (g_Player.health < g_Player.maxHealth) {
g_Player.health++;
}
}
g_Game.b_isPlayerTurn = true;
g_Game.b_inBattle = true;
g_Game.roomGenerator();
bState = e_gameState::PLAYER;
}
break;
case 2: // Other
if (keyPress == SPAC) {
if (other()) {
return true;
}
}
break;
}
}
return false;
}
bool InputManager::other() {
resetSelectState();
bool b_contin = false;
while (!b_contin) {
g_Scene.other(selectState.y);
int keyPress = _getch();
upDownNav(keyPress, 3);
switch (selectState.y) {
case 0: //Tut on Character
if (keyPress == SPAC) {
g_Scene.charTut1();
pause("Press [Space] to cotinue to the next Page.", 2, SPAC);
g_Scene.charTut2();
pause("Press [Space] to Continue.", 2, SPAC);
}
break;
case 1: //Tut on Combat
if (keyPress == SPAC) {
g_Scene.combatTut1();
pause("Press [Space] to cotinue to the next Page.", 2, SPAC);
g_Scene.combatTut2();
pause("Press [Space] to Continue.", 2, SPAC);
}
break;
case 2: // Exit
if(keyPress == SPAC){
//Exit Game
return true;
}
break;
case 3: // Continue
if (keyPress == SPAC) {
b_contin = true;
}
break;
}
}
resetSelectState();
return false;
}
bool InputManager::battle() {
//Display
switch (bState) {
case e_gameState::PLAYER:
g_Scene.battlePlayer(selectState.x);
break;
case e_gameState::ENEMY:
g_Scene.battleEnemy(selectState.x);
break;
case e_gameState::MAP:
g_Scene.battleMap(selectState.x);
break;
}
if (g_Game.b_isPlayerTurn) {
//Input
int keyPress = _getch();
leftRightNav(keyPress, 2);
//Process
switch (selectState.x) {
case 0:
if (keyPress == SPAC) {
switch (bState) {
case e_gameState::PLAYER:
bState = e_gameState::ENEMY;
break;
case e_gameState::ENEMY:
bState = e_gameState::MAP;
break;
case e_gameState::MAP:
bState = e_gameState::PLAYER;
break;
}
}
break;
case 1: // ACTIONS
if (keyPress == SPAC) {
switch (bState) {
case e_gameState::PLAYER: // Inventory
inventory();
break;
case e_gameState::ENEMY: //ATTACK INPUT
battleAction();
break;
case e_gameState::MAP: //MOVEMENT INPUT
moveInput();
break;
}
}
break;
case 2: // Other (Game Exit, Tutorials)
if (keyPress == SPAC) {
if (other()) {
return true;
}
}
break;
}
if (keyPress == ENTR) { //Skip turn
g_Game.b_isPlayerTurn = false;
pause("You have ended your turn! Press [Space] to continue!", 0, SPAC);
}
}
else { //Not player's turn, Process Enemy turns and setup.
for (auto e : g_Game.v_Enemy) {
e->speed = e->maxSpeed;
e->enemyTurn();
}
//Player stuff
//Speed
g_Player.speed = g_Player.maxSpeed;
//Stress
g_Player.stress++;
if (g_Player.stress >= g_Player.maxStress) {
pause("You become self destructive, and lose a 1/4 of your health", 0);
g_Player.health -= (g_Player.maxHealth / 4);
g_Player.stress = 0;
}
//Reset Block
g_Player.b_block = true;
g_Player.block = 1;
g_Player.blockType = Items::e_Type::NONE;
if (g_Player.clas == Character::e_Class::RANGER) {
g_Player.selectedWep.at(0).uses = 2;
}
else {
g_Player.selectedWep.at(0).uses = 1;
}
g_Player.selectedWep.at(1).uses = 1;
g_Game.b_isPlayerTurn = true;
//Check if player is dead
if (g_Player.health <= 0) {
return true;
}
}
return false;
}
void InputManager::battleAction() {
resetSelectState();
bool b_contin = false;
while (!b_contin) {
g_Scene.battleAction(selectState.y);
//Input
int keyPress = _getch();
upDownNav(keyPress, 3);
switch (selectState.y) {
case 0: // Wep 1
if (keyPress == SPAC) {
playerAttack(g_Player.selectedWep.at(0));
}
break;
case 1: // Wep 2
if (keyPress == SPAC) {
playerAttack(g_Player.selectedWep.at(1));
}
break;
case 2: // Block
if (keyPress == SPAC ) {
if (g_Player.b_block) {
pause("You ready for an attack. Press [Space] to continue!", 0, SPAC);
g_Player.blockType = g_Player.selectedWep.at(0).type;
switch (g_Player.blockType) {
case Items::e_Type::NONE:
g_Player.block = 0.95f;
break;
case Items::e_Type::MELEE:
if (g_Player.selectedWep.at(0) == g_Item.v_Weapons.at(3) || g_Player.selectedWep.at(0) == g_Item.v_Weapons.at(4)) {
g_Player.block = 0.70f;
}
else {
g_Player.block = 0.80f;
}
break;
case Items::e_Type::RANGED:
g_Player.block = 0.90f;
break;
case Items::e_Type::MAGIC:
g_Player.block = 0.85f;
break;
}
g_Player.speed = 0;
b_contin = true;
}
else {
pause("You have already moved! Press [Space] to continue!", 0, SPAC);
}
}
break;
case 3: // Back
if (keyPress == SPAC) {
b_contin = true;
}
break;
}
}
}
void InputManager::playerAttack(Items::Weapon& t_wep) {
resetSelectState();
bool b_contin = false;
selectState.y = 1;
while (!b_contin) {
g_Scene.playerAttack(t_wep, selectState.y);
int keyPress = _getch();
upDownNav(keyPress, g_Game.v_Enemy.size());
if (selectState.y == 0 && keyPress == SPAC) {
b_contin = true;
break;
}
if (keyPress == SPAC) {
if (t_wep.uses > 0) {
if (((t_wep.range + g_Player.pos.x >= g_Game.v_Enemy.at(selectState.y - 1)->pos.x) && (t_wep.range - g_Player.pos.x <= g_Game.v_Enemy.at(selectState.y - 1)->pos.x))
&& ((t_wep.range + g_Player.pos.y >= g_Game.v_Enemy.at(selectState.y - 1)->pos.y) && (t_wep.range - g_Player.pos.y <= g_Game.v_Enemy.at(selectState.y - 1)->pos.y))) {
if ((g_Player.stats.perception * 2) + g_Player.pos.x >= g_Game.v_Enemy.at(selectState.y - 1)->pos.x){
int hitChance = 0;
int randChance = rand() % 10 + 1;
switch (t_wep.type) {
case Items::e_Type::MELEE:
hitChance = g_Player.stats.strength;
break;
case Items::e_Type::RANGED:
hitChance = g_Player.stats.perception;
break;
case Items::e_Type::MAGIC:
hitChance = g_Player.stats.wisdom;
break;
}
if (hitChance > randChance) {
bool b_isDead = g_Game.v_Enemy.at(selectState.y - 1)->takeDamage(t_wep);
if (b_isDead) {
g_Game.v_Enemy.erase(g_Game.v_Enemy.begin() + selectState.y - 1);
}
t_wep.uses--;
b_contin = true;
break;
}
else {
g_Player.stress += 2;
pause("You missed your attack.", 0);
t_wep.uses--;
b_contin = true;
break;
}
}
else {
pause("Your perception isn't good enough to hit this target! Press [Space] to Continue!", 0, SPAC);
b_contin = true;
break;
}
}
else {
pause("Your weapon doesn't have enough range to hit this target! Press [Space] to Continue!", 0, SPAC);
b_contin = true;
break;
}
}
else {
pause("Your weapon doesn't have anymore uses! Press [Space] to Continue!", 0, SPAC);
}
}
}
resetSelectState();
g_Player.levelUp();
resetSelectState();
}
void InputManager::levelUp(Character::Stats& t_stats) {
resetSelectState();
bool b_contin = false;
while (!b_contin) {
g_Scene.levelUp(t_stats, selectState.y);
int keyPress = _getch();
upDownNav(keyPress, 5);
switch (selectState.y) {
case 0: // Str
if (keyPress == SPAC) {
t_stats.strength++;
b_contin = true;
}
break;
case 1: // Fort
if (keyPress == SPAC) {
t_stats.fortitude++;
b_contin = true;
}
break;
case 2: // Agl
if (keyPress == SPAC) {
t_stats.agility++;
b_contin = true;
}
break;
case 3: // Wis
if (keyPress == SPAC) {
t_stats.wisdom++;
b_contin = true;
}
break;
case 4: // Perc
if (keyPress == SPAC) {
t_stats.perception++;
b_contin = true;
}
break;
case 5: // Tutorial
if (keyPress == SPAC) {
g_Scene.charTut1();
pause("Press [Space] to cotinue to the next Page.", 2, SPAC);
g_Scene.charTut2();
pause("Press [Space] to Continue.", 2, SPAC);
}
break;
}
}
}
/* Inputs for Scrolls in Scenes */
void InputManager::diffInput(SelectState t_selectState) {
switch (t_selectState.x) {
case 0:
g_Game.diff = "Easy";
g_Game.diffRate = 0.80f;
break;
case 1:
g_Game.diff = "Normal";
g_Game.diffRate = 1.00f;
break;
case 2:
g_Game.diff = "Hard";
g_Game.diffRate = 1.20f;
break;
}
}
void InputManager::raceInput(SelectState t_selectState) {
switch (t_selectState.x) {
case 0:
g_Player.raceStr = "Elf";
g_Player.race = Character::e_Race::ELF;
break;
case 1:
g_Player.raceStr = "Orc";
g_Player.race = Character::e_Race::ORC;
break;
case 2:
g_Player.raceStr = "Human";
g_Player.race = Character::e_Race::HUMAN;
break;
case 3:
g_Player.raceStr = "Goblin";
g_Player.race = Character::e_Race::GOBLIN;
break;
case 4:
g_Player.raceStr = "Dwarf";
g_Player.race = Character::e_Race::DWARF;
break;
case 5:
g_Player.raceStr = "Gnome";
g_Player.race = Character::e_Race::GNOME;
break;
}
}
void InputManager::clasInput(SelectState t_selectState) {
switch (t_selectState.x) {
case 0:
g_Player.clasStr = "Warrior";
g_Player.clas = Character::e_Class::WARRIOR;
break;
case 1:
g_Player.clasStr = "Ranger";
g_Player.clas = Character::e_Class::RANGER;
break;
case 2:
g_Player.clasStr = "Magician";
g_Player.clas = Character::e_Class::MAGICIAN;
break;
case 3:
g_Player.clasStr = "Bandit";
g_Player.clas = Character::e_Class::BANDIT;
break;
}
}
void InputManager::moveInput() {
if (g_Player.speed > 0) {
while (g_Game.b_inBattle) {
g_Scene.battleMap(3);
output(static_cast<std::string>("Moves left: ").append(std::to_string(g_Player.speed)), 0);
if (g_Player.clas == Character::e_Class::BANDIT) {
output("Press [Space] to pause your move!", 0);
}
else {
output("Press [Space] to end your move!", 0);
}
int keyPress = _getch();
g_Player.prevPos = g_Player.pos;
switch (keyPress) {
case WKEY:
if (g_Player.speed > 0) {
g_Player.pos.y -= 1;
g_Player.speed -= 1;
}
break;
case AKEY:
if (g_Player.speed > 0) {
g_Player.pos.x -= 1;
g_Player.speed -= 1;
}
break;
case SKEY:
if (g_Player.speed > 0) {
g_Player.pos.y += 1;
g_Player.speed -= 1;
}
break;
case DKEY:
if (g_Player.speed > 0) {
g_Player.pos.x += 1;
g_Player.speed -= 1;
}
break;
case SPAC:
if (g_Player.clas != Character::e_Class::BANDIT) {
g_Player.speed = 0;
}
return;
}
g_Game.checkCollision();
}
if (g_Game.b_inBattle) {
g_Scene.battleMap(3);
}
}
else if (g_Game.b_inBattle) {
pause("You have already moved! Press [Space] to continue!", 0, SPAC);
}
} | true |
189b58bb6a78f3327266f14e7b86654ee7919c6a | C++ | ChrisTwaitees/ChromaEngine | /Chroma/Chroma/source/models/StaticMesh.cpp | UTF-8 | 6,972 | 2.78125 | 3 | [
"MIT"
] | permissive | #include "StaticMesh.h"
void StaticMesh::setupMesh()
{
// Generate buffers
// Vertex Array Object Buffer
glGenVertexArrays(1, &VAO);
// Vertex Buffer and Element Buffer
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
// Bind buffers
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int),
&indices[0], GL_STATIC_DRAW);
// vertex positions
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
// vertex normals
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Normal));
// vertex uvs
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, TexCoords));
// vertex tangents
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Tangent));
// vertex bitangents
glEnableVertexAttribArray(4);
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Bitangent));
glBindVertexArray(0);
}
void StaticMesh::updateUniforms(const Shader* updateShader, std::vector < std::shared_ptr<Light>> Lights, Camera& RenderCam, glm::mat4& TransformMatrix)
{
updateTransformUniforms(updateShader, RenderCam, TransformMatrix);
updateTextureUniforms(updateShader);
updateMaterialUniforms(updateShader);
updateLightingUniforms(updateShader, Lights, RenderCam);
}
void StaticMesh::updateLightingUniforms(const Shader* shader, std::vector < std::shared_ptr<Light>> Lights, Camera& renderCam)
{
int pointlights{ 0 };
int dirlights{ 0 };
int spotlights{ 0 };
for (int i = 0; i < Lights.size(); i++)
{
std::string lightIndex;
// set uniforms
switch (Lights[i]->type) {
case Light::POINT:
pointlights++;
lightIndex = "pointLights[" + std::to_string(pointlights - 1) + "]";
break;
case Light::SUNLIGHT :
case Light::DIRECTIONAL :
dirlights++;
lightIndex = "dirLights[" + std::to_string(dirlights - 1) + "]";
break;
case Light::SPOT:
spotlights++;
lightIndex = "spotLights[" + std::to_string(spotlights - 1) + "]";
break;
default:
break;
}
//// lights directional
shader->setVec3(lightIndex + ".direction", Lights[i]->direction);
shader->setVec3(lightIndex + ".position", Lights[i]->position);
shader->setVec3(lightIndex + ".diffuse", Lights[i]->diffuse);
shader->setFloat(lightIndex + ".intensity", Lights[i]->intensity);
//// lights spotlight
shader->setFloat(lightIndex + ".spotSize", Lights[i]->spotSize);
shader->setFloat(lightIndex + ".penumbraSize", Lights[i]->penumbraSize);
//// lights point light falloff
shader->setFloat(lightIndex + ".constant", Lights[i]->constant);
shader->setFloat(lightIndex + ".linear", Lights[i]->linear);
shader->setFloat(lightIndex + ".quadratic", Lights[i]->quadratic);
//// lights view pos
shader->setVec3("viewPos", renderCam.get_position());
}
}
void StaticMesh::updateTextureUniforms(const Shader* shader)
{
// updating shader's texture uniforms
unsigned int diffuseNr{ 1 };
unsigned int specularNr{ 1 };
unsigned int shadowmapNr{ 1 };
unsigned int normalNr{ 1 };
for (int i = 0; i < textures.size(); i++)
{
glActiveTexture(GL_TEXTURE0 + i);// activate proper texture unit before binding
// building the uniform name
std::string name;
std::string texturenum;
if (textures[i].type == Texture::DIFFUSE)
{
name = "material.texture_diffuse";
texturenum = std::to_string(diffuseNr++);
}
if (textures[i].type == Texture::SPECULAR)
{
name = "material.texture_specular";
texturenum = std::to_string(specularNr++);
}
if (textures[i].type == Texture::SHADOWMAP)
{
name = "shadowmaps.shadowmap";
texturenum = std::to_string(shadowmapNr++);
}
if (textures[i].type == Texture::NORMAL)
{
name = "material.texture_normal";
texturenum = std::to_string(normalNr++);
}
// setting uniform and binding texture
shader->setInt(( name + texturenum).c_str(), i);
glBindTexture(GL_TEXTURE_2D, textures[i].ShaderID);
// activate texture
}
glActiveTexture(GL_TEXTURE0);
}
void StaticMesh::updateTransformUniforms(const Shader* shader, Camera& renderCam, glm::mat4& modelMatrix)
{
glm::mat4 finalTransform = getTransformationMatrix() * modelMatrix;
shader->setMat4("model", finalTransform);
shader->setMat4("view", renderCam.viewMat);
shader->setMat4("projection", renderCam.projectionMat);
}
void StaticMesh::updateMaterialUniforms(const Shader* shader)
{
shader->setFloat("material.ambientBrightness", 0.16f);
shader->setFloat("material.roughness", 64.0f);
shader->setFloat("material.specularIntensity", 1.0f);
shader->setFloat("material.cubemapIntensity", 1.0f);
}
void StaticMesh::Draw(Shader &shader)
{
shader.use();
// draw mesh
BindDrawVAO();
}
void StaticMesh::Draw(Camera& RenderCamera, std::vector < std::shared_ptr<Light>> Lights, glm::mat4& transformMatrix)
{
pShader->use();
updateUniforms(pShader, Lights, RenderCamera, transformMatrix);
BindDrawVAO();
}
void StaticMesh::Draw(Shader& shader, Camera& RenderCamera, std::vector < std::shared_ptr<Light>> Lights, glm::mat4& transformMatrix)
{
shader.use();
updateUniforms(&shader, Lights, RenderCamera, transformMatrix);
BindDrawVAO();
}
void StaticMesh::BindDrawVAO()
{
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0); // reset to default
}
void StaticMesh::bindShader(Shader* newShader)
{
pShader = newShader;
}
void StaticMesh::bindTextures(std::vector<Texture> textures_val)
{
for (unsigned int i = 0; textures_val.size(); i++)
{
bool skip{ false };
for (unsigned int j = 0; j < textures.size(); j++)
{
if (std::strcmp(textures[j].path.data(), textures_val[j].path.data()) == 0)
{
skip = true;
break;
}
}
if (!skip)
textures.push_back(textures_val[i]);
}
}
void StaticMesh::bindTexture(Texture texture_val)
{
bool skip{false};
for (unsigned int i = 0; i < textures.size(); i++)
{
skip = false;
if (std::strcmp(textures[i].path.data(), texture_val.path.data()) == 0)
{
skip = true;
break;
}
}
if (!skip)
{
textures.push_back(texture_val);
}
}
void StaticMesh::setMat4(std::string name, glm::mat4 value)
{
pShader->setMat4(name, value);
}
void StaticMesh::setInt(std::string name, int value)
{
pShader->setInt(name, value);
}
StaticMesh::StaticMesh(std::vector<Vertex> vertices_val, std::vector<unsigned int> indices_val, std::vector<Texture> textures_val)
{
isRenderable = true;
vertices = vertices_val;
indices = indices_val;
textures = textures_val;
setupMesh();
}
StaticMesh::StaticMesh()
{
isRenderable = true;
}
StaticMesh::~StaticMesh()
{
delete pShader;
}
| true |
7e58d922cc4e4255a72d31e715b60ead8a70a7dd | C++ | Lisoleg555/OOP | /lab6/tree.cpp | UTF-8 | 1,365 | 2.828125 | 3 | [] | no_license | #include "tree.h"
template <class F> TTree<F>::TTree() : seed(nullptr){
}
template <class F> std::ostream& operator<<(std::ostream& os, const TTree<F>& tree)
{
std::shared_ptr<TTreeItem<F>> item = tree.seed;
if(item == nullptr)
{
return os;
}
item->Show();
return os;
}
template <class F> void TTree<F>::push(std::shared_ptr<F> figure, int k)
{
seed = seed->Set(nullptr, seed, figure, k);
}
template <class F> std::shared_ptr<TTreeItem<F>> TTree<F>::GetSeed()
{
return this->seed;
}
template <class F> std::shared_ptr<F> TTree<F>::pop()
{
std::shared_ptr<F> result;
std::shared_ptr<TTreeItem<F>> oldSeed;
if(seed != nullptr)
{
if(seed->CheckLeft())
{
oldSeed = seed->GetLeft(seed);
result = oldSeed->GetFigure();
seed = seed->DelItem(oldSeed, seed);
oldSeed = nullptr;
}
else
{
oldSeed = seed;
result = seed->GetFigure();
seed = seed->DelItem(oldSeed, seed);
oldSeed = nullptr;
}
}
return result;
}
template <class F> TIterator<F, TTreeItem<F>> TTree<F>::begin()
{
return TIterator<F, TTreeItem<F>>(seed->Min(seed));
}
template <class F> TIterator<F, TTreeItem<F>> TTree<F>::end()
{
return TIterator<F, TTreeItem<F>>(nullptr);
}
template <class F> TTree<F>::~TTree(){
}
#include "figure.h"
template class TTree<Figure>;
template std::ostream& operator<<(std::ostream& os, const TTree<Figure>& obj);
| true |
cd332ca29b9c82e6ef40e24a41eaff3a6e4a2820 | C++ | openvkl/openvkl | /openvkl/devices/cpu/common/Allocator.h | UTF-8 | 1,518 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | // Copyright 2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <atomic>
#include "../common/ManagedObject.h"
#include "rkcommon/memory/malloc.h"
namespace openvkl {
namespace cpu_device {
/*
* Allocate and deallocate aligned blocks of
* memory safely, and keep some stats.
*/
class Allocator : public ManagedObject
{
public:
Allocator() = default;
Allocator(const Allocator &) = delete;
Allocator &operator=(const Allocator &) = delete;
Allocator(Allocator &&) = delete;
Allocator &operator=(Allocator &&) = delete;
~Allocator() = default;
template <class T>
T *allocate(size_t size);
template <class T>
void deallocate(T *&ptr);
private:
std::atomic<size_t> bytesAllocated{0};
};
// -------------------------------------------------------------------------
template <class T>
inline T *Allocator::allocate(size_t size)
{
const size_t numBytes = size * sizeof(T);
bytesAllocated += numBytes;
T *buf = reinterpret_cast<T *>(rkcommon::memory::alignedMalloc(numBytes));
if (!buf)
throw std::bad_alloc();
std::memset(buf, 0, numBytes);
return buf;
}
template <class T>
inline void Allocator::deallocate(T *&ptr)
{
rkcommon::memory::alignedFree(ptr);
ptr = nullptr;
}
} // namespace cpu_device
} // namespace openvkl
| true |
88c72d92afc953e340d0236767bcd3e0dc40388c | C++ | apoorvKautilya21/Data-Structures-And-Algorithm-in-C- | /12. Recursion Questions/13_stringGenerationAcode.cpp | UTF-8 | 926 | 3.53125 | 4 | [] | no_license | #include<iostream>
#include<cstring>
using namespace std;
int string2Int(char *c, int n) {
if(n == 0) {
return 0;
}
// Assumed that it will find 123
int num = string2Int(c, n - 1);
// when i have 123 i will multiply it with 10 and (c[n - 1] - '0') that's last element
num = num * 10 + (c[n - 1] - '0');
return num;
}
void generateAcodeStrings(char a[], char out[], int i, int j) {
// Base Case
if(a[i] == '\0') {
out[j] = '\0';
cout << out << endl;
return;
}
// Recursive Case
// taking one digit at a time
out[j] = 'A' + a[i] - '0' - 1;
generateAcodeStrings(a, out, i + 1, j + 1);
// taking 2 digits at a time
if(a[i+1] != '\0') {
int num = (a[i + 1] - '0') + (a[i] - '0') * 10 - 1;
if(num < 26) {
out[j] = 'A' + num;
generateAcodeStrings(a, out, i + 2, j + 1);
}
}
}
int main() {
char a[1000];
cin >> a;
char out[1000];
generateAcodeStrings(a, out, 0, 0);
return 0;
} | true |
9a5bfc416fd6c6a678d723fe562ce667dabd3f90 | C++ | alexandraback/datacollection | /solutions_2453486_0/C++/totoroXD/main.cpp | UTF-8 | 1,932 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<stack>
#include<string>
using namespace std;
char brd[5][5];
int cnt;
bool check_row(int i, char p)
{
int cntp=0,cntt=0;
for(int j=0; j<4; j++){
if(brd[i][j]==p){
cntp++;
}
else if(brd[i][j]=='T'){
cntt++;
}
}
return cntp==4 || (cntp==3 && cntt==1);
}
bool check_col(int i, char p)
{
int cntp=0,cntt=0;
for(int j=0; j<4; j++){
if(brd[j][i]==p){
cntp++;
}
else if(brd[j][i]=='T'){
cntt++;
}
}
return cntp==4 || (cntp==3 && cntt==1);
}
bool check_diag(char p){
int cntp=0,cntt=0;
for(int i=0; i<4; i++){
if(brd[i][i]==p){
cntp++;
}
else if(brd[i][i]=='T'){
cntt++;
}
}
if(cntp==4 || (cntp==3 && cntt==1))return 1;
cntp=0,cntt=0;
for(int i=0; i<4; i++){
if(brd[i][3-i]==p){
cntp++;
}
else if(brd[i][3-i]=='T'){
cntt++;
}
}
return cntp==4 || (cntp==3 && cntt==1);
}
bool check_full()
{
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
if(brd[i][j]=='.')return 0;
}
}
return 1;
}
void input()
{
for(int i=0; i<4; i++)scanf("%s",&brd[i]);
}
void solve()
{
printf("Case #%d: ",cnt+1);
for(int i=0; i<4; i++){
if(check_row(i, 'X')){
printf("X won\n");
return ;
}
else if(check_col(i, 'X')){
printf("X won\n");
return ;
}
else if(check_row(i, 'O')){
printf("O won\n");
return ;
}
else if(check_col(i, 'O')){
printf("O won\n");
return ;
}
}
if(check_diag('O'))
printf("O won\n");
else if(check_diag('X'))
printf("X won\n");
else if(check_full())
printf("Draw\n");
else
printf("Game has not completed\n");
}
int main ()
{
freopen("A-small-attempt0.in","r",stdin);
freopen("A-small-attempt0.out","w",stdout);
int zz;
scanf("%d",&zz);
for(cnt=0; cnt<zz; cnt++){
input();
solve();
}
}
| true |
f7a31f50a3ff9ae5c0a2e1f4d9799f14feaa19cf | C++ | prakhartp/codingNinjasProj | /L16/LinkedList.cpp | UTF-8 | 4,476 | 3.515625 | 4 | [] | no_license | #include<iostream>
using namespace std;
#include "Node.h"
Node* createList(){
Node* n1 = new Node(10);
Node* n2 = new Node(20);
Node* n3 = new Node(30);
Node* n4 = new Node(40);
n1->next = n2;
n2->next = n3;
n3->next = n4;
return n1;
/* Node n1(10);
Node n2(20);
Node n3(30);
n1.next = &n2;
n2.next = &n3;
cout <<"&n1 " << &n1 << " " << n1.data << " " << n1.next << endl;
cout <<"&n2 " << &n2 << " " << n2.data << " " << n2.next << endl;
cout <<"&n3 " << &n3 << " " << n3.data << " " << n3.next << endl;
Node* head = &n1;
return head;
*/
}
void print(Node* head){
Node* temp = head;
while(temp != NULL){
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
/*while(head != NULL){
cout << head->data << " ";
head = head->next;
}
cout << endl;
*/
//cout << head->data << endl;
//cout << head->next->data << endl;
//cout << head->next->next->data << endl;
}
void demo(Node* head){
Node* temp; // this will only create pointer and that too with garbage address
temp = new Node(1);
temp->data = 10;
head = new Node(10);
//head->data = 60;
//Runtime error - head->next->next;
//head = head->next;
//head->next = head;
}
Node* insertNode(Node *head, int pos, int data) {
// This is the node to be inserted
Node* newNode = new Node(data);
if(pos == 0){
newNode->next = head;
// Bakwas
//head = newNode;
return newNode;
}else{
int i = 0;
Node* prev = head;
while(prev!= NULL && i < pos - 1){
prev = prev->next;
i++;
}
// prev will point to Node at pos - 1
if(prev != NULL){
newNode->next = prev->next;
prev->next = newNode;
}
return head;
}
}
Node* deleteNode(Node* head, int i){
if(i == 0){
Node* newHead = head->next;
delete head;
return newHead;
}else{
int pos = 0;
Node* prev = head;
while(prev!= NULL && pos < i - 1){
prev = prev->next;
pos++;
}
// prev will point to Node at pos - 1
if(prev != NULL && prev->next != NULL){
Node* nodeToBeDeleted = prev->next;
prev->next = prev->next->next; // nodeToBeDeleted->next
delete nodeToBeDeleted;
}
return head;
}
}
Node* insertRec(Node* head, int i, int data){
if(i == 0){
Node* nodeToBeInserted = new Node(data);
nodeToBeInserted->next = head;
return nodeToBeInserted;
}
// List length is smaller than i
if(head == NULL){
return NULL;
}
Node* smallerListHead = insertRec(head->next, i - 1, data);
head->next = smallerListHead;
return head;
}
void increment(Node* head){
//head = new Node(1);
while(head != NULL){
head->data++;
head = head->next;
}
}
Node* takeInput(){
Node* head = NULL, * tail = NULL;
int data;
cin >> data;
while(data != -1){
Node* newNode = new Node(data);
if(head == NULL){
// If its first node
head = newNode;
tail = newNode;
}else{
/* Node* lastNode = head;
while(lastNode->next != NULL){
lastNode = lastNode->next;
}
lastNode->next = newNode;
*/
tail->next = newNode;
tail = newNode; // tail = tail->next;
}
cin >> data;
}
return head;
}
Node* mergeTwoLLs(Node* head1, Node* head2){
// Head will point to first Node of sorted List
// Tail will point to last Node of sorted list
Node* head = NULL, *tail = NULL;
Node* t1 = head1, *t2 = head2;
if(t1->data <= t2->data){
head = t1;
tail = t1;
t1 = t1->next;
}else{
head = t2;
tail = t2;
t2 = t2->next;
}
while(t1 != NULL && t2!= NULL){
if(t1->data <= t2->data){
tail->next = t1;
tail = t1; // tail = tail->next
t1 = t1->next;
}else{
tail->next = t2;
tail = t2;
t2 = t2->next;
}
}
if(t1 != NULL){
tail->next = t1;
}else{
tail->next = t2;
}
return head;
}
Node* midpoint(Node* head){
if(head == NULL){
return NULL;
}
Node* slow = head, *fast = head;
while(fast->next != NULL && fast->next->next != NULL){
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
Node* mergeSort(Node* head){
if(head == NULL || head->next == NULL){
return head;
}
Node* part1Head = head;
// Split List in 2 parts
// Sort each part recursively
part1Head = mergeSort(part1Head);
// Merge
}
int main(){
Node* head = takeInput(); //createList();
head = mergeSort(head);
print(head);
//increment(head);
//head = insertNode(head,0, 80);
//print(head);
//demo(head);
//print(head);
//print(head->next);
/*
Node n1(10);
cout << n1.data << " " << n1.next << endl;
Node* n2 = new Node(20);
cout << n2->data << " " << n2->next << endl;
*/
}
| true |
b916a45835da7bb1758dc782c116bfe8a09cb899 | C++ | kumar-kunal/Algorithm | /DP/Bellman_Ford_Algorithm.cpp | UTF-8 | 1,718 | 3.1875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
const int m=100;
struct edges
{
int s,d,w;
};
struct edges edge[m];
int e=0;
//Make edge list so that we can travel ....
void collect_edge(int graph[m][m],int v)
{
for(int i=0;i<v;i++)
{
for(int j=0;j<v;j++)
{
if(graph[i][j]!=0)
{
edge[e].s=i;
edge[e].d=j;
edge[e].w=graph[i][j];
e++;
}
}
}
}
void BellmanFord(int graph[m][m],int v,int src)
{
int distance[v];
int parent[v];
for(int i=0;i<v;i++)
{
distance[i]=INT_MAX;
parent[i]=-1;
}
distance[src]=0;
for(int i=0;i<v-1;i++)
{
for(int j=0;j<e;j++)
{
int a=edge[j].s;
int b=edge[j].d;
int weight=edge[j].w;
if(distance[a]!=INT_MAX && distance[a]+weight<distance[b])
{
distance[b]=distance[a]+weight;
//parent[b]=a;
}
}
}
//check for -ve cycle
//run algo one more time.. if there is relaxation with any edge ,that means cycle.
for(int j=0;j<e;j++)
{
int a=edge[j].s;
int b=edge[j].d;
int weight=edge[j].w;
if(distance[a]!=INT_MAX && distance[a]+weight<distance[b])
{
printf("O hello... your graph has negative weight cycle!!!");
}
}
printf("Vertex Distance from source\n");
for(int i=0;i<v;i++)
{
if(distance[i]==INT_MAX)
{
printf("%d\t\tThere is no way from source\n",i);
}
else
printf("%d\t\t%d\n",i,distance[i]);
}
}
int main()
{
int v;
printf("Enter the no of vertices in the graph:\n");
scanf("%d",&v);
int graph[m][m];
printf("Enter the adjacency matrix of the graph:\n");
for(int i=0;i<v;i++)
{
for(int j=0;j<v;j++)
{
scanf("%d",&graph[i][j]);
}
}
int src;
printf("Enetr source\n");
scanf("%d",&src);
collect_edge(graph,v);
BellmanFord(graph,v,src);
} | true |