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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c45fcb98d6fbe830fdd789d7674cd153e9a36e00 | C++ | LinuxKernelDevelopment/cppprimer | /ch16/16.1/find.h | UTF-8 | 373 | 2.765625 | 3 | [] | no_license | #ifndef FIND_H
#define FIND_H
#include <set>
template <class T, typename U>
std::set<unsigned int> find(T vec, U key)
{
std::set<unsigned int> iset;
/*for (unsigned int i = 0; i <= vec.size(); i++) {
if (vec[i] == key)
iset.insert(i);
}*/
unsigned int i = 0;
for (auto tmp : vec) {
i++;
if (tmp == key) {
iset.insert(i);
}
}
return iset;
}
#endif
| true |
dc6a2ff3cb5fea47a4829e8f9e5c98a62578b3fb | C++ | tbfe-de/mc-cppmodern | /Exercises/06_Wednesday2_2/Airport.cpp | UTF-8 | 506 | 2.671875 | 3 | [] | no_license | #include "Airport.h"
#include "Connection.h"
using namespace std;
void Airport::addConnection(ConnectionRef c, size_t n) {
removeConnection(c);
connections.emplace_back(n, c);
}
void Airport::removeConnection(ConnectionRef c) {
connections.remove_if(
[c](const tuple<size_t, ConnectionRef> &_1) {
return get<1>(_1) == c;
}
);
}
const list<tuple<size_t, ConnectionRef>> &Airport::getConnections() const {
return connections;
}
size_t Airport::instances;
| true |
4002c34998276974ab1be3cbf1b9f09786cddabf | C++ | niangu/Qt-C- | /设计模式/Memento_Pattern/memo.h | UTF-8 | 578 | 3.171875 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
class Memo;
//发起人类
class Originator{
public:
string state;
Memo* CreateMemo();
void SetMemo(Memo* memo);
void Show()
{
cout<<"状态:"<<state<<endl;
}
};
//备忘录类
class Memo
{
public:
string state;
Memo(string strState)
{
state=strState;
}
};
Memo* Originator::CreateMemo()
{
return new Memo(state);
}
void Originator::SetMemo(Memo* memo)
{
state=memo->state;
}
//管理者类
class Caretaker
{
public:
Memo *memo;
};
#endif // MEMO_H
| true |
7629fcbb1b0f0a0d82d67da9bb72d545ccb3cd0a | C++ | laurashcherbak/cpp_oop | /Lab_6_7/Lab/Predicate.h | UTF-8 | 2,960 | 3.640625 | 4 | [] | no_license | //Predicate.h
#pragma once
#include <iostream>
using namespace std;
// інтерфейс, що описує функтори - унарні предикати
template<class T>
class Predicate
{
public:
virtual bool operator () (T x) = 0;
};
// реалізуємо інтерфейс функтором - перевірка, чи значення дорівнює нулю
template<class T>
class Zero : public Predicate<T>
{
public:
virtual bool operator () (T x)
{
T zero = T();
return x == zero;
}
};
// реалізуємо інтерфейс функтором - перевірка, чи значення додатне
// працює лише для числових типів
template<class T>
class Positive : public Predicate<T>
{
public:
virtual bool operator () (T x)
{
return x > 0;
}
};
// реалізуємо інтерфейс функтором - перевірка, чи значення від'ємне
// працює лише для числових типів
template<class T>
class Negative : public Predicate<T>
{
public:
virtual bool operator () (T x)
{
return x < 0;
}
};
// реалізуємо інтерфейс функтором - перевірка, чи значення парне
// працює лише для цілих типів
template<class T>
class Even : public Predicate<T>
{
public:
virtual bool operator () (T x)
{
return ((int)x % 2) == 0;
}
};
// реалізуємо інтерфейс функтором - перевірка, чи значення не парне
// працює лише для цілих типів
template<class T>
class Odd : public Predicate<T>
{
public:
virtual bool operator () (T x)
{
return ((int)x % 2) != 0;
}
};
// begin - ітератор початку вхідного контейнера (вказує на перший елемент)
// end - ітератор кінця вхідного контейнера (вказує на елемент після останнього)
template<class T>
bool search(T* begin, T* end, T* begin2, T* end2)
{
//T* from = begin;
T* from2 = begin2;
for (T* from = begin; from < end; from++) // from - ітератор першого контейнера
{
if (*from == *from2)
{
from2++; // from2 - ітератор другого контейнера
}
else
{
from2 = begin2;
}
if (*from2 == *end2)
return 1;
}
return 0;
}
template<class T>
bool search_if(T* begin, T* end, T* begin2, T* end2, Predicate<T>& p)
{
//T* from = begin;
T* from2 = begin2;
for (T* from = begin; from < end; from++) // from - ітератор першого контейнера
{
if (p(*from)) // якщо справджується умова предикату
{
if (*from == *from2)
{
from2++; // from2 - ітератор другого контейнера
}
else
{
from2 = begin2;
}
if (*from2 == *end2)
return 1;
}
}
return 0;
}
| true |
84085cfe284081fc141a9101c052673e8d4a3886 | C++ | mayank-75/Algorithms | /DSA/csacademy.cpp | UTF-8 | 3,654 | 3.265625 | 3 | [] | no_license | # include<bits/stdc++.h>
using namespace std ;
void generatePermutations(vector<vector<int>> &res, vector<int> comb, int index, vector<int> &v)
{
if(index >= v.size())
{
res.push_back(comb) ; return ;
}
for(int i=0;i<v.size();i++)
{
auto it = find(comb.begin(),comb.end(),i) ;
if(it == comb.end())
{
comb.push_back(i) ;
generatePermutations(res,comb,index+1,v) ;
comb.pop_back() ;
}
}
}
void printDistinctPermutations(vector<int>& v) {
sort(v.begin(),v.end()) ;
vector<vector<int>> res ;
vector<int> comb ;
generatePermutations(res,comb,0,v) ;
set<vector<int>> s ;
for(int i=0;i<res.size();i++)
{
vector<int> temp ;
for(int x : res[i])
{
temp.push_back(v[x]) ;
}
s.insert(temp) ;
}
for(auto it=s.begin();it!=s.end();it++)
{
for(int x : *it) cout<<x<<" " ;
cout<<endl ;
}
}
int main()
{
int t; cin>>t ;
while(t--)
{
int n ; cin>>n ;
vector<int> v(n) ;
for(int i=0;i<n;i++) cin>>v[i] ;
printDistinctPermutations(v);
}
}
/*void possibleSum(int n, int i, vector<int> &arr, vector<int> comb, vector<vector<int>> &res)
{
if(i >= arr.size()) return ;
if(n == 0)
{
res.push_back(comb) ;
return ;
}
if(n-arr[i] >=0)
{
comb.push_back(arr[i]) ;
possibleSum(n-arr[i],i+1,arr,comb,res) ;
comb.pop_back() ;
possibleSum(n,i+1,arr,comb,res) ;
}
else
{
possibleSum(n,i+1,arr,comb,res) ;
}
}
bool compare(vector<int> v1, vector<int> v2)
{
return v1.size() < v2.size() ;
}
vector<int> fibonacciSum(int n) {
vector<int> arr(2) ;
arr[0] = 0, arr[1] = 1 ;
while(arr.back() < n)
{
int x = arr.size() ;
arr.push_back(arr[x-1]+arr[x-2]) ;
}
/*for(int x : arr) cout<<x<<" " ;
cout<<endl ;
vector<vector<int>> res ;
vector<int> comb ;
possibleSum(n,0,arr,comb,res) ;
sort(res.begin(),res.end(),compare) ;
/*for(auto v : res)
{
for(int x : v) cout<<x<<" " ;
cout<<endl ;
}
return res[0] ;
}*/
/*vector<int> fibonacciSum(int n) {
vector<int> arr(2) ;
arr[0] = 0, arr[1] = 1 ;
while(arr.back() < n)
{
int x = arr.size() ;
arr.push_back(arr[x-1]+arr[x-2]) ;
}
vector<int> res ;
int x = arr.size() ;
for(int i=x-1;i>=0;i--)
{
if((int)(n/arr[i]))
{
int c = n/arr[i] ;
while(c--) res.push_back(arr[i]) ;
n = n%arr[i] ;
}
}
sort(res.begin(),res.end()) ;
return res ;
}
int main()
{
int t ; cin>>t ;
while(t--)
{
int n ; cin>>n ;
vector<int> res = fibonacciSum(n) ;
for(int x : res) cout<<x<<" " ;
cout<<endl ;
}
}*/
/*bool compare(vector<int> v1, vector<int> v2)
{
for(int i=0;i<v1.size();i++)
{
if(v1[i]!=v2[i]) return v1[i] < v2[i] ;
}
}
void generateCombinations(int N, int K) {
vector<vector<int>> res ;
int num = pow(2,N) ;
vector<int> temp ;
for(int i=0;i<num;i++)
{
temp.clear() ;
for(int j=0;j<N;j++)
{
if(i & (1<<j)) temp.push_back(j+1) ;
}
if(temp.size() == K)
{
res.push_back(temp) ;
}
}
sort(res.begin(),res.end(),compare) ;
for(auto v : res)
{
for(int x : v) cout<<x<<" " ;
cout<<endl ;
}
}
int main()
{
int t ; cin>>t;
while(t--)
{
int n,k ; cin>>n>>k ;
generateCombinations(n,k) ;
}
}*/
| true |
b86c0131b13cb9585cf7c29ec6ed20b2f7b7948d | C++ | kejn/job-shop-HGA | /jobshop_HGA/src/html/PageHTML.cpp | UTF-8 | 1,509 | 2.828125 | 3 | [] | no_license | /*
* GanttHTML.cpp
*
* Created on: 20 kwi 2016
* Author: Kamil
*/
#include "../../inc/html/PageHTML.h"
#include "../../inc/html/TextContentHTML.h"
#include <sstream>
using namespace std;
void PageHTML::add(const PageHTML::Section& section,
ContentHTML * const & childElement) {
if (section == Section::HEAD) {
_head.addChild(childElement);
} else if (section == Section::BODY) {
_body.addChild(childElement);
}
}
void PageHTML::addContentType(string contentType) {
TagContentHTML* meta = new TagContentHTML("meta");
meta->addParam("http-equiv", "Content-Type");
meta->addParam("content", contentType);
add(Section::HEAD, meta);
}
void PageHTML::addTitle(string title) {
TagContentHTML* titleTag = new TagContentHTML("title");
titleTag->addChild(new TextContentHTML(title));
add(Section::HEAD, titleTag);
}
void PageHTML::addStyle(string url) {
TagContentHTML* linkTag = new TagContentHTML("link");
linkTag->addParam("rel", "stylesheet");
linkTag->addParam("type", "text/css");
linkTag->addParam("href", url);
add(Section::HEAD, linkTag);
}
void PageHTML::addScript(string url) {
TagContentHTML* scriptTag = new TagContentHTML("script");
scriptTag->addChild(new TextContentHTML(""));
scriptTag->addParam("src", url);
add(Section::HEAD, scriptTag);
}
std::string PageHTML::toString() {
stringstream ss;
ss << "<!doctype html>\n";
ss << "<html>\n";
ss << _head.toString() << endl;
ss << _body.toString() << endl;
ss << "</html>" << endl;
return (ss.str());
}
| true |
701f576b4329c9047b1af96b4122d4a4bf60943f | C++ | Aleda/libsummer | /algorithm/basic-algorithm/sort/heapsort.cpp | UTF-8 | 1,443 | 3.515625 | 4 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
using namespace std;
void print(int *a, int n)
{
for (int i = 1; i <= n; i++)
{
printf("%d ", a[i]);
}
cout << endl;
}
void heapify(int *a, int x, int n)
{
int l = x << 1;
int r = x << 1 | 1;
int largest;
if (l <= n && a[l] > a[x])
{
largest = l;
}
else
{
largest = x;
}
if (r <= n && a[r] > a[largest])
{
largest = r;
}
if (largest != x)
{
int t = a[largest];
a[largest] = a[x];
a[x] = t;
heapify(a, largest, n);
}
}
void buildHeap(int *a, int n)
{
//在堆中(也就是完全二叉树中),叶子结点的数目应当等于总结点数目(n - n / 2), 所以非叶子结点的数目为n/2(下整)
for (int i = n / 2; i >= 1; i--)
{
heapify(a, i, n);
}
}
void heapSort(int *a, int n)
{
buildHeap(a, n);
print(a, n);
for (int i = n; i > 1; i--)
{
int t = a[i];
a[i] = a[1];
a[1] = t;
heapify(a, 1, i - 1);
}
}
int main()
{
int n;
int a[100];
scanf("%d", &n);
for (int i = 1; i <= n; i++) //由于创建堆的时候,根结点的编号是从1开始的,所以如果依旧按照从0开始编写序号的话,就不方便
{
scanf("%d", &a[i]);
}
heapSort(a, n);
print(a, n);
return 0;
}
| true |
1dbfec57135ce372f12a1fc051d736689c528cfc | C++ | fpischedda/ld33 | /main.cpp | UTF-8 | 649 | 2.90625 | 3 | [
"BSD-3-Clause"
] | permissive | #include <SFML/Graphics.hpp>
#include "director.hpp"
#include "test_scene.hpp"
int main()
{
sf::RenderWindow window(sf::VideoMode(640, 480), "SFML works!");
Director director;
TestScene scene;
director.set_scene(&scene);
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
switch (event.type){
case sf::Event::Closed:
window.close();
break;
case sf::Event::KeyPressed:
director.key_pressed(event.key.code);
break;
case sf::Event::KeyReleased:
director.key_released(event.key.code);
break;
}
}
director.update();
director.draw(window);
}
return 0;
}
| true |
cbb16f706c0a3fd578f7126717bd27b93dc6c835 | C++ | jafo2128/dht22 | /dht22.ino | UTF-8 | 2,563 | 2.734375 | 3 | [] | no_license | #include <SoftwareSerial.h>
#include <DHT22.h>
#define tx_PIN 2
#define DHT22_PIN 4
SoftwareSerial LCD = SoftwareSerial(0, tx_PIN);
DHT22 sensor(DHT22_PIN);
// since the LCD does not send data back to the Arduino, we should only define the txPin
const int LCDdelay=10; // conservative, 2 actually works
int flag = 0;
int cnt = 0;
void clearLCD() {
LCD.write(0xFE); //command flag
LCD.write(0x58); //clear command.
delay(LCDdelay);
}
void contrastLCD(char c) {
LCD.write(0xFE);
LCD.write(0x91);
LCD.write(c);
delay(LCDdelay);
}
void cursorOff() {
LCD.write(0xFE);
LCD.write(0x54);
delay(LCDdelay);
}
void backlightOn() { //turns on the backlight
LCD.write(0xFE); //command flag for backlight stuff
LCD.write(0x42); //light level.
delay(LCDdelay);
}
void backlightOff() { //turns off the backlight
LCD.write(0xFE); //command flag for backlight stuff
LCD.write(0x46); //light level for off.
delay(LCDdelay);
}
void lineOne() { //puts the cursor at line 0 char 0.
LCD.write(0xFE); //command flag
LCD.write(128); //position
}
void newLine() {
LCD.write(10);
}
void cursorHome() {
LCD.write(0xFE);
LCD.write(72);
}
void cursorSet(int xpos, int ypos){
LCD.write(017);
LCD.write(xpos); //Column position
LCD.write(ypos); //Row position
}
void setup() {
pinMode(tx_PIN, OUTPUT);
LCD.begin(9600);
delay(1000); // the LCD display take some time to initialize
clearLCD();
contrastLCD(255);
backlightOff();
LCD.print("Starting sensor");
}
void loop()
{
DHT22_ERROR_t errorCode;
errorCode = sensor.readData();
clearLCD();
switch(errorCode)
{
case DHT_ERROR_NONE:
char buf[128];
sprintf(buf, " Temp: %hi.%01hiC\nHumidity: %i.%01i%%",
sensor.getTemperatureCInt()/10, abs(sensor.getTemperatureCInt()%10),
sensor.getHumidityInt()/10, sensor.getHumidityInt()%10);
LCD.print(buf);
break;
case DHT_ERROR_CHECKSUM:
LCD.print("check sum error ");
break;
case DHT_BUS_HUNG:
LCD.print("BUS Hung");
break;
case DHT_ERROR_NOT_PRESENT:
LCD.print("Not Present");
break;
case DHT_ERROR_ACK_TOO_LONG:
LCD.print("ACK time out");
break;
case DHT_ERROR_SYNC_TIMEOUT:
LCD.print("Sync Timeout");
break;
case DHT_ERROR_DATA_TIMEOUT:
LCD.print("Data Timeout");
break;
case DHT_ERROR_TOOQUICK:
LCD.print("Polled to quick ");
break;
}
delay(10000); // We update poll the sensor every 10 sec
}
| true |
3aedd5b90f7d52bab63875c3a14fe4d2be02a143 | C++ | kamyu104/LeetCode-Solutions | /C++/maxPathSum.cpp | UTF-8 | 808 | 3.234375 | 3 | [
"MIT"
] | permissive | // Time Complexity: O(n)
// Space Complexity: O(logn)
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxPathSum(TreeNode *root) {
max_sum = INT_MIN;
dfs(root);
return max_sum;
}
private:
int max_sum;
int dfs(const TreeNode *root) {
if(!root) return 0;
int l = dfs(root->left);
int r = dfs(root->right);
int sum = root->val;
if(l > 0) sum += l;
if(r > 0) sum += r;
max_sum = max(max_sum, sum);
return max(r, l) > 0? max(r, l) + root->val : root->val;
}
};
| true |
9002476679b4945d16857d1579c7a851034d5301 | C++ | zetwhite/boj | /others/boj16917.cpp | UTF-8 | 324 | 2.9375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int A, B, C, X, Y;
cin >> A >> B >> C >> X >> Y;
if(A >= C*2)
A = C*2;
if(B >= C*2)
B = C*2;
if(A + B <= C*2){
cout << A*X + B*Y;
}
else{
int mix = min(X, Y);
cout << C*mix*2 + A*(X - mix) + B*(Y - mix);
}
return 0;
} | true |
4c6cbe770ba8853a8f24c14903847e8515ec1b8b | C++ | muffinista/palm-pitch | /Src/AI.cpp | UTF-8 | 32,042 | 2.984375 | 3 | [
"MIT"
] | permissive | #include "ComputerPlayer.h"
#include "GameManager.h"
extern GameManager *gManager;
ComputerPlayer::ComputerPlayer() : Player() {
TOLERANCE = 80;
VALUE_TOLERANCE = 80;
PARTNER_WIN_TOLERANCE = 85;
LOW_TRUMP_HOLD_VAL = (Int16)Card::five;
}
ComputerPlayer::ComputerPlayer(char c, CString name): Player(c, name) {
TOLERANCE = 80;
VALUE_TOLERANCE = 80;
PARTNER_WIN_TOLERANCE = 85;
LOW_TRUMP_HOLD_VAL = (Int16)Card::five;
}
ComputerPlayer::~ComputerPlayer() {
my_clubs.DeleteAll();
my_diamonds.DeleteAll();
my_hearts.DeleteAll();
my_spades.DeleteAll();
}
/* funcion for giving the computer's Player's bid */
Int16 ComputerPlayer::BeginBidProcess(Player *dealer, Player *current_winner) {
my_clubs.DeleteAll();
my_diamonds.DeleteAll();
my_hearts.DeleteAll();
my_spades.DeleteAll();
sortHand();
analyzeHand(current_winner);
return bid;
}
/*
AI logic:
if we are the first player, we want to win outright. Play our best card, unless it
stinks, and if so, play our worst card
if we are the second player, play junk unless we can take the 1st card and it is worth taking
if we are the 3rd player, we want to help our partner (the lead) if we can by throwing a tasty
card, but only if it is safe. otherwise, follow the rules for #2
if we are the last player, we want to sneak in a winning low card or ten if we can, otherwise throw junk
or win outright if it's worth doing
*/
Boolean ComputerPlayer::PickCard(Trick * trk) {
Card *i;
if ( played_card == NULL ) {
Boolean first = haveLeadPlay();
Boolean last = haveLastPlay();
if ( first ) {
HostTraceOutputTL(sysErrorClass, "play first");
i = first_pick_card(trk);
}
else if ( last ) {
HostTraceOutputTL(sysErrorClass, "play last");
i = last_pick_card(trk);
}
else {
HostTraceOutputTL(sysErrorClass, "play middle");
i = middle_pick_card(trk);
}
//
// let's track if we are out of trump cards or not
//
if ( trk->getLead() == trk->getTrump() ) {
if ( i->Suit() != trk->getTrump() ) {
out_of_trump = true;
}
}
//
// find the card in our hand
//
CArray<Card *>::iterator tmp;
for( tmp = hand.BeginIterator() ; tmp != hand.EndIterator(); tmp++ ) {
if ( *tmp == i ) {
break;
}
}
//
// delete it
//
Int16 toss = hand.LinearSearch((*tmp));
hand.Delete( toss );
//
// track the cards we have played
//
played_cards.Add(i);
//
// store a link to the card we chose
//
played_card = i;
}
return true;
}
Card *ComputerPlayer::first_pick_card(Trick *trk) {
/*
strategy:
- if it's the first hand of a no Trick first trump, play a high non-trumper
- if we have the lead and a high trump Card, always play it
- else, if we're likely to lose, play a worthless Card
*/
CArray<Card *>::iterator tmp_best_card;
CArray<Card *>::iterator tmp_worst_card;
Int16 best_chance = -1;
Int16 best_value = -1;
Int16 worst_value = 9999;
Int16 worst_chance = 9999;
CArray<Card *>::iterator tmp;
Card *foo = NULL;
tmp_best_card = hand.BeginIterator();
tmp_worst_card = hand.BeginIterator();
Boolean first_card = true;
//
// lets go through and figure out our 'worst' Card, our most valuable Card,
// and our Card most likely to win the hand
//
for( tmp = hand.BeginIterator() ; tmp != hand.EndIterator(); tmp++ ) {
if ( followSuit(trk, *tmp) ) {
Int16 tmp_chance = chance_of_winning_hand(trk, *tmp);
Int16 tmp_value = chance_of_winning_point(trk, *tmp);
if ( first_card ) {
HostTraceOutputTL(sysErrorClass, "first card: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
first_card = false;
best_chance = tmp_chance;
best_value = tmp_value;
worst_value = tmp_value;
worst_chance = tmp_chance;
tmp_best_card = tmp;
tmp_worst_card = tmp;
}
else {
Card *x = *tmp;
//
// tens are walking timebombs, don't lead them
//
if ( (*tmp_best_card)->Face() == Card::ten && tmp_chance < 100 ) {
HostTraceOutputTL(sysErrorClass, "ten timebomb: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
best_chance = tmp_chance;
best_value = tmp_value;
tmp_best_card = tmp;
}
else if (
// if our best card is NOT trump, and so is this one
(*tmp_best_card)->Suit() != trk->getTrump() && x->Suit() != trk->getTrump() &&
(Int16)x->Face() > (Int16)(*tmp_best_card)->Face()
) {
HostTraceOutputTL(sysErrorClass, "first trump: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
best_chance = tmp_chance;
best_value = tmp_value;
tmp_best_card = tmp;
}
else if (
// if our best card is trump, and so is this one
(*tmp_best_card)->Suit() == trk->getTrump() && x->Suit() == trk->getTrump() &&
// what was this line doing???
(Int16)(*tmp_best_card)->Face() <= LOW_TRUMP_HOLD_VAL && (Int16)x->Face() <= LOW_TRUMP_HOLD_VAL &&
// and this card has a higher face value
(Int16)x->Face() > (Int16)(*tmp_best_card)->Face()
) {
HostTraceOutputTL(sysErrorClass, "better trump: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
best_chance = tmp_chance;
best_value = tmp_value;
tmp_best_card = tmp;
}
else if (
(
// this Card has a higher chance of winning
( tmp_chance > best_chance ) ||
// OR this Card is more valuable with the same chance
( tmp_chance == best_chance && tmp_value > best_value )
) &&
// this Card isn't a possible low Card
! ( x->Suit() == trk->getTrump() && (Int16)x->Face() <= LOW_TRUMP_HOLD_VAL && tmp_value > 0 )
) {
HostTraceOutputTL(sysErrorClass, "better winner: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
best_chance = tmp_chance;
best_value = tmp_value;
tmp_best_card = tmp;
}
else if (
// this card has the same chance but is of higher value
( tmp_chance > 0 && tmp_chance == best_chance && tmp_value > best_value) &&
// AND this card is not low
! ( x->Suit() == trk->getTrump() && (Int16)x->Face() <= LOW_TRUMP_HOLD_VAL )
) {
HostTraceOutputTL(sysErrorClass, "better value: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
best_chance = tmp_chance;
best_value = tmp_value;
tmp_best_card = tmp;
}
if (
(*tmp_worst_card)->Suit() == trk->getTrump() && (*tmp)->Suit() != trk->getTrump()
) {
HostTraceOutputTL(sysErrorClass, "worst card: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
worst_value = tmp_value;
worst_chance = tmp_chance;
tmp_worst_card = tmp;
}
else if ( tmp_value < worst_value || ( tmp_value == worst_value && tmp_chance < worst_chance ) ) {
HostTraceOutputTL(sysErrorClass, "worser card: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
worst_value = tmp_value;
worst_chance = tmp_chance;
tmp_worst_card = tmp;
}
} // else (not first Card)
} // if
} // for
// if we are the first Player and we asked for no trump first Trick,
// make sure we play our best Card here
if ( trk->no_trump_first_trick && trk->first_trick ) {
HostTraceOutputTL(sysErrorClass, "we won bid and called ntft, play best: %c%c",
(*tmp_best_card)->FaceChar(),
(*tmp_best_card)->SuitChar() );
return *tmp_best_card;
}
//
// only play our best Card if there's something worth winning
//
if ( best_chance >= TOLERANCE &&
// don't play a jack unless we are guaranteed
! ( (*tmp_best_card)->Face() == Card::jack &&
(*tmp_best_card)->Suit() == trk->getTrump() &&
best_chance < 100
)
) {
HostTraceOutputTL(sysErrorClass, "first play best: %c%c",
(*tmp_best_card)->FaceChar(),
(*tmp_best_card)->SuitChar() );
return *tmp_best_card;
}
HostTraceOutputTL(sysErrorClass, "worst card: %c%c",
(*tmp_worst_card)->FaceChar(),
(*tmp_worst_card)->SuitChar() );
return *tmp_worst_card;
}
/*
if we are the second player, play junk unless we can take the 1st card and it is worth taking
if we are the 3rd player, we want to help our partner (the lead) if we can by throwing a tasty
card, but only if it is safe. otherwise, follow the rules for #2
*/
Card *ComputerPlayer::middle_pick_card(Trick *trk) {
CArray<Card *>::iterator tmp_best_card;
CArray<Card *>::iterator tmp_worst_card;
CArray<Card *>::iterator tmp_valuable_card;
Int16 best_chance = -1;
Int16 best_value = -1;
Int16 best_value_chance = -1;
Int16 best_value_val = -1;
Int16 worst_value = 99999;
Int16 worst_chance = 99999;
CArray<Card *>::iterator tmp;
Card *foo = NULL;
tmp_best_card = hand.BeginIterator();
tmp_worst_card = hand.BeginIterator();
tmp_valuable_card = hand.BeginIterator();
Boolean first_card = true;
Int16 partner_win_chance = 0;
Boolean partner_winning = is_partner_winning(trk);
Boolean play_junk = true;
if ( partner_winning ) {
HostTraceOutputTL(sysErrorClass, "partner is winning");
partner_win_chance = chance_of_winning_hand(trk, trk->current_winner->c, true );
if ( partner_win_chance >= PARTNER_WIN_TOLERANCE || want_trick(trk) ) {
HostTraceOutputTL(sysErrorClass, "don't play junk");
play_junk = false;
}
}
Card *lowest = trk->lowestCardPlayed();
//
// lets go through and figure out our 'worst' Card, our most valueable Card,
// and our Card most likely to win the hand
//
for( tmp = hand.BeginIterator() ; tmp != hand.EndIterator(); tmp++ ) {
if ( followSuit(trk, *tmp) ) {
Int16 tmp_chance = chance_of_winning_hand(trk, *tmp);
Int16 tmp_value = chance_of_winning_point(trk, *tmp);
HostTraceOutputTL(sysErrorClass, "card: %c%c hand: %d point: %d",
(*tmp)->FaceChar(),
(*tmp)->SuitChar(),
tmp_chance,
tmp_value );
if ( first_card ) {
HostTraceOutputTL(sysErrorClass, "first card: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
first_card = false;
best_chance = tmp_chance;
best_value_chance = tmp_chance;
best_value = tmp_value;
best_value_val = tmp_value;
worst_value = tmp_value;
worst_chance = tmp_chance;
tmp_best_card = tmp;
tmp_worst_card = tmp;
tmp_valuable_card = tmp;
}
else {
Card *x = *tmp;
if ( ! play_junk ) {
//
// tens are walking timebombs, don't lead them
//
if ( (*tmp_best_card)->Face() == Card::ten &&
( tmp_chance == 100 || partner_win_chance >= PARTNER_WIN_TOLERANCE ) ) {
HostTraceOutputTL(sysErrorClass, "ten timebomb: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
best_chance = tmp_chance;
best_value = tmp_value;
tmp_best_card = tmp;
}
else if (
( ( tmp_chance > best_chance ) ||
( tmp_chance == best_chance && tmp_value > best_value ) ) &&
! ( x->Suit() == trk->getTrump() && (Int16)x->Face() <= LOW_TRUMP_HOLD_VAL ) ) {
HostTraceOutputTL(sysErrorClass, "better chance: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
best_chance = tmp_chance;
tmp_best_card = tmp;
}
else if (
( tmp_chance > 0 && tmp_chance == best_chance && tmp_value > best_value) &&
! ( x->Suit() == trk->getTrump() && (Int16)x->Face() <= LOW_TRUMP_HOLD_VAL )
) {
HostTraceOutputTL(sysErrorClass, "same chance, better val: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
best_chance = tmp_chance;
tmp_best_card = tmp;
}
//
// figure out what our most valuable Card is, and what
// our chance of winning is with it
//
if ( tmp_value > best_value ||
( tmp_value == best_value &&
(*tmp_valuable_card)->Face() > (*tmp)->Face() )
// partner_win_chance < 100 &&
) {
HostTraceOutputTL(sysErrorClass, "better value: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
best_value_val = tmp_value;
best_value_chance = tmp_chance;
tmp_valuable_card = tmp;
}
} // if ( ! play junk )
if (
(*tmp_worst_card)->Suit() == trk->getTrump() && (*tmp)->Suit() != trk->getTrump()
) {
HostTraceOutputTL(sysErrorClass, "worst value: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
worst_value = tmp_value;
worst_chance = tmp_chance;
tmp_worst_card = tmp;
}
/*
! ( (*tmp)->Suit() == trk->getTrump() &&
( (*tmp)->Face() == Card::jack || (int)(*tmp)->Face() <= (int)Card::five ) ) &&
(
(int)((*tmp)->Face()) < (*tmp_worst_card)->Face() ||
*/
else if ( tmp_value < worst_value ||
( tmp_value == worst_value && tmp_chance < worst_chance )
)
{
HostTraceOutputTL(sysErrorClass, "worser value: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
worst_value = tmp_value;
worst_chance = tmp_chance;
tmp_worst_card = tmp;
}
}
} // if
} // for
delete lowest;
//
// if there's nothing worth winning, don't play a good card
//
if ( play_junk ) {
HostTraceOutputTL(sysErrorClass, "play junky card: %c%c",
(*tmp_worst_card)->FaceChar(),
(*tmp_worst_card)->SuitChar() );
return *tmp_worst_card;
}
//
// if our partner is winning, chuck her a good card
//
if ( is_partner_winning(trk) &&
chance_of_winning_hand(trk, trk->current_winner->c, true ) >= PARTNER_WIN_TOLERANCE ) {
HostTraceOutputTL(sysErrorClass, "play valuable card: %c%c",
(*tmp_valuable_card)->FaceChar(),
(*tmp_valuable_card)->SuitChar() );
return *tmp_valuable_card;
}
//
// if there's something worth winning, then lets win it
//
if ( want_trick(trk) &&
best_chance >= TOLERANCE &&
( best_chance >= 100 ||
(*tmp_best_card)->Suit() != trk->getTrump() ) ) {
HostTraceOutputTL(sysErrorClass, "want, best card: %c%c",
(*tmp_best_card)->FaceChar(),
(*tmp_best_card)->SuitChar() );
return *tmp_best_card;
}
HostTraceOutputTL(sysErrorClass, "play worst card: %c%c",
(*tmp_worst_card)->FaceChar(),
(*tmp_worst_card)->SuitChar() );
return *tmp_worst_card;
}
/*
if we are the last player, we want to sneak in a winning low card or ten if we can, otherwise throw junk
or win outright if it's worth doing
*/
Card *ComputerPlayer::last_pick_card(Trick *trk) {
CArray<Card *>::iterator tmp_best_card;
CArray<Card *>::iterator tmp_worst_card;
CArray<Card *>::iterator tmp_worst_winning_card;
CArray<Card *>::iterator tmp_valuable_card;
Int16 best_value_chance = -1;
Int16 best_value_val = -1;
Int16 worst_value = 99999;
Int16 worst_chance = 99999;
Int16 best_value = -1;
Int16 best_chance = -1;
Int16 worst_win_value = 99999;
Int16 worst_win_chance = -1;
CArray<Card *>::iterator tmp;
tmp_best_card = hand.BeginIterator();
tmp_worst_card = hand.BeginIterator();
tmp_worst_winning_card = hand.BeginIterator();
tmp_valuable_card = hand.BeginIterator();
Boolean first_card = true;
Card *lowest = trk->lowestCardPlayed();
//
// lets go through and figure out our 'worst' Card, our most valueable Card,
// and our Card most likely to win the hand
//
for( tmp = hand.BeginIterator() ; tmp != hand.EndIterator(); tmp++ ) {
if ( followSuit(trk, *tmp) ) {
Int16 tmp_chance = chance_of_winning_hand(trk, *tmp);
Int16 tmp_value = chance_of_winning_point(trk, *tmp);
if ( first_card ) {
first_card = false;
HostTraceOutputTL(sysErrorClass, "first card: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
best_value_chance = tmp_chance;
best_value_val = tmp_value;
tmp_valuable_card = tmp;
worst_value = tmp_value;
worst_chance = tmp_chance;
tmp_worst_card = tmp;
tmp_worst_winning_card = tmp;
worst_win_value = tmp_value;
worst_win_chance = tmp_chance;
best_chance = tmp_chance;
best_value = tmp_value;
}
else {
Card *x = *tmp;
if ( worst_value > tmp_value ) {
HostTraceOutputTL(sysErrorClass, "worst val card: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
worst_value = tmp_value;
worst_chance = tmp_chance;
tmp_worst_card = tmp;
}
if ( worst_win_value > tmp_value && tmp_chance > 0 ) {
HostTraceOutputTL(sysErrorClass, "worst win card: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
worst_win_value = tmp_value;
worst_win_chance = tmp_chance;
tmp_worst_winning_card = tmp;
}
//
// figure out what our most valuable Card is, and what
// our chance of winning is with it
//
if ( tmp_value > best_value_val ||
( tmp_value == best_value_val &&
( (*tmp_valuable_card)->Face() <= Card::four && (*tmp_valuable_card)->Face() < (*tmp)->Face() ) )
) {
HostTraceOutputTL(sysErrorClass, "best val card: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
best_value_val = tmp_value;
best_value_chance = tmp_chance;
tmp_valuable_card = tmp;
}
if ( tmp_chance > best_chance ) {
HostTraceOutputTL(sysErrorClass, "best chance card: %c%c",
(*tmp)->FaceChar(),
(*tmp)->SuitChar() );
best_chance = tmp_chance;
tmp_best_card = tmp;
}
}
} // if
} // for
delete lowest;
//
// if we're last and our partner is winning, chuck her a good Card
//
if ( is_partner_winning(trk) &&
(*tmp_valuable_card)->Face() <= Card::jack &&
best_value_val >= VALUE_TOLERANCE ) {
HostTraceOutputTL(sysErrorClass, "partner winning, best card: %c%c",
(*tmp_valuable_card)->FaceChar(),
(*tmp_valuable_card)->SuitChar() );
return *tmp_valuable_card;
}
//
// only play our best Card if there's something worth winning
//
if ( best_value_chance > 0 && ( best_value_val >= VALUE_TOLERANCE || want_trick(trk) )
&& ! ( (*tmp_valuable_card)->Suit() == trk->getTrump() && (*tmp_valuable_card)->Face() >= Card::queen ) ) {
HostTraceOutputTL(sysErrorClass, "win with best val card: %c%c",
(*tmp_valuable_card)->FaceChar(),
(*tmp_valuable_card)->SuitChar() );
return *tmp_valuable_card;
}
//
// if our worst winner will win, and we want the hand, then use that
//
if (
( worst_win_value >= VALUE_TOLERANCE || want_trick(trk) ) &&
worst_win_chance > 0 ) {
HostTraceOutputTL(sysErrorClass, "want trick, win w/ worst card: %c%c",
(*tmp_worst_winning_card)->FaceChar(),
(*tmp_worst_winning_card)->SuitChar() );
return *tmp_worst_winning_card;
}
if ( want_trick(trk) && best_chance > 0 ) {
HostTraceOutputTL(sysErrorClass, "want trick, win w/ card: %c%c",
(*tmp_best_card)->FaceChar(),
(*tmp_best_card)->SuitChar() );
return *tmp_best_card;
}
HostTraceOutputTL(sysErrorClass, "lose w/ worst card: %c%c",
(*tmp_worst_card)->FaceChar(),
(*tmp_worst_card)->SuitChar() );
return *tmp_worst_card;
}
/* sorts Card into vectors for each suit */
void ComputerPlayer::sortHand() {
sort_hand();
for( CArray<Card *>::iterator i = hand.BeginIterator(); i != hand.EndIterator(); i++)
{
if ( (*i)->Suit() == Card::club)
{
my_clubs.Add(*i);
}
else if ((*i)->Suit() == Card::diamond)
{
my_diamonds.Add(*i);
}
else if ((*i)->Suit() == Card::heart)
{
my_hearts.Add(*i);
}
else if ((*i)->Suit() == Card::spade)
{
my_spades.Add(*i);
}
}
} // sortHand
Int16 ComputerPlayer::handValue(Int16 suit, Boolean partner_winning, Int16 partner_bid, Int16 ourScore, Int16 theirScore) {
Int16 points = 0;
Int16 count = 0;
Int16 total = suits[suit].GetCount();
for( CArray<Card *>::iterator i = suits[suit].BeginIterator(); i != suits[suit].EndIterator(); i++) {
Int16 win_chance = 0;
// chance of a higher Card =
// # of higher cards / # of cards left (total - my cards)
Int16 higher_cards = (Int16)Card::ace - (Int16)(*i)->Face() - count;
win_chance = 100 - (higher_cards * 100)/(52 - total);
if ( (*i)->Face() == Card::jack ) {
have_jack = true;
}
else if ( (*i)->Face() == Card::king || (*i)->Face() == Card::ace ) {
have_high = true;
}
// count++;
// points += (win_chance - 74);
/*
12 has a 100 chance of winning
11 has a 98 chance of winning
10 has a 96 chance of winning
9 has a 94 chance of winning
8 has a 92 chance of winning
7 has a 90 chance of winning
6 has a 88 chance of winning
5 has a 86 chance of winning
4 has a 84 chance of winning
3 has a 82 chance of winning
2 has a 80 chance of winning
1 has a 78 chance of winning
0 has a 76 chance of winning */
if ( win_chance >= 98 ) {
points += 5;
}
else if ( win_chance >= 94 ) {
points += 4;
}
else if ( win_chance >= 90 ) {
points += 3;
}
else if ( win_chance >= 85 ) {
points += 2;
}
else {
points += 1;
}
} // for
if ( have_high ) {
points += 3;
}
if ( theirScore + 3 >= gManager->winning_score ) {
points += 2;
}
return points;
} // handValue
void ComputerPlayer::analyzeHand(Player *bidder) {
UInt16 bestIndex = 0;
Int16 suitScore = 0;
Boolean partner_winning = false;
Int16 partner_bid = 0;
bid = 0;
Int16 tmpOurScore = 0;
Int16 tmpTheirScore = 0;
if ( gManager->CutThroat() ) {
partner_winning = false;
partner_bid = 0;
tmpOurScore = gManager->scores[playerIndex];
if ( playerIndex == 0 ) {
tmpTheirScore = gManager->scores[1] > gManager->scores[2] ?
gManager->scores[1] :
gManager->scores[2];
}
else if ( playerIndex == 1 ) {
tmpTheirScore = gManager->scores[0] > gManager->scores[2] ?
gManager->scores[0] :
gManager->scores[2];
}
else if ( playerIndex == 2 ) {
tmpTheirScore = gManager->scores[0] > gManager->scores[1] ?
gManager->scores[0] :
gManager->scores[1];
}
}
else {
if ( bidder == partner ) {
partner_winning = true;
partner_bid = partner->bid;
}
if ( playerIndex == 0 || playerIndex == 2 ) {
tmpOurScore = gManager->scores[0];
tmpTheirScore = gManager->scores[1];
}
else {
tmpOurScore = gManager->scores[1];
tmpTheirScore = gManager->scores[0];
}
}
Int8 best_points = -1;
for (Int16 i = 0; i < 4; i++) {
have_jack = false;
have_high = false;
Int16 points = handValue(i, partner_winning, partner_bid,
tmpOurScore, tmpTheirScore );
if ( points > best_points ) {
best_points = points;
// max possible score is 30 points, which would be a lock for smudge
if ( partner_winning ) {
if ( points >= 28 && have_jack && have_high ) {
bid = 5;
}
else if ( points >= 24 && have_jack && have_high ) {
bid = 4;
}
else if ( ( points >= 21 && have_high ) || ( points >= 19 && have_jack && have_high ) ) {
bid = 3;
}
else if ( points >= 15 ) {
bid = 2;
}
else {
bid = 0;
}
}
else {
if ( points >= 26 && have_jack && have_high ) {
bid = 5;
}
else if ( points >= 20 && have_jack && have_high ) {
bid = 4;
}
else if ( ( points >= 17 && have_high ) || ( points >= 15 && have_jack && have_high ) ) {
bid = 3;
}
else if ( points >= 13 ) {
bid = 2;
}
else {
bid = 0;
}
}
bestIndex = i;
} // if ( points > best_points )
} // for
switch (bestIndex)
{
case 0:
bestSuit = Card::club;
break;
case 1:
bestSuit = Card::diamond;
break;
case 2:
bestSuit = Card::heart;
break;
case 3:
bestSuit = Card::spade;
break;
}
no_trump_first_trick = false;
/*
if we're running the smart AI, let's check and see if we should do a first Trick no trump
*/
if ( gManager->no_trump_first_trick ) {
for (Int16 array_counter = 0; array_counter < 4; array_counter++)
{
if ( array_counter != bestIndex && suits[array_counter].GetCount() > 0 ) {
CArray<Card *>::iterator i = suits[array_counter].EndIterator() - 1;
Card *highest = *i;
if ( (Int16)highest->Face() >= Card::queen ) {
no_trump_first_trick = true;
}
}
}
} // if Smart
} // analyzeHand
Boolean ComputerPlayer::want_trick(Trick *t) {
Boolean has_jack = t->hasJack();
Boolean has_ten = t->hasTen();
Card *low = t->currentLow();
Card *lowest = t->lowestCardPlayed();
if ( has_jack ) {
HostTraceOutputTL(sysErrorClass, "trick has a jack, we want it");
}
if ( has_ten ) {
HostTraceOutputTL(sysErrorClass, "trick has a ten, we want it");
}
if ( has_jack || has_ten || ( low && low->Face() < lowest->Face() && low->Face() <= Card::four ) ) {
delete lowest;
return true;
}
delete lowest;
return false;
}
/*
what is the probability of getting a point out of this hand? we're
not actually looking at the chance of winning the hand itself, just
it's overall value
*/
Int16 ComputerPlayer::chance_of_winning_point(Trick *t, Card *c) {
Int16 chance = 0;
Int16 tmp_chance = 0;
Card *current_high = t->highestCardPlayed(c->Suit());
Card *current_low = t->lowestCardPlayed();
if ( c->Suit() == t->getTrump() ) {
// check for jack
if ( c->Face() == Card::jack ) {
chance = 100;
}
else {
// check for high
if ( c->Face() >= current_high->Face() ) {
// chance of a higher Card == # of cards higher than this one / # of playable cards left
Int16 diff = (Int16)Card::ace - (Int16)c->Face();
//
// if this isn't a face Card, we want to play it more conservatively
//
if ( (Int16)c->Face() <= Card::ten ) {
diff += 2;
}
Int16 foo = diff * 100 / t->cards_left;
tmp_chance = 100 - foo;
if ( tmp_chance > chance ) {
chance = tmp_chance;
}
}
// check for low
if ( (Int16)current_low->Face() >= (Int16)c->Face() ) {
// chance of a lower Card == # of cards lower than this one / # of playable cards left
Int16 diff = (Int16)c->Face() - (Int16)Card::two;
//
// if this isn't a really low Card, we want to play it more conservatively
//
if ( (Int16)c->Face() >= Card::five ) {
diff += 2;
}
Int16 foo = diff * 100 / t->cards_left;
tmp_chance = 100 - foo;
if ( tmp_chance > chance ) {
chance = tmp_chance;
}
}
}
}
if ( (Int16)c->Face() == (Int16)Card::ten ) {
chance += 35;
}
else if ( (Int16)c->Face() > (Int16)Card::ten ) {
// chance += 5;
}
delete current_high;
delete current_low;
return chance;
}
Boolean ComputerPlayer::is_partner_winning(Trick *trk) {
if ( gManager->CutThroat() ) {
return false;
}
return trk->current_winner != NULL &&
trk->current_winner->p->playerIndex == partner->playerIndex;
}
Int16 ComputerPlayer::chance_of_winning_hand(Trick *trk, Card *c) {
return chance_of_winning_hand(trk, c, false);
}
/*
what is the chance of winning with the given Card, regardless of
it's value?
*/
Int16 ComputerPlayer::chance_of_winning_hand(Trick *trk, Card *c,
Boolean checking_partner_card) {
Boolean last_player = haveLastPlay();
Boolean partner_winning = ( ! checking_partner_card ) && is_partner_winning(trk);
Boolean no_trump_left = trk->noTrumpLeft(this);
Boolean trump_played = trk->current_winner != NULL && trk->current_winner->c->Suit() == trk->getTrump();
Int16 cardval = (Int16)c->Face();
Int16 trump_left = 0;
Int16 diff = 0;
Int16 chance = 0;
Int16 partner_win_chance = 0;
HostTraceOutputTL(sysErrorClass, "guess chance of winning with %c%c", c->FaceChar(), c->SuitChar() );
Card *highest_card_left = trk->highestCardNotPlayed(c->Suit());
HostTraceOutputTL(sysErrorClass, "highest card left %c%c",
highest_card_left->FaceChar(), highest_card_left->SuitChar() );
if ( last_player && partner_winning ) {
HostTraceOutputTL(sysErrorClass, "last player and partner winning, i'll win" );
delete highest_card_left;
return 100;
}
if ( partner_winning ) {
partner_win_chance = chance_of_winning_hand(trk, trk->current_winner->c, true );
HostTraceOutputTL(sysErrorClass, "partner win chance: %d", partner_win_chance );
}
// am i the last Player? if so, special rules
// && c >= highest_card_left
if ( last_player &&
( ! trump_played && c->Suit() == trk->getTrump() ) ) {
HostTraceOutputTL(sysErrorClass, "last player, i'll win" );
delete highest_card_left;
return 100;
}
if ( last_player &&
trk->current_winner &&
trk->current_winner->c->Suit() == c->Suit() &&
trk->current_winner->c->Face() < c->Face() ) {
HostTraceOutputTL(sysErrorClass, "last player 2, i'll win");
delete highest_card_left;
return 100;
}
// has the other team played the highest Card? if so...
if ( trk->current_winner != NULL &&
c->Suit() == trk->current_winner->c->Suit() &&
(Int16)c->Face() < (Int16)trk->current_winner->c->Face() ) {
HostTraceOutputTL(sysErrorClass, "Card %c < %c, I'll lose", c->FaceChar(),
trk->current_winner->c->FaceChar() );
delete highest_card_left;
return 0;
}
//
// chance of a higher Card == # of higher cards / # number of cards left
//
if ( trump_played && trk->getTrump() != c->Suit() ) {
HostTraceOutputTL(sysErrorClass, "not trump, i'll lose");
delete highest_card_left;
return 0;
}
//
// trump has not been played at this point
//
if ( c->Suit() != trk->getTrump() ) {
Card *highest_trump = trk->highestCardNotPlayed(trk->getTrump());
trump_left = (Int16)highest_trump->Face() + 1;
Int16 higher_cards = trump_left + ( (Int16)Card::ace - cardval );
chance = 100 - (higher_cards * (100 / trk->cards_left));
// HostTraceOutputTL(sysErrorClass, "chance1: 100 - (%d * 100 / %d) = %d", higher_cards, trk->cards_left, chance );
HostTraceOutputTL(sysErrorClass, "chance1: %d", chance);
delete highest_trump;
}
else {
diff = (Int16)highest_card_left->Face() - (Int16)c->Face();
chance = 100 - (diff * (100 / trk->cards_left));
HostTraceOutputTL(sysErrorClass, "chance2: %d", chance);
}
//
// is my partner guaranteed to win? if so...
//
if ( partner_win_chance >= PARTNER_WIN_TOLERANCE && partner_win_chance > chance ) {
chance = partner_win_chance;
HostTraceOutputTL(sysErrorClass, "go with partner win chance" );
}
delete highest_card_left;
return chance;
}
/* if bid is won then this is used to set trump, just returns best suit */
Card::suit_t ComputerPlayer::Trump() {
if ( (int)bestSuit == -1 ) {
analyzeHand(this);
}
return bestSuit;
}
Boolean ComputerPlayer::haveLastPlay() {
// CArray<Player *>::iterator tmp = gManager->players.EndIterator() - 1;
Player *l = gManager->getPrevPlayer(gManager->tbl->lead);
// Player *c = (*gManager->current);
// if ( l->playerIndex == c->playerIndex ) {
if ( l->playerIndex == playerIndex ) {
return true;
}
return false;
}
Boolean ComputerPlayer::haveLeadPlay() {
if ( gManager->tbl->lead == this ) {
return true;
}
return false;
}
| true |
03f300a3acf80e0b2af98bedf7106f2d323dcd03 | C++ | nurakib/Problems-and-Solutions | /Book-1/uva_11059_Maximum Product.cpp | UTF-8 | 732 | 3 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
long long maxProd(long long arr[], int n){
long long sum = 1, max_val = 0;
//checking all possible cases
for(int i = 0; i < n; i++){
for(int j = i; j < n; j++){
sum = sum * arr[j];
if(sum > max_val) max_val = sum;
}
sum = 1;
}
return max_val;
}
int main(){
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
int n, caseno = 0;
long long ans, num[105];
while(cin >> n){
for(int i = 0; i < n; i++){
cin >> num[i];
}
ans = maxProd(num, n);
cout << "Case #" << ++caseno << ": The maximum product is " << ans << ".\n\n";
}
return 0;
}
| true |
b8c841fecd375a07389989052ed3615bafe345c2 | C++ | zbream/school-work | /EECS4530/Project2/Project2/Program.cpp | UTF-8 | 8,581 | 2.59375 | 3 | [] | no_license | // Zack Ream
// EECS 4530 - Fall 2016
#include <iostream>
#include <string>
#include <GL/glew.h>
#include <GL/freeglut.h>
#include "vgl.h"
#include "vmath.h"
#include "LoadShaders.h"
float *readOBJFile(std::string filename, int &nbrTriangles, float * &normalArray);
#define BUFFER_OFFSET(x) ((const void*) (x))
// === GLOBALS
GLuint vertexBuffers[10], arrayBuffers[10], elementBuffers[10];
float rotationAngle;
int nbrTriangles;
GLint transformLocation, colorLocation, lightPositionLocation,
ambientLightColorLocation, diffuseLightColorLocation, specularLightColorLocation, specularPowerLocation, eyePositionLocation, normalTransformLocation,
materialAmbientLocation, materialDiffuseLocation, materialEmissiveLocation, materialSpecularLocation, materialShininessLocation;
// === GL FUNCTIONS
void timer(int value) {
rotationAngle += 2.0f;
if (rotationAngle >= 360) {
rotationAngle = 0;
}
glutPostRedisplay();
glutTimerFunc(1000 / 30, timer, 1);
}
void init() {
float *trianglesArray;
float *normalArray;
trianglesArray = readOBJFile("triangulatedCowDos.obj", nbrTriangles, normalArray);
glLineWidth(4.0);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glGenVertexArrays(1, vertexBuffers);
glBindVertexArray(vertexBuffers[0]);
glGenBuffers(1, arrayBuffers);
glBindBuffer(GL_ARRAY_BUFFER, arrayBuffers[0]);
glBufferData(GL_ARRAY_BUFFER, nbrTriangles * 3 * 4 * sizeof(float) + nbrTriangles * 3 * 3 * sizeof(float), NULL, GL_STATIC_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, 0, nbrTriangles * 3 * 4 * sizeof(float), trianglesArray);
glBufferSubData(GL_ARRAY_BUFFER, nbrTriangles * 3 * 4 * sizeof(float), nbrTriangles * 3 * 3 * sizeof(float), normalArray);
ShaderInfo shaders[] = {
{GL_VERTEX_SHADER, "pass.vert"},
{GL_FRAGMENT_SHADER, "pass.frag"},
{GL_NONE, NULL}
};
GLuint program = LoadShaders(shaders);
glUseProgram(program);
GLuint vPosition = glGetAttribLocation(program, "vPosition");
glEnableVertexAttribArray(vPosition);
glVertexAttribPointer(vPosition, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
GLuint vNormal = glGetAttribLocation(program, "vNormal");
glEnableVertexAttribArray(vNormal);
glVertexAttribPointer(vNormal, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(nbrTriangles * 3 * 4 * sizeof(float)));
transformLocation = glGetUniformLocation(program, "transform");
colorLocation = glGetUniformLocation(program, "cowcolor");
lightPositionLocation = glGetUniformLocation(program, "lightPosition");
ambientLightColorLocation = glGetUniformLocation(program, "ambientLightColor");
diffuseLightColorLocation = glGetUniformLocation(program, "diffuseLightColor");
specularLightColorLocation = glGetUniformLocation(program, "specularLightColor");
specularPowerLocation = glGetUniformLocation(program, "specularPower");
eyePositionLocation = glGetUniformLocation(program, "eyeLocation");
normalTransformLocation = glGetUniformLocation(program, "normalTransform");
materialAmbientLocation = glGetUniformLocation(program, "material.ambient");
materialSpecularLocation = glGetUniformLocation(program, "material.specular");
materialDiffuseLocation = glGetUniformLocation(program, "material.diffuse");
materialShininessLocation = glGetUniformLocation(program, "material.shininess");
materialEmissiveLocation = glGetUniformLocation(program, "material.emissive");
glEnable(GL_DEPTH_TEST);
}
void display() {
static GLfloat
red[4] = { 1.0f, 0.0f, 0.0f, 1.0f },
white[4] = { 1.0f, 1.0f, 1.0f, 1.0f },
blue[4] = { 0.0f, 0.0f, 1.0f, 1.0f };
GLfloat lightPosition[] = { 0.0f, 0.0f, 10.0f };
GLfloat diffuseLightColor[] = { 0.5f, 0.5f, 0.5f };
GLfloat ambientLightColor[] = { 0.3f, 0.3f, 0.3f };
GLfloat eyePosition[] = { 0.0f, 0.0f, 10.0f };
GLfloat specularLightColor[] = { 0.5f, 0.5f, 0.5f };
GLfloat specularPower[] = { 64.0f };
GLfloat normalTransformation[3][3];
vmath::mat4 normalTrans;
vmath::perspective(60.0f, 1.0f, 0.01f, 100.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
vmath::mat4 currentMatrix = vmath::scale(0.08f) *
vmath::rotate(rotationAngle, 0.0f, 1.0f, 0.0f);
/*
* m seems to be wrong. Need to go back and make sure I've got these in the
* right positions.
*/
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
normalTransformation[i][j] = currentMatrix[i][j];
}
}
glUniformMatrix4fv(transformLocation, 1, GL_TRUE, currentMatrix);
glUniformMatrix3fv(normalTransformLocation, 1, GL_TRUE, (const GLfloat *)normalTransformation);
glUniform4fv(colorLocation, 1, white);
glUniform3fv(lightPositionLocation, 1, lightPosition);
glUniform3fv(diffuseLightColorLocation, 1, diffuseLightColor);
glUniform3fv(ambientLightColorLocation, 1, (const GLfloat *)&ambientLightColor);
glUniform3fv(eyePositionLocation, 1, eyePosition);
glUniform3fv(specularLightColorLocation, 1, specularLightColor);
glUniform1fv(specularPowerLocation, 1, specularPower);
// Pearl material
GLfloat ambient[] = { 0.25f, 0.20725f, 0.20725f };
GLfloat diffuse[] = { 1.0f, 0.829f, 0.829f };
GLfloat specular[] = { 0.296648f, 0.296648f, 0.296648f };
GLfloat shininess = (128.0f*0.088f);
glUniform3fv(materialDiffuseLocation, 1, diffuse);
glUniform3fv(materialAmbientLocation, 1, ambient);
glUniform3fv(materialSpecularLocation, 1, specular);
glUniform1fv(materialShininessLocation, 1, &shininess);
// cow 1
vmath::mat4 c1Transform(vmath::vec4(1.0f, 0.0f, 0.0f, 2.00f), // x
vmath::vec4(0.0f, 1.0f, 0.0f, 0.00f), // y
vmath::vec4(0.0f, 0.0f, 1.0f, 0.00f), // z
vmath::vec4(0.0f, 0.0f, 0.0f, 1.0f));
currentMatrix = c1Transform * vmath::scale(0.08f) *
vmath::rotate(rotationAngle, 0.0f, 1.0f, 0.0f); // overall rotation
glUniformMatrix4fv(transformLocation, 1, GL_TRUE, currentMatrix);
glBindVertexArray(vertexBuffers[0]);
glBindBuffer(GL_ARRAY_BUFFER, arrayBuffers[0]);
glDrawArrays(GL_TRIANGLES, 0, nbrTriangles * 3);
// cow 2 (top gun)
vmath::mat4 c2Transform(vmath::vec4(1.0f, 0.0f, 0.0f, 3.00f), // x
vmath::vec4(0.0f, 1.0f, 0.0f, -6.00f), // y
vmath::vec4(0.0f, 0.0f, 1.0f, 0.00f), // z
vmath::vec4(0.0f, 0.0f, 0.0f, 1.0f));
currentMatrix = c2Transform * vmath::scale(0.07f) *
vmath::rotate(180.0f, 1.0f, 0.0f, 0.0f) * // flip upside down
vmath::rotate(rotationAngle, 0.0f, 1.0f, 0.0f); // overall rotation
glUniformMatrix4fv(transformLocation, 1, GL_TRUE, currentMatrix);
glBindVertexArray(vertexBuffers[0]);
glBindBuffer(GL_ARRAY_BUFFER, arrayBuffers[0]);
glDrawArrays(GL_TRIANGLES, 0, nbrTriangles * 3);
// cow 3 (calf)
vmath::mat4 c3Transform(vmath::vec4(1.0f, 0.0f, 0.0f, -6.00f), // x
vmath::vec4(0.0f, 1.0f, 0.0f, -4.00f), // y
vmath::vec4(0.0f, 0.0f, 1.0f, -14.00f), // z
vmath::vec4(0.0f, 0.0f, 0.0f, 1.0f));
currentMatrix = c3Transform * vmath::scale(0.04f) *
vmath::rotate(90.0f, 0.0f, 1.0f, 0.0f) * // face the mother
vmath::rotate(rotationAngle, 0.0f, 1.0f, 0.0f); // overall rotation
glUniformMatrix4fv(transformLocation, 1, GL_TRUE, currentMatrix);
glBindVertexArray(vertexBuffers[0]);
glBindBuffer(GL_ARRAY_BUFFER, arrayBuffers[0]);
glDrawArrays(GL_TRIANGLES, 0, nbrTriangles * 3);
// cow 4 (next to, looking behind)
vmath::mat4 c4Transform(vmath::vec4(1.0f, 0.0f, 0.0f, 0.00f), // x
vmath::vec4(0.0f, 1.0f, 0.0f, -1.00f), // y
vmath::vec4(0.0f, 0.0f, 1.0f, -8.00f), // z
vmath::vec4(0.0f, 0.0f, 0.0f, 1.0f));
currentMatrix = c4Transform * vmath::scale(0.06f) *
vmath::rotate(180.0f, 0.0f, 1.0f, 0.0f) * // face behind the mother
vmath::rotate(rotationAngle, 0.0f, 1.0f, 0.0f); // overall rotation
glUniformMatrix4fv(transformLocation, 1, GL_TRUE, currentMatrix);
glBindVertexArray(vertexBuffers[0]);
glBindBuffer(GL_ARRAY_BUFFER, arrayBuffers[0]);
glDrawArrays(GL_TRIANGLES, 0, nbrTriangles * 3);
glFlush();
}
void keypress(unsigned char keycode, int x, int y) {
if (keycode == 'q' || keycode == 'Q') {
exit(0);
}
}
// === ENTRY POINT
int main(int argCount, char *argValues[]) {
glutInit(&argCount, argValues);
glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(500, 500);
glutCreateWindow("Cows Everywhere - Zack Ream");
glutInitContextVersion(3, 1);
glutInitContextProfile(GLUT_CORE_PROFILE);
glewInit();
init();
glutKeyboardFunc(keypress);
glutDisplayFunc(display);
glutTimerFunc(1000 / 30, timer, 1);
glutMainLoop();
return 0;
} | true |
82118b06bb9d831a0e4b2eb29e0bc7f6a082b595 | C++ | jzx0614/Course | /2ndhw/c09102014/exam2.cpp | BIG5 | 785 | 3.484375 | 3 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
int f(int sum,char t[]) //1. B
{ int s=0;
for(int i=0;i<strlen(t);i++)
{
if(t[i]=='+'||t[i]=='-')
{
if(t[i+1]=='(') //3.A
{
s=atoi(t+i+2)+f(s,t+i+2);
if(t[i]=='+')
sum=sum+s;
else
sum=sum-s;
while(t[i]!=')')i++;
}
else
sum=sum+atoi(t+i);
}
else if (t[i]==')') break;
}
return sum;
}
void main()
{
char temp[100];
cout << "input:";
cin >> temp;
int sum=atoi(temp);
for(int i=0;i<strlen(temp);i++)
{
if((temp[i]=='+'||temp[i]=='-')&&(temp[i+1]=='+'||temp[i+1]=='-'))//2.P_kO_
{ //sWL+-N
cout << "Output: ERROR\n";
exit(1);
}
}
cout << "Output: "<< f(sum,temp) <<endl;
} | true |
5c9706b45f2d4650b41375988b305e21d292f7b8 | C++ | murtada58/RobotCarApp | /RobotCarApp/RobotCarApp.ino | UTF-8 | 19,870 | 2.921875 | 3 | [
"MIT"
] | permissive | #include <SoftwareSerial.h>
#include <Servo.h> // include the servo libary this gives us access to functions and classes from the library
// TX and RX pin numbers
const uint8_t BLU_RX_ARD_TX = 1;
const uint8_t BLU_TX_ARD_RX = 0;
SoftwareSerial bluetooth(BLU_TX_ARD_RX, BLU_RX_ARD_TX);
Servo servosweep; // create a Servo class object with the name servosweep
const int SERVO_PIN = 3; // Servo motor control pin
// motor control pins
const int ENL = 5; // Enable left
const int ENR = 6; // Enable right
const int WLF = 7; // wheel left front (when high and back low causes wheels to spin forward)
const int WLB = 8; // wheel left back
const int WRF = 11; // wheel right front (when high and back low causes wheels to spin forward)
const int WRB = 9; // wheel right back
// line tracking IR sensor pins
const int LTL = 2; // line tracking left
const int LTM = 4; // line tracking middle
const int LTR = 10; // line tracking right
// intialising move speed and turn speed for line following mode
const int DEFAULT_SPEED = 150;
const int DEFAULT_TURN_SPEED = 130;
// Echo and Trig pins of ultrasonic sensor
const int ECHO = A4;
const int TRIG = A5;
const int DECISION_DISTANCE_CM = 30; // the distance at which to consider another direction to avoid collision
const unsigned long TIME_FOR_90_TURN = 600; // the time that it takes for a 90 degree turn at 130 turn speed (this value might be different depending on the surface and operating conditions)
// intalising the car move speed and car turn speed
int carSpeed = 255;
int carTurnSpeed = 255;
bool lost = false; // This variable keeps track of if we have lost the track or not it is used to determine when the car should stop moving
bool lastDirectionRight = true; // keeps track of the last direction turned in right is true and left is false
String currentState = "manual";
String recieved = ""; // the last recieved message
const int messageIntervalTime = 100; // the time between messages used to ensure that messages have enough time to send
unsigned long messageTimer = 0; // keeps track of the time since the last message was sent same data type as returned variable from the millis function
void setup()
{
bluetooth.begin(9600);
Serial.begin(9600);
// setting all the pinmodes for the motor pins and the IR pins
pinMode(WLF, OUTPUT);
pinMode(WLB, OUTPUT);
pinMode(WRB, OUTPUT);
pinMode(WRF, OUTPUT);
pinMode(ENL, OUTPUT);
pinMode(ENR, OUTPUT);
pinMode(LTL, INPUT);
pinMode(LTM, INPUT);
pinMode(LTR, INPUT);
pinMode(TRIG, OUTPUT);
pinMode(ECHO,INPUT);
servosweep.attach(SERVO_PIN); // set the pin SERVO_PIN as the pin we use to communicate with the servo motor, when we use the servosweep object functions they will act on this pin
// setting trig to low intially as we need it to start low when communicating with the ultrasonic sensor
digitalWrite(TRIG, LOW);
// setting the starting angle for the servo at 90 degrees so that it faces forward
servosweep.write(90);
delay(500);
}
void loop()
{
newBluetoothMessage();
if (currentState == "manual")
{
manualControl(recieved);
}
else if (currentState == "lineFollower")
{
lineFollower();
}
else if (currentState == "obstacleAvoidance")
{
obstacleAvoidance();
}
}
bool newBluetoothMessage()
{
char charBuffer[20];//most we would ever see
if (bluetooth.available() > 0)
{
int numberOfBytesReceived = bluetooth.readBytesUntil('\n', charBuffer, 19);
charBuffer[numberOfBytesReceived] = NULL;
recieved = charBuffer;
if (recieved[0] == 'M')
{
servosweep.write(90);
currentState = "manual";
stop();
}
else if (recieved[0] == 'L')
{
lost = false;
servosweep.write(90);
currentState = "lineFollower";
stop();
}
else if (recieved[0] == 'O')
{
// setting the starting angle for the servo at 90 degrees so that it faces forward
servosweep.write(90);
delay(500);
currentState = "obstacleAvoidance";
stop();
}
return true;
}
else
{
return false;
}
}
void manualControl(String code)
{
if (code[0] == 'W')
{
forwards(carSpeed);
}
else if (code[0] == 'A')
{
antiClockwise(carTurnSpeed);
}
else if (code[0] == 'S')
{
backwards(carSpeed);
}
else if (code[0] == 'D')
{
clockwise(carTurnSpeed);
}
else if (code[0] == 'P')
{
stop();
}
else if (code[0] == 'C')
{
stop();
carSpeed = 255;
carTurnSpeed = 255;
}
else if (code[0] == 'V')
{
code.remove(0, 1);
carSpeed = code.toInt();
}
else if (code[0] == 'T')
{
code.remove(0, 1);
carTurnSpeed = code.toInt();
}
else if (code[0] == 'Z')
{
code.remove(0, 1);
if (code[0] == '-')
{
code.remove(0, 1);
carTurnSpeed = (255 * code.toInt()) / 10;
antiClockwise(carTurnSpeed);
}
else
{
carTurnSpeed = (255 * code.toInt()) / 10;
clockwise(carTurnSpeed);
}
}
else if (code[0] == 'X')
{
code.remove(0, 1);
if (code[0] == '-')
{
code.remove(0, 1);
carSpeed = (255 * code.toInt()) / 10;
forwards(carSpeed);
}
else
{
carSpeed = (255 * code.toInt()) / 10;
backwards(carSpeed);
}
}
}
void lineFollower()
{
// storing the sensor readings for this loop for use in the checks below (constant because they shouldn't change during the loop iteration they are read in)
const bool VLTL = digitalRead(LTL);
const bool VLTM = digitalRead(LTM);
const bool VLTR = digitalRead(LTR);
// check if car not lost (still following a line) and all IR sensors return 1 (not on black line)
if (!lost && VLTL && VLTM && VLTR)
{
stop(); // stop the car
while (messageTimer + messageIntervalTime > millis()){} // wait until there is enough time between messages
Serial.println("111"); // send the meesage 111 corresponding to the sensor value readings wish means searching for track
messageTimer = millis(); // reset the message timer for the next message
// if the code gets here it means that the car has gone of the track
// so we will search for the track using the function below
searchForTrack();
}
else if (!VLTL) // check if the left IR sensor detected a blackline
{
lost = false; // set lost to false since if the left IR sensor detect we are back on track so we should search again when we lose it
lastDirectionRight = false; // set the last rotation direction to left (the vairable is a bool false for left true for right)
antiClockwise(DEFAULT_SPEED); // rotate anticlockwise at DEFAULT_SPEED (set above)
if (messageTimer + messageIntervalTime <= millis())
{
String sensorValues = "";
if (VLTL) { sensorValues += "1";} else {sensorValues += "0";}
if (VLTM) { sensorValues += "1";} else {sensorValues += "0";}
if (VLTR) { sensorValues += "1";} else {sensorValues += "0";}
Serial.println(sensorValues); // send sensor values if enough time since last message
messageTimer = millis(); // reset the message timer for the next message
}
}
else if (!VLTR) // check if the right IR sensor detected a blackline
{
lost = false; // set lost to false since if the right IR sensor detect we are back on track so we should search again when we lose it
lastDirectionRight = true; // set the last rotation direction to right (the vairable is a bool false for left true for right)
clockwise(DEFAULT_SPEED); // rotate clockwise at DEFAULT_SPEED (set above)
if (messageTimer + messageIntervalTime <= millis())
{
String sensorValues = "";
if (VLTL) { sensorValues += "1";} else {sensorValues += "0";}
if (VLTM) { sensorValues += "1";} else {sensorValues += "0";}
if (VLTR) { sensorValues += "1";} else {sensorValues += "0";}
Serial.println(sensorValues); // send sensor values if enough time since last message
messageTimer = millis(); // reset the message timer for the next message
}
}
else if (!VLTM) // check if the middle IR sensor detected a blackline
{
lost = false; // set lost to false since if the middle IR sensor detect we are back on track so we should search again when we lose it
forwards(DEFAULT_SPEED); // move forwards at DEFAULT_SPEED (set above)
if (messageTimer + messageIntervalTime <= millis())
{
String sensorValues = "";
if (VLTL) { sensorValues += "1";} else {sensorValues += "0";}
if (VLTM) { sensorValues += "1";} else {sensorValues += "0";}
if (VLTR) { sensorValues += "1";} else {sensorValues += "0";}
Serial.println(sensorValues); // send sensor values if enough time since last message
messageTimer = millis(); // reset the message timer for the next message
}
}
else // if no other check is true just stop this should only happen if we have lost the track (the end condidtion in this case)
{
stop();
if (messageTimer + messageIntervalTime <= millis())
{
Serial.println("s"); // send s to show that the track is either done or lost and car is stopped if enough time since last message
messageTimer = millis(); // reset the message timer for the next message
}
}
}
void obstacleAvoidance()
{
// store the distance in cm in for later checks
int distanceCM = getDistanceCM();
// if the distance is greater than the decision distance keep moving forward otherwise check left and right direction and move in the direction with most space
if (distanceCM > DECISION_DISTANCE_CM)
{
forwards(DEFAULT_SPEED);
if (messageTimer + messageIntervalTime <= millis())
{
String message = "f" + String(distanceCM);
Serial.println(message); // send current distance if enough time since last message
messageTimer = millis(); // reset the message timer for the next message
}
}
else
{
stop();
while (messageTimer + messageIntervalTime > millis()){} // wait until there is enough time between messages
if (messageTimer + messageIntervalTime <= millis())
{
String message = "r" + String(distanceCM);
Serial.println(message); // send current distance if enough time since last message
messageTimer = millis(); // reset the message timer for the next message
}
redirect(); // checks right and left to decide if it should rotate right or left or moveback a bit instead if both directions are blocked
}
delay(50); // small delay to force small movement before another decision is made smooths out movement a bit
}
// redirects the car to a different direction
void redirect()
{
stop(); // stop the car while making decsisions to avoid crashing
if (newBluetoothMessage() && (recieved[0] == 'L' || recieved[0] == 'M')){return;}
servosweep.write(0); // turn the sensor right
delay(500); // delay to give time for the servo to turn the sensor fully to the right
int distanceRightCM = getDistanceCM(); // get the distance in the right direction
if (newBluetoothMessage() && (recieved[0] == 'L' || recieved[0] == 'M')){return;}
servosweep.write(180); // turn the sensor left now
delay(500); // delay to give the servo time to fully rotate the sensor left
int distanceLeftCM = getDistanceCM(); // get the distance in the left direction
// if both distances are smaller than the decision distance move back for a bit and call the redirect function again to check left and right again now
if (distanceLeftCM < DECISION_DISTANCE_CM && distanceRightCM < DECISION_DISTANCE_CM)
{
if (newBluetoothMessage() && (recieved[0] == 'L' || recieved[0] == 'M')){return;}
backwards(DEFAULT_SPEED); // move the car backwards at the car speed
delay(500); // delay to allow for this small backwards movement to happen
redirect(); // call redirect again to check if the left and right direction are now clear
return; // the last recursivley called redirect will handle setting the sensor back in the right place so exit the function here to avoid waiting an extra 500ms per recursive call
// (this could add up to a lot depending on how deep in the recursion we are)
}
else if (distanceRightCM > distanceLeftCM) // if either left or right distances are larger than the decision distance check if right is bigger than left if so turn right
{
clockwise(DEFAULT_TURN_SPEED); // turn right
delay(TIME_FOR_90_TURN); // delay to allow for 90 degree turn both the turnspeed and the time for the turn are predetermined but might be different depending on car battery level and enviornment
stop(); // stop the car after the turn is done
}
else // if here than left distance is larger than the decision distance and the right distance so turn left
{
antiClockwise(DEFAULT_TURN_SPEED); // turn left
delay(TIME_FOR_90_TURN); // delay to allow for 90 degree turn both the turnspeed and the time for the turn are predetermined but might be different depending on car battery level and enviornment
stop(); // stop the car after the turn is done
}
if (newBluetoothMessage() && (recieved[0] == 'L' || recieved[0] == 'M')){return;}
servosweep.write(90); // rotate the sensor back to the front
delay(500); // delay to give time for the rotation to finsih before moving on
}
// returns the distance in cm determined using the ultrasonic sensor
int getDistanceCM()
{
// sending a 10 microsecond long pulse to the ultrasonic sensor this causes the sensor to send out a sound wave and send back a pulse that we can use to determine the distance
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
// storing the duration that the returned pulse in echo is high for this is the time taken for the sound to travel from the sensor and back after bouncing from an object in microseconds
int duration = pulseIn(ECHO, HIGH);
// return the distance in cm of the object that the sound bounced back from (all constants are precomupted for effiency leading to this formula assuming 20C and 50% humidity)
return duration / 58;
}
// searches for the track by rotating the car 90 degrees clockwise and breaking out of the loop if it find the track again
// if not it rotates 180 degrees anticlockwise and breaking out of the loop if it find the track again the extra 90 degrees is to compensate for rotating 90 degreees clockwise before
// this function is quite usefull when 90 degree turns are encountered
void searchForTrack()
{
// stop for a small amount of time to allow the car to come to halt before rotating
stop();
if (newBluetoothMessage() && (recieved[0] == 'O' || recieved[0] == 'M')){return;}
delay(500);
unsigned long currentTime = millis(); // store the current time (unsigned long to match the data type of millis() and avoid issues when the device has been on for too long)
while (currentTime + TIME_FOR_90_TURN + 50 > millis()) // for the amount of time it takes for a 90 degree turn at 130 speed rotate clockwise and look for a blackline (adding 50 to compensate for the lower time at max speed)
{
if (newBluetoothMessage() && (recieved[0] == 'O' || recieved[0] == 'M')){return;}
if (lastDirectionRight) // this check is to determine which direction to rotate in first
{
clockwise(DEFAULT_TURN_SPEED);
if (!digitalRead(LTR)) // check if a black line was found on the right IR sensor (this is the first sensor to find the line when turning clockwise)
{
return; // if black line was found exit the function and continue with the rest of the code
}
}
else
{
antiClockwise(DEFAULT_TURN_SPEED);
if (!digitalRead(LTL)) // check if a black line was found on the left IR sensor (this is the first sensor to find the line when turning anticlockwise)
{
return; // if black line was found exit the function and continue with the rest of the code
}
}
}
// stop for a small amount of time to allow the car to come to halt before rotating in the opposite direction
stop();
delay(250);
lastDirectionRight = !lastDirectionRight;
currentTime = millis(); // store the current time again
while (currentTime + (TIME_FOR_90_TURN * 2) > millis()) // rotate anticlockwise for double the time it takes to make a 90 degree turn to make a 180 degree turn while searching
{
if (newBluetoothMessage() && (recieved[0] == 'O' || recieved[0] == 'M')){return;}
if (lastDirectionRight) // this check is to determine which direction to rotate in first
{
clockwise(DEFAULT_TURN_SPEED);
if (!digitalRead(LTR)) // check if a black line was found on the right IR sensor (this is the first sensor to find the line when turning clockwise)
{
return; // if black line was found exit the function and continue with the rest of the code
}
}
else
{
antiClockwise(DEFAULT_TURN_SPEED);
if (!digitalRead(LTL)) // check if a black line was found on the left IR sensor (this is the first sensor to find the line when turning anticlockwise)
{
return; // if black line was found exit the function and continue with the rest of the code
}
}
}
// if we get here it means we failed to find the blackline so set lost to true to stop the car from searching when the sensors don't detect anything and stop the car
lost = true;
stop();
}
// moves the car forwards at a given speed from 0 to 255
void forwards(int carSpeed)
{
analogWrite(ENL, carSpeed);
analogWrite(ENR, carSpeed);
digitalWrite(WLF, HIGH);
digitalWrite(WLB, LOW);
digitalWrite(WRF, HIGH);
digitalWrite(WRB, LOW);
}
// moves the car backwards at a given speed from 0 to 255
void backwards(int carSpeed)
{
analogWrite(ENL, carSpeed);
analogWrite(ENR, carSpeed);
digitalWrite(WLF, LOW);
digitalWrite(WLB, HIGH);
digitalWrite(WRF, LOW);
digitalWrite(WRB, HIGH);
}
// rotate the car anticlockwise
void antiClockwise(int carSpeed)
{
analogWrite(ENL, carSpeed);
analogWrite(ENR, carSpeed);
digitalWrite(WLF, LOW);
digitalWrite(WLB, HIGH);
digitalWrite(WRF, HIGH);
digitalWrite(WRB, LOW);
}
// rotate the car clockwise
void clockwise(int carSpeed)
{
analogWrite(ENL, carSpeed);
analogWrite(ENR, carSpeed);
digitalWrite(WLF, HIGH);
digitalWrite(WLB, LOW);
digitalWrite(WRF, LOW);
digitalWrite(WRB, HIGH);
}
// stop the car
void stop()
{
digitalWrite(ENL, LOW);
digitalWrite(ENR, LOW);
// the values below don't matter since ENL and ENR are low however it makes sense for everything to be low if the car is not moving
digitalWrite(WLF, LOW);
digitalWrite(WLB, LOW);
digitalWrite(WRF, LOW);
digitalWrite(WRB, LOW);
}
| true |
fe21401c989e20116c6f22aa103d29a9ab7ece88 | C++ | eligantRU/TAaFL | /LW/nfa2dfa/main.cpp | UTF-8 | 6,736 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <cassert>
#include <string>
#include <vector>
#include <set>
#include "../Common/GraphizUtils.hpp"
using namespace::std;
template <class T>
void UnionSet(set<T> & targ, const set<T> & add)
{
targ.insert(add.cbegin(), add.cend());
}
struct NFA
{
vector<set<string>> states;
vector<string> inputs;
string startState;
set<string> acceptStates;
vector<vector<set<string>>> table;
static constexpr size_t BAD_INDEX = SIZE_MAX;
size_t GetStateIndex(const set<string> & state) const
{
for (size_t i = 0; i < states.size(); ++i)
{
if (state == states[i])
{
return i;
}
}
return BAD_INDEX;
}
size_t GetInputIndex(const string & str) const
{
for (size_t i = 0; i < inputs.size(); ++i)
{
if (str == inputs[i])
{
return i;
}
}
return BAD_INDEX;
}
void InsertState(const set<string> & srcState, const string & input, const set<string> & targState)
{
const size_t srcStateIndex = GetStateIndex(srcState);
const size_t inputIndex = GetInputIndex(input);
assert(srcStateIndex != BAD_INDEX && inputIndex != BAD_INDEX);
UnionSet(table[srcStateIndex][inputIndex], targState);
}
void AddPowersetState(const set<string> & powerState)
{
states.push_back(powerState);
const vector<set<string>> emptyNode(inputs.size());
table.push_back(emptyNode);
for (const auto & state : powerState)
{
const size_t stateInd = GetStateIndex({ state });
assert(stateInd != BAD_INDEX);
for (size_t in = 0; in < inputs.size(); ++in)
{
UnionSet(table.back()[in], table[stateInd][in]);
}
}
}
};
vector<string> GetInBraceParts(const string & str, char lbrace, char rbrace)
{
vector<string> result;
size_t startFrom = 0;
while (startFrom < str.length())
{
const size_t begin = str.find(lbrace, startFrom);
const size_t end = str.find(rbrace, startFrom);
const bool dataFound = (begin != string::npos && end != string::npos && begin < end);
if (dataFound)
{
const size_t dataLength = end - begin - 1;
result.push_back(str.substr(begin + 1, dataLength));
startFrom = end + 1;
}
else
{
startFrom = string::npos;
}
}
return result;
}
vector<string> SplitString(const string & str, const string & delimiter)
{
vector<string> result;
size_t startIndex = 0;
while (startIndex < str.length())
{
const size_t delimiterIndex = str.find(delimiter, startIndex);
const bool delimiterFound = (delimiterIndex != string::npos);
const size_t partLength = delimiterFound ? delimiterIndex - startIndex : string::npos;
result.push_back(str.substr(startIndex, partLength));
startIndex = delimiterFound ? delimiterIndex + delimiter.length() : string::npos;
}
return result;
}
vector<set<string>> StrVectorToStrSetVector(const vector<string> & strVector)
{
vector<set<string>> result;
for (auto str : strVector)
{
result.push_back({ str });
}
return result;
}
set<string> ToSet(const vector<string> & strVector)
{
return { strVector.cbegin(), strVector.cend() };
}
string GetInBracePart(const string & str, char lbrace, char rbrace)
{
const vector<string> parts = GetInBraceParts(str, lbrace, rbrace);
assert(parts.size() == 1);
return parts[0];
}
void ParseTransition(const string & str, string & srcState, string & input, string & targState)
{
const vector<string> parts = SplitString(str, " = ");
assert(parts.size() == 2);
const vector<string> leftPartData = SplitString(GetInBracePart(str, '(', ')'), ", ");
assert(leftPartData.size() == 2);
srcState = leftPartData[0];
input = leftPartData[1];
targState = parts[1];
}
NFA ReadFromFile(istream & input)
{
NFA result;
{
string definition;
getline(input, definition);
const vector<string> defParts = GetInBraceParts(definition, '{', '}');
assert(defParts.size() == 4);
result.states = StrVectorToStrSetVector(SplitString(defParts[0], ", "));
result.inputs = SplitString(defParts[1], ", ");
result.startState = defParts[2];
result.acceptStates = ToSet(SplitString(defParts[3], ", "));
}
{
const vector<set<string>> emptyNode(result.inputs.size());
result.table.assign(result.states.size(), emptyNode);
}
string curLine;
while (getline(input, curLine))
{
string srcState, input, targState;
ParseTransition(curLine, srcState, input, targState);
result.InsertState({ srcState }, input, { targState });
}
return result;
}
void DefineAllPowersetStates(NFA & nfa)
{
for (size_t st = 0; st < nfa.table.size(); ++st)
{
assert(nfa.states.size() == nfa.table.size());
for (size_t in = 0; in < nfa.inputs.size(); ++in)
{
if (!nfa.table[st][in].empty() && nfa.GetStateIndex(nfa.table[st][in]) == NFA::BAD_INDEX)
{
nfa.AddPowersetState(nfa.table[st][in]);
}
}
}
}
bool IsStateAccepting(const set<string> & state, const set<string> & acceptingStates)
{
for (const auto & acceptingState : acceptingStates)
{
if (state.find(acceptingState) != state.cend())
{
return true;
}
}
return false;
}
vector<bool> GetAcceptingStates(const NFA & nfa)
{
vector<bool> result(nfa.states.size(), false);
for (size_t st = 0; st < nfa.states.size(); ++st)
{
if (IsStateAccepting(nfa.states[st], nfa.acceptStates))
{
result[st] = true;
}
}
return result;
}
string IndexToNewState(size_t index)
{
string result;
if (index < 26)
{
result = char('A' + index);
}
else
{
result = "S" + to_string(index - 26);
}
return result;
}
void PrintAsDFA(ostream & output, const NFA & nfa)
{
output << "M = ({";
for (size_t st = 0; st < nfa.states.size(); ++st)
{
if (st)
{
output << ", ";
}
output << IndexToNewState(st);
}
output << "}, {";
for (size_t in = 0; in < nfa.inputs.size(); ++in)
{
if (in)
{
output << ", ";
}
output << nfa.inputs[in];
}
output << "}, F, {" << IndexToNewState(nfa.GetStateIndex({ nfa.startState })) << "}, {";
const vector<bool> acceptingStates = GetAcceptingStates(nfa);
bool alreadyPrinted = false;
for (size_t st = 0; st < nfa.states.size(); ++st)
{
if (acceptingStates[st])
{
if (alreadyPrinted)
{
output << ", ";
}
output << IndexToNewState(st);
alreadyPrinted = true;
}
}
output << "})\n";
std::vector<WeightedEdge> weightedEdges;
for (size_t st = 0; st < nfa.states.size(); ++st)
{
for (size_t in = 0; in < nfa.inputs.size(); ++in)
{
if (!nfa.table[st][in].empty())
{
weightedEdges.emplace_back(Edge{ st, nfa.GetStateIndex(nfa.table[st][in]) }, nfa.inputs[in]);
output << "F(" << IndexToNewState(st) << ", " << nfa.inputs[in] << ") = " << IndexToNewState(nfa.GetStateIndex(nfa.table[st][in])) << "\n";
}
}
}
ToGraphizFormat(weightedEdges);
}
int main()
{
NFA nfa = ReadFromFile(cin);
DefineAllPowersetStates(nfa);
PrintAsDFA(cout, nfa);
}
| true |
87be99f51160c5fde716cd48e2e9dc274fe46624 | C++ | DzikuVx/e45-ttl-100-base-station | /e45-ttl-100_range_test_sender.ino | UTF-8 | 1,491 | 2.828125 | 3 | [] | no_license | #define LED_PIN 13
#define UART_SPEED 57600
/*
* This code is for stationary device
*/
uint8_t counter = 0;
void setup() {
delay(2000);
pinMode(LED_PIN, OUTPUT);
Serial.begin(UART_SPEED);
}
enum dataStates {
IDLE,
HEADER_RECEIVED,
DATA_RECEIVED,
CRC
};
uint8_t protocolState = IDLE;
uint8_t dataBytesReceived = 0;
uint32_t incomingData;
bool doRetransmit = false;
void loop() {
if (Serial.available()) {
uint8_t data = Serial.read();
if (protocolState == IDLE && data == 0xff) {
protocolState = HEADER_RECEIVED;
dataBytesReceived = 0;
incomingData = 0;
} else if (protocolState == HEADER_RECEIVED) {
if (dataBytesReceived == 0) {
incomingData = data;
} else {
//Shift data to the left
incomingData = (uint32_t) incomingData << 8;
incomingData = (uint32_t) ((uint32_t) incomingData) + data;
}
dataBytesReceived++;
if (dataBytesReceived == 4) {
protocolState = IDLE;
doRetransmit = true;
digitalWrite(LED_PIN, HIGH);
}
}
}
if (doRetransmit) {
Serial.write(0xfe);
uint32_t toSend = incomingData;
byte buf[4];
buf[0] = toSend & 255;
buf[1] = (toSend >> 8) & 255;
buf[2] = (toSend >> 16) & 255;
buf[3] = (toSend >> 24) & 255;
Serial.write(buf, sizeof(buf));
Serial.end();
delay(30);
digitalWrite(LED_PIN, LOW);
Serial.begin(UART_SPEED);
doRetransmit = false;
}
}
| true |
25128ec805891764755856ed849ea83cd2aee53f | C++ | gmtranthanhtu/competitive-programming | /UVa-AC/uva 10069 Distinct Subsequences.cpp | UTF-8 | 3,815 | 2.609375 | 3 | [] | no_license | /*
Name: UVa 10069 Distinct Subsequences
Copyright:
Author: 3T
Date: 02/06/10 16:58
Description: DP
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#define Max1 10005
#define Max2 105
#define INP "10069.INP"
int N,i,sX,sZ,j,r,len1,len2,MaxLen;
int M[Max2][Max1][Max2+1];
char X[Max1],Z[Max2];
void Add2Cell(int rowD, int colD, int rowS1, int colS1, int rowS2, int colS2){
int j;
for(j = Max2; j >= 0; j--){
if(M[rowS1][colS1][j] != 0) break;
}
len1 = j;
for(j = Max2; j >= 0; j--){
if(M[rowS2][colS2][j] != 0) break;
}
len2 = j;
if(len1 == -1 && len2 >= 0){
for(j = 0; j <= len2; j++){
M[rowD][colD][j] = M[rowS2][colS2][j];
}
for(j = len2 + 1; j <= Max2; j++) M[rowD][colD][j] = 0;
}
else if(len2 == -1 && len1 >= 0){
for(j = 0; j <= len1; j++){
M[rowD][colD][j] = M[rowS1][colS1][j];
}
for(j = len1 + 1; j <= Max2; j++) M[rowD][colD][j] = 0;
}
else if(len2 == -1 && len1 == -1){
for(j = 0; j <= Max2; j++){
M[rowD][colD][j] = 0;
}
}
else if(len2 >= 0 && len1 >= 0){
// MaxLen = std::max(len1,len2);
if(len1 > len2) MaxLen = len1;
else MaxLen = len2;
// printf("Test1: %d\n",MaxLen);
r = 0;
for(j = 0; j <= MaxLen; j++){
int temp = M[rowS1][colS1][j] + M[rowS2][colS2][j] + r;
if(temp < 10) {M[rowD][colD][j] = temp; r = 0;}
else{
M[rowD][colD][j] = temp % 10;
r = 1;
}
}
if(r == 1) M[rowD][colD][MaxLen + 1] = 1;
else M[rowD][colD][MaxLen + 1] = 0;
for(int u = MaxLen + 2; u <= Max2; u++){
M[rowD][colD][u] = 0;
}
}
}
void PrintCell(int row, int col){
int j;
for(j = Max2; j >= 0; j--){
if(M[row][col][j] != 0) break;
}
if(j < 0){printf("%d",0);return;}
else{
for(int p = j; p >= 0; p--){
printf("%d",M[row][col][p]);
}
}
}
int main () {
// FILE *f = fopen(INP, "r");
// FILE *f = stdin; ------------> wrong answer
scanf("%d ",&N);
// getchar();
for(i = 1; i <= N; i++){
// memset(M,0,sizeof(M)); ----------> time limit
gets(X);
sX = strlen(X);
gets(Z);
sZ = strlen(Z);
if(sX == 0 && sZ == 0) printf("1\n");
else if(sZ > sX) printf("0\n");
else{
for(int p = 0; p <= sX; p++){
M[0][p][0] = 1;
for(j = 1; j <= Max2; j++){
M[0][p][j] = 0;
}
}
for(int p = 1; p <= sZ ; p++){
for(j = 0; j <= Max2; j++){
M[p][p - 1][j] = 0;
}
}
for(int p = 1; p <= sZ; p++){
for(int q = p; q <= sX; q++){
if(X[q - 1] == Z[p - 1]){
Add2Cell(p,q,p,q - 1,p - 1,q - 1);
}
else{
for(int t = 0; t <= Max2; t++){
M[p][q][t] = M[p][q-1][t];
}
}
}
}
PrintCell(sZ,sX);
printf("\n");
}
}
// getchar();
return 0;
}
| true |
3ac0ea3f4c36f8fa6c8c321d276bc32e21185d39 | C++ | bolart161/polytech-c | /boltunov.artem/B1/taskNum2.cpp | UTF-8 | 677 | 3.203125 | 3 | [] | no_license | #include <fstream>
#include <vector>
#include <memory>
#include <iostream>
int taskNum2(const char *fileName)
{
std::ifstream inputStream(fileName);
if (!inputStream) {
std::cerr << "This file doesn't exist;";
return 1;
}
inputStream.seekg(0, inputStream.end);
const size_t length = inputStream.tellg();
inputStream.seekg(0, inputStream.beg);
std::unique_ptr<char[]> array (new char[length]);
inputStream.read(array.get(), length);
if (inputStream) {
std::vector<char> vector(array.get(), array.get() + length);
for (auto i = vector.begin(); i != vector.end(); i++) {
std::cout << *i;
}
}
inputStream.close();
return 0;
}
| true |
916065f934b833703366ad9ea61706e86bf20fe2 | C++ | Anubis-13/EmulationStation | /es-core/src/guis/GuiTextEditPopupKeyboard.cpp | WINDOWS-1252 | 12,298 | 2.515625 | 3 | [
"Apache-2.0",
"MIT"
] | permissive | #include "guis/GuiTextEditPopupKeyboard.h"
#include "components/MenuComponent.h"
#include "Log.h"
#include "utils/StringUtil.h"
std::vector<std::vector<UNICODE_CHARTYPE>> kbFrench {
{ UNICODE_CHARS("&"), UNICODE_CHARS(""), UNICODE_CHARS("\""), UNICODE_CHARS("'"), UNICODE_CHARS("("), UNICODE_CHARS("#"), UNICODE_CHARS(""), UNICODE_CHARS("!"), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(")"), UNICODE_CHARS("-") },
{ UNICODE_CHARS("1"), UNICODE_CHARS("2"), UNICODE_CHARS("3"), UNICODE_CHARS("4"), UNICODE_CHARS("5"), UNICODE_CHARS("6"), UNICODE_CHARS("7"), UNICODE_CHARS("8"), UNICODE_CHARS("9"), UNICODE_CHARS("0"), UNICODE_CHARS("@"), UNICODE_CHARS("_") },
/*
{ UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS("\\"), UNICODE_CHARS("|"), UNICODE_CHARS(""), UNICODE_CHARS("") },
{ UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS("", ""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS("") },
*/
{ UNICODE_CHARS("a"), UNICODE_CHARS("z"), UNICODE_CHARS("e"), UNICODE_CHARS("r"), UNICODE_CHARS("t"), UNICODE_CHARS("y"), UNICODE_CHARS("u"), UNICODE_CHARS("i"), UNICODE_CHARS("o"), UNICODE_CHARS("p"), UNICODE_CHARS("^"), UNICODE_CHARS("$") },
{ UNICODE_CHARS("A"), UNICODE_CHARS("Z"), UNICODE_CHARS("E"), UNICODE_CHARS("R"), UNICODE_CHARS("T"), UNICODE_CHARS("Y"), UNICODE_CHARS("U"), UNICODE_CHARS("I"), UNICODE_CHARS("O"), UNICODE_CHARS("P"), UNICODE_CHARS(""), UNICODE_CHARS("*") },
{ UNICODE_CHARS("q"), UNICODE_CHARS("s"), UNICODE_CHARS("d"), UNICODE_CHARS("f"), UNICODE_CHARS("g"), UNICODE_CHARS("h"), UNICODE_CHARS("j"), UNICODE_CHARS("k"), UNICODE_CHARS("l"), UNICODE_CHARS("m"), UNICODE_CHARS(""), UNICODE_CHARS("`") },
{ UNICODE_CHARS("Q"), UNICODE_CHARS("S"), UNICODE_CHARS("D"), UNICODE_CHARS("F"), UNICODE_CHARS("G"), UNICODE_CHARS("H"), UNICODE_CHARS("J"), UNICODE_CHARS("K"), UNICODE_CHARS("L"), UNICODE_CHARS("M"), UNICODE_CHARS("%"), UNICODE_CHARS("") },
//SHIFT key at position 0
{ UNICODE_CHARS("SHIFT"), UNICODE_CHARS("<"), UNICODE_CHARS("w"), UNICODE_CHARS("x"), UNICODE_CHARS("c"), UNICODE_CHARS("v"), UNICODE_CHARS("b"), UNICODE_CHARS("n"), UNICODE_CHARS(","), UNICODE_CHARS(";"), UNICODE_CHARS(":"), UNICODE_CHARS("=") },
{ UNICODE_CHARS("SHIFT"), UNICODE_CHARS(">"), UNICODE_CHARS("W"), UNICODE_CHARS("X"), UNICODE_CHARS("C"), UNICODE_CHARS("V"), UNICODE_CHARS("B"), UNICODE_CHARS("N"), UNICODE_CHARS("?"), UNICODE_CHARS("."), UNICODE_CHARS("/"), UNICODE_CHARS("+") }
};
std::vector<std::vector<UNICODE_CHARTYPE>> kbUs {
{ UNICODE_CHARS("1"), UNICODE_CHARS("2"), UNICODE_CHARS("3"), UNICODE_CHARS("4"), UNICODE_CHARS("5"), UNICODE_CHARS("6"), UNICODE_CHARS("7"), UNICODE_CHARS("8"), UNICODE_CHARS("9"), UNICODE_CHARS("0"), UNICODE_CHARS("_"), UNICODE_CHARS("+") },
{ UNICODE_CHARS("!"), UNICODE_CHARS("@"), UNICODE_CHARS("#"), UNICODE_CHARS("$"), UNICODE_CHARS("%"), UNICODE_CHARS("^"), UNICODE_CHARS("&"), UNICODE_CHARS("*"), UNICODE_CHARS("("), UNICODE_CHARS(")"), UNICODE_CHARS("-"), UNICODE_CHARS("=") },
/*
{ UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS("") },
{ UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS(""), UNICODE_CHARS("") },
*/
{ UNICODE_CHARS("q"), UNICODE_CHARS("w"), UNICODE_CHARS("e"), UNICODE_CHARS("r"), UNICODE_CHARS("t"), UNICODE_CHARS("y"), UNICODE_CHARS("u"), UNICODE_CHARS("i"), UNICODE_CHARS("o"), UNICODE_CHARS("p"), UNICODE_CHARS("{"), UNICODE_CHARS("}") },
{ UNICODE_CHARS("Q"), UNICODE_CHARS("W"), UNICODE_CHARS("E"), UNICODE_CHARS("R"), UNICODE_CHARS("T"), UNICODE_CHARS("Y"), UNICODE_CHARS("U"), UNICODE_CHARS("I"), UNICODE_CHARS("O"), UNICODE_CHARS("P"), UNICODE_CHARS("["), UNICODE_CHARS("]") },
{ UNICODE_CHARS("a"), UNICODE_CHARS("s"), UNICODE_CHARS("d"), UNICODE_CHARS("f"), UNICODE_CHARS("g"), UNICODE_CHARS("h"), UNICODE_CHARS("j"), UNICODE_CHARS("k"), UNICODE_CHARS("l"), UNICODE_CHARS(";"), UNICODE_CHARS("\""), UNICODE_CHARS("|") },
{ UNICODE_CHARS("A"), UNICODE_CHARS("S"), UNICODE_CHARS("D"), UNICODE_CHARS("F"), UNICODE_CHARS("G"), UNICODE_CHARS("H"), UNICODE_CHARS("J"), UNICODE_CHARS("K"), UNICODE_CHARS("L"), UNICODE_CHARS(":"), UNICODE_CHARS("'"), UNICODE_CHARS("\\") },
{ UNICODE_CHARS("SHIFT"), UNICODE_CHARS("~"), UNICODE_CHARS("z"), UNICODE_CHARS("x"), UNICODE_CHARS("c"), UNICODE_CHARS("v"), UNICODE_CHARS("b"), UNICODE_CHARS("n"), UNICODE_CHARS("m"), UNICODE_CHARS(","), UNICODE_CHARS("."), UNICODE_CHARS("?") },
{ UNICODE_CHARS("SHIFT"), UNICODE_CHARS("`"), UNICODE_CHARS("Z"), UNICODE_CHARS("X"), UNICODE_CHARS("C"), UNICODE_CHARS("V"), UNICODE_CHARS("B"), UNICODE_CHARS("N"), UNICODE_CHARS("M"), UNICODE_CHARS("<"), UNICODE_CHARS(">"), UNICODE_CHARS("/") },
};
GuiTextEditPopupKeyboard::GuiTextEditPopupKeyboard(Window* window, const std::string& title, const std::string& initValue,
const std::function<void(const std::string&)>& okCallback, bool multiLine, const char* acceptBtnText)
: GuiComponent(window), mBackground(window, ":/frame.png"), mGrid(window, Vector2i(1, 7)), mMultiLine(multiLine)
{
auto theme = ThemeData::getMenuTheme();
mBackground.setImagePath(theme->Background.path); // ":/frame.png"
mBackground.setCenterColor(theme->Background.color);
mBackground.setEdgeColor(theme->Background.color);
addChild(&mBackground);
addChild(&mGrid);
mTitle = std::make_shared<TextComponent>(mWindow, Utils::String::toUpper(title), ThemeData::getMenuTheme()->Title.font, ThemeData::getMenuTheme()->Title.color, ALIGN_CENTER);
mText = std::make_shared<TextEditComponent>(mWindow);
mText->setValue(initValue);
if(!multiLine)
mText->setCursor(initValue.size());
// Header
mGrid.setEntry(mTitle, Vector2i(0, 0), false, true);
// Text edit add
mGrid.setEntry(mText, Vector2i(0, 1), true, false, Vector2i(1, 1));
std::vector< std::vector< std::shared_ptr<ButtonComponent> > > buttonList;
// Keyboard
// Case for if multiline is enabled, then don't create the keyboard.
if (!mMultiLine)
{
std::vector<std::vector<UNICODE_CHARTYPE>> &layout = kbUs;
if (GuiTextTool::getLanguage() == "fr")
layout = kbFrench;
for (unsigned int i = 0; i < layout.size() / 2; i++)
{
std::vector<std::shared_ptr<ButtonComponent>> buttons;
for (unsigned int j = 0; j < layout[2 * i].size(); j++)
{
#ifdef WIN32
std::wstring toConvert = layout[2 * i][j];
std::string atj = GuiTextTool::convertFromWideString(toConvert);
toConvert = layout[2 * i + 1][j];
std::string atjs = GuiTextTool::convertFromWideString(toConvert);
#else
std::string atj = layout[2 * i][j];
std::string atjs = layout[2 * i + 1][j];
#endif
if (atj == "SHIFT")
{
// Special case for shift key
mShiftButton = std::make_shared<ButtonComponent>(mWindow, "SHIFT", _T("SHIFTS FOR UPPER,LOWER, AND SPECIAL"), [this] {
shiftKeys();
});
buttons.push_back(mShiftButton);
}
else
buttons.push_back(makeButton(atj, atjs));
}
buttonList.push_back(buttons);
}
}
const float gridWidth = Renderer::getScreenWidth() * 0.85f;
mKeyboardGrid = makeMultiDimButtonGrid(mWindow, buttonList, gridWidth - 20);
mGrid.setEntry(mKeyboardGrid, Vector2i(0, 2), true, false);
// Accept/Cancel buttons
buttons.push_back(std::make_shared<ButtonComponent>(mWindow, _L(acceptBtnText), _L(acceptBtnText), [this, okCallback] { okCallback(mText->getValue()); delete this; }));
buttons.push_back(std::make_shared<ButtonComponent>(mWindow, _T("SPACE"), _T("SPACE"), [this] {
mText->startEditing();
mText->textInput(" ");
mText->stopEditing();
}));
buttons.push_back(std::make_shared<ButtonComponent>(mWindow, _T("DELETE"), _T("DELETE A CHAR"), [this] {
mText->startEditing();
mText->textInput("\b");
mText->stopEditing();
}));
buttons.push_back(std::make_shared<ButtonComponent>(mWindow, _T("CANCEL"), _T("discard changes"), [this] { delete this; }));
mButtons = makeButtonGrid(mWindow, buttons);
mGrid.setEntry(mButtons, Vector2i(0, 3), true, false);
// Determine size from text size
float textHeight = mText->getFont()->getHeight();
if (multiLine)
textHeight *= 6;
mText->setSize(gridWidth - 40, textHeight);
// If multiline, set all diminsions back to default, else draw size for keyboard.
if (mMultiLine)
{
setSize(Renderer::getScreenWidth() * 0.5f, mTitle->getFont()->getHeight() + textHeight + mKeyboardGrid->getSize().y() + 40);
setPosition((Renderer::getScreenWidth() - mSize.x()) / 2, (Renderer::getScreenHeight() - mSize.y()) / 2);
}
else
{
setSize(gridWidth, mTitle->getFont()->getHeight() + textHeight + 40 + mKeyboardGrid->getSize().y() + mButtons->getSize().y());
setPosition((Renderer::getScreenWidth() - mSize.x()) / 2, (Renderer::getScreenHeight() - mSize.y()) / 2);
}
}
void GuiTextEditPopupKeyboard::onSizeChanged()
{
mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32, -32));
mText->setSize(mSize.x() - 40, mText->getSize().y());
float fullHeight = mTitle->getFont()->getHeight() + mText->getSize().y() + mKeyboardGrid->getSize().y() + mButtons->getSize().y();
// update grid
mGrid.setRowHeightPerc(0, mTitle->getFont()->getHeight() / fullHeight);
mGrid.setRowHeightPerc(1, mText->getSize().y() / fullHeight);
mGrid.setRowHeightPerc(2, mKeyboardGrid->getSize().y() / fullHeight);
mGrid.setRowHeightPerc(3, mButtons->getSize().y() / fullHeight);
mGrid.setSize(mSize);
mKeyboardGrid->onSizeChanged();
/*
mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32, -32));
mText->setSize(mSize.x() - 40, mText->getSize().y());
// update grid
mGrid.setRowHeightPerc(0, mTitle->getFont()->getHeight() / mSize.y());
mGrid.setRowHeightPerc(2, mKeyboardGrid->getSize().y() / mSize.y());
mGrid.setSize(mSize);*/
}
bool GuiTextEditPopupKeyboard::input(InputConfig* config, Input input)
{
if (GuiComponent::input(config, input))
return true;
// pressing back when not text editing closes us
if (config->isMappedTo("b", input) && input.value)
{
delete this;
return true;
}
// For deleting a chara (Left Top Button)
if (config->isMappedTo("lefttop", input) && input.value) {
mText->startEditing();
mText->textInput("\b");
mText->stopEditing();
}
// For Adding a space (Right Top Button)
if (config->isMappedTo("righttop", input) && input.value) {
mText->startEditing();
mText->textInput(" ");
}
// For Shifting (X)
if (config->isMappedTo("x", input) && input.value) {
if (mShift) mShift = false;
else mShift = true;
shiftKeys();
}
return false;
}
void GuiTextEditPopupKeyboard::update(int deltatime) {
}
std::shared_ptr<ButtonComponent> GuiTextEditPopupKeyboard::makeButton(const std::string& key, const std::string& shiftedKey)
{
std::shared_ptr<ButtonComponent> button = std::make_shared<ButtonComponent>(mWindow, key, key, [this, key, shiftedKey] {
mText->startEditing();
if (mShift)
mText->textInput(shiftedKey.c_str());
else
mText->textInput(key.c_str());
mText->stopEditing();
}, false);
KeyboardButton kb(button, key, shiftedKey);
keyboardButtons.push_back(kb);
return button;
}
// Shifts the keys when user hits the shift button.
void GuiTextEditPopupKeyboard::shiftKeys()
{
mShift = !mShift;
if (mShift)
mShiftButton->setColorShift(0xFF0000FF);
else
mShiftButton->removeColorShift();
for (auto & kb : keyboardButtons)
{
const std::string& text = mShift ? kb.shiftedKey : kb.key;
kb.button->setText(text, text, false);
}
}
std::vector<HelpPrompt> GuiTextEditPopupKeyboard::getHelpPrompts()
{
std::vector<HelpPrompt> prompts = mGrid.getHelpPrompts();
prompts.push_back(HelpPrompt("x", _T("SHIFT")));
prompts.push_back(HelpPrompt("b", _T("BACK")));
prompts.push_back(HelpPrompt("r", _T("SPACE")));
prompts.push_back(HelpPrompt("l", _T("DELETE")));
return prompts;
}
| true |
417e682776fc3a0520001f62ad6e7ffda4dfd091 | C++ | denis-gubar/Leetcode | /Depth-first Search/0934. Shortest Bridge.cpp | UTF-8 | 1,355 | 2.53125 | 3 | [] | no_license | class Solution {
public:
int shortestBridge(vector<vector<int>>& A) {
vector<int> dx{ 0, 1, 0, -1 };
vector<int> dy{ 1, 0, -1, 0 };
vector<vector<int>> M(A);
int X = A.size(), Y = A[0].size();
bool isCompleted = false;
for (int i = 0; i < X && !isCompleted; ++i)
for (int j = 0; j < Y; ++j)
if (M[i][j] == 1)
{
M[i][j] = 2;
queue<int> q;
q.push(i); q.push(j);
while (!q.empty())
{
int x = q.front(); q.pop();
int y = q.front(); q.pop();
for (int t = 0; t < 4; ++t)
{
int nx = x + dx[t];
int ny = y + dy[t];
if (nx >= 0 && nx < X && ny >= 0 && ny < Y && M[nx][ny] == 1)
{
M[nx][ny] = 2;
q.push(nx); q.push(ny);
}
}
}
isCompleted = true;
break;
}
queue<int> q;
for (int i = 0; i < X; ++i)
for (int j = 0; j < Y; ++j)
if (M[i][j] == 2)
{
q.push(0); q.push(i); q.push(j);
}
while (!q.empty())
{
int s = q.front(); q.pop();
int x = q.front(); q.pop();
int y = q.front(); q.pop();
for (int t = 0; t < 4; ++t)
{
int nx = x + dx[t];
int ny = y + dy[t];
if (nx >= 0 && nx < X && ny >= 0 && ny < Y && M[nx][ny] != 2)
{
if (M[nx][ny] == 1)
return s;
M[nx][ny] = 2;
q.push(s + 1); q.push(nx); q.push(ny);
}
}
}
return -1;
}
}; | true |
2faed5bec99e85cd9ab548afb064872fa5359531 | C++ | dean-mrack/TrapForMonsters | /TrapForMonsters.ino | UTF-8 | 2,239 | 2.796875 | 3 | [
"BSD-2-Clause"
] | permissive | // -------------------------------------------------
// Trap for Monsters
// Ulrix Creation © 2016
// Version: 1.4.12
// 2016-10-13
// -------------------------------------------------
#define Trig 8
#define Echo 7
unsigned int impulseTime=0;
unsigned int distance_sm1=0;
unsigned int distance_sm2=0;
unsigned int distance_sz=0; // distance of save zone
void soundOfDanger()
{
tone(9,1000);
delay(500);
tone(9,800);
delay(500);
tone(9,1000);
delay(500);
tone(9,800);
delay(500);
noTone( 9);
delay(500);
}
void soundOfStart()
{
tone(9,700);
delay(500);
tone(9,800);
delay(500);
tone(9,900);
delay(500);
tone(9,1000);
delay(500);
noTone( 9);
delay(500);
}
int readSonicData()
{
// Код дальномера. Тупая задежка, как принято в Arduino. Никаких таймеров.
digitalWrite( Trig, HIGH);// Подаем импульс на вход trig дальномера
delayMicroseconds( 10); // равный 10 микросекундам
digitalWrite( Trig, LOW); // Отключаем
impulseTime = pulseIn( Echo, HIGH); // Замеряем длину импульса
return impulseTime/58; // Пересчитываем в сантиметры
}
void setup()
{
pinMode( 9, OUTPUT); // пьезо-пищалка инициируем как выход
pinMode( Trig, OUTPUT); // инициируем как выход
pinMode( Echo, INPUT); // инициируем как вход
Serial.begin( 9600);
distance_sm1 = distance_sm1 = 0;
while( distance_sm1 != distance_sm1)
{
distance_sm1 = readSonicData();
delay( 4000);
distance_sm2 = readSonicData();
if( distance_sm1 == distance_sm2 ) distance_sz = distance_sm2;
}
soundOfStart();
delay( 2500);
}
void loop()
{
distance_sm1 = readSonicData();
if( ( distance_sm1 < distance_sz - 6) || ( distance_sm1 > distance_sz + 6))
{
soundOfDanger();
Serial.println( "DANGER : MONSTER DETECTED");
delay( 1000);
distance_sz = distance_sm1;
}
else
{
Serial.println( "INFORMATION : UNDETECTED MOITION");
delay( 1000);
}
}
| true |
7971089e2a4f9cc0fe6958b5f89abba849726ebe | C++ | russellkir/project_euler | /src/id_12.cpp | UTF-8 | 937 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <math.h>
using namespace std;
inline long nth_triangle(int n){
return (n*n + n) / 2;
}
int is_fact(int n, int f) {
return n % f == 0;
}
int num_divisors(int n){
int divisors = 1;
int count = 0;
while(n % 2 == 0) {
++count;
n /= 2;
}
divisors *= (count + 1);
for(int i = 3; i <= n; i+= 2) {
int count = 0;
while(n % i == 0) {
n /= i;
++count;
}
divisors *= (count + 1);
}
return divisors;
}
long n_divisors(int n) {
long i = 1;
long nth_tri = nth_triangle(i);
while(true){
cout << i << "th tri: " << nth_tri << endl;
if(num_divisors(nth_tri) > n) {
cout << nth_tri << endl;
break;
}
nth_tri = nth_triangle(++i);
}
return i;
}
int main() {
n_divisors(500);
return 0;
}
| true |
93cdbd6d2649e28e053dad04798a86e6b9833f64 | C++ | thegamer1907/Code_Analysis | /DP/364.cpp | UTF-8 | 495 | 2.6875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
main()
{
int n,m;
cin>>n;
int *a=(int*)malloc(n*sizeof(int));
for(int i=0;i<n;i++)
cin>>a[i];
cin>>m;
int *b=(int*)malloc(m*sizeof(int));
for(int i=0;i<m;i++)
cin>>b[i];
sort(a,a+n);
sort(b,b+m);
int i=0,j=0,ans=0;
while(i<n && j<m)
{
if(abs(a[i]-b[j])<=1)
{
ans++;i++;j++;
}
else if(a[i]<b[j])
i++;
else
j++;
}
cout<<ans<<endl;
free(a);
free(b);
}
| true |
adf97948860463b00d2758a9e8eaa8a21fb26213 | C++ | rahulinsane11/leetcode | /1.two_sum2.cpp | UTF-8 | 627 | 3.203125 | 3 | [] | no_license | class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) { // T.C.=O(n) , S.C.=O(n)
vector<int> result;
unordered_map<int,int> hash_table;
for(int i=0; i<nums.size(); i++)
{
int x= target- nums.at(i);
if(hash_table.find(x) != hash_table.end()) // if x is present in hash table
{
result.push_back(i);
result.push_back(hash_table.find(x)->second);
break;
}
else
hash_table[nums.at(i)]=i;
}
return result;
}
}; | true |
bec7ff0a7ad7122eac354976da460cff66a2f26b | C++ | Teckwar160/EGE | /include/std/Windows/Others/WindowsTerminal.hpp | UTF-8 | 4,366 | 3.15625 | 3 | [] | no_license | #ifndef WINDOWSTERMINAL_HPP
#define WINDOWSTERMINAL_HPP
#include <core/Entity.hpp>
#include <core/Manager.hpp>
#include <core/Alias.hpp>
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <iostream>
#include <string>
namespace EGE::STD::TERMINAL::WINDOWS{
class Terminal : public EGE::CORE::Entity<Terminal>{
private:
/**Tamaño en x del tablero*/
int width;
/**Tamaño en y del tablero*/
int tall;
/**Instancia de Terminal*/
static inline Terminal *terminal = nullptr;
/**
*@brief Método constructor del tablero,
*@param width Tamaño en x del tablero.
*@param tall Tamaño en y del tablero.
*/
Terminal(int width, int tall);
public:
/**
* @brief Método que regresa una instancia de Terminal.
* @param x Tamaño en horizontal del tablero.
* @param y Tamaño en vertical del tablero.
* @return Instancia unica de terminal.
*/
static Terminal *getTerminal(int x,int y);
/**
* @brief Método que regresa una instancia de Terminal.
* @return Instancia unica de terminal.
*/
static Terminal *getTerminal();
/**
*@brief Método destructor de la clase.
*/
~Terminal();
/**
*@brief Método que oculta el cursor de la terminal.
*/
void hideCursor();
/**
*@brief Método que mueve el cursor en la temrinal.
*@param x Coordenada en x en la temrinal.
*@param y Coordenada en y en la temrinal.
*/
void gotoxy(int x, int y);
/**
* @brief Método que define el color de los limites de la terminal y el fondo.
* @param color Color de los limites y del fondo.
*/
void setColor(unsigned short color);
/**
*@brief Métdodo que pinta los limites del tablero.
*@param charHorizontal Caracter de las lineas horizontales del tablero.
*@param charVertical Caracter de las lineas verticales del tablero.
*@param charCorner1 Caracter de la esquina superior izquierda del tablero.
*@param charCorner2 Caracter de la esquina superior derecha del tablero.
*@param charCorner3 Caracter de la esquina inferiro izquierda del tablero.
*@param charCorner4 Carcter de la esquina inferiro derecha del tablero.
*/
void drawLimits(char charHorizontal,char charVertical, char charCorner1, char charCorner2, char charCorner3, char charCorner4);
/**
* @brief Método que regresa el largo del tablero.
* @return Largo del tablero.
*/
int getWidth();
/**
* @brief Método que regresa el alto de ltablero.
* @return Alto del tablero.
*/
int getTall();
/**
* @brief Método que ejecuta funciones de rutina, con paramtros base.
*/
void init();
};
class mTerminal : public EGE::CORE::Manager<Terminal>{
private:
/**Bandera que indica si ya se creo la terminal*/
bool isCreated = false;
public:
/**
* @brief Método encargado de agregar una terminal al manager.
* @param x Posición en x de la terminal.
* @param y Posición en y de la terminal.
* @return Identificador de la terminal.
*/
EGE::CORE::EntityId addEntity(int x, int y);
/**
* @brief Método encargado de inicializr una terminal por default.
* @param id Identificador de la terminal.
*/
void terminalDefault(EGE::CORE::EntityId id);
/**
* @brief Método encargado de de inicializar una terminal que se puede personalizar los limites.
* @param id Identificador de la terminal.
* @param charHorizontal Caracter de las lineas horizontales del tablero.
* @param charVertical Caracter de las lineas verticales del tablero.
* @param charCorner1 Caracter de la esquina superior izquierda del tablero.
* @param charCorner2 Caracter de la esquina superior derecha del tablero.
* @param charCorner3 Caracter de la esquina inferiro izquierda del tablero.
* @param charCorner4 Carcter de la esquina inferiro derecha del tablero.
*/
void terminalPersonalized(EGE::CORE::EntityId id,char charHorizontal = 205,char charVertical = 186, char charCorner1 = 201, char charCorner2 = 187, char charCorner3 = 200, char charCorner4 = 188);
/**
* @brief Método encargado de definir el color de los limites y del fondo de la terminal.
* @param id Identificador de la terminal.
* @param color Color de los limites y de la terminal.
*/
void terminalSetColor(EGE::CORE::EntityId id, unsigned short color);
};
}
#endif | true |
ed93e6cf48011971fdb93a0f9b6962740affd308 | C++ | szigetigabor/Arduino | /GardenWatering/MCPManagement.h | UTF-8 | 1,326 | 2.59375 | 3 | [] | no_license |
#ifndef _McpManagement_h
#define _McpManagement_h
#include "Adafruit_MCP23017.h"
#define NR_OF_PORTS 8
/*
* MCP23017 management class
* MCP ports are mapped the following rules:
* 0-7. ports: input
* 8-15. ports: output
*
* When i. input port is triggered (move to LOW) it triggers the i. output (i+8. MCP) port to change state.
*
*/
class MCPManagement {
public:
/**
* Construct MCP management.
*/
MCPManagement(int I2CAddr=0); //I2C address is between 0 and 7
void buttonPushTriggerCheck();
bool getInput(int port);
bool getOutput(int port);
void setOutput(int port, bool value);
String getIdentifier(int port);
void setIdentifier(int port, String value);
void setIdentifier(String value[NR_OF_PORTS]);
protected:
void oneButtonCheck(int port);
void printDebugMessage(int port, bool isInput, String ExtraText="");
//private:
Adafruit_MCP23017 mcp;
int mI2CAddr;
bool zoneInput[NR_OF_PORTS];
bool zoneOutput[NR_OF_PORTS];
String identifier[NR_OF_PORTS];
};
class MCPMomentaryManagement: public MCPManagement {
public:
/**
* Construct MCP management.
*/
MCPMomentaryManagement(int I2CAddr=0); //I2C address is between 0 and 7
void setOutput(int port, bool value);
};
#endif // _McpManagement_h
| true |
d75bc4ec10e07c022d344c01883ba098e31fc44d | C++ | philbarbier/arduino-projects | /flimrail_switch_control/flimrail_switch_control.ino | UTF-8 | 2,953 | 2.984375 | 3 | [] | no_license | /*
* Flimrail switch control software
*
* v 0.1 - (c)2016 Phil Barbier / Flimflam
*
*/
#include <Switch.h>
const int numSwitches = 2;
// switches that work as pairs (ie: crossovers)
const int switchPairs[1][2] = {
{0,1}
};
/*
* Have custom header for switch object .h and .cpp, has functions to makeTurn/Straight given a switch ID.
*
* switch has following constants:
* - maxNumSwitches
*
* switch has following properties:
* - servoMovement
* - inputPin
* - outputPin
* - id
* - location?
* - switchType - was intended to identify differences in switches for servo movement
* - not necessary anymore since switchData contains the servo movement value
* - defaultDirection (straight / turned)
*
* switch has following methods
* - makeTurn
* - makeStraight
*
* When instantiating switch object in control software below:
* - need to dynamically assign the pins to each switch
* - need to define pins and servo movement
*
*
*/
int switchState = 0;
int die = 0;
// for now have this shit in here, eventually move to SD card + csv
/*
* switchData definition
* array(switchId, servoMovement, inputPin, outputPin, defaultDirection - 0=straight, 1=turn, isPair - 0=no, 1=yes)
*
*/
int switchData[8][6] = {
{0, 25, 2, 27, 0, 1}, // inner->outer loop north side
{1, 25, 3, 28, 0, 1}, // outer->inner loop north side
{2, 25, 4, 29, 0, 1}, // outer->inner loop south side
{3, 25, 5, 30, 0, 1}, // inner->outer loop south side
{4, 25, 6, 31, 0, 0}, // outer->upper
{5, 25, 7, 32, 0, 0}, // inner->passing track south side
{6, 25, 8, 33, 0, 0}, // inner->passing track north side
{7, 25, 9, 34, 1, 0} // upper line escape track switch
};
Switch switches(numSwitches);
void setup() {
Serial.begin(9600);
for (int i=0; i < numSwitches; i++) {
pinMode(switchData[i][2], INPUT);
switches.attachServo(switchData[i][0], switchData[i][3]);
}
delay(500);
//exit(0);
}
void loop() {
for (int i=0; i < numSwitches; i++) {
// scan for inputs
switchState = digitalRead(switchData[i][2]);
int pairId = checkIsPair(switchData[i][0]);
Serial.println("Pair:");
Serial.println(pairId);
if (switchState == HIGH) {
switches.makeTurn(switchData[i][0], switchData[i][1]);
if (pairId > 0) {
switches.makeTurn(pairId, switchData[pairId][1]);
}
} else {
switches.makeStraight(switchData[i][0]);
if (pairId > 0) {
switches.makeStraight(pairId);
}
}
delay(1);
}
delay(250);
if (die > 250) {
Serial.println("End");
delay(5);
exit(0);
}
die++;
}
int checkIsPair(int switchId) {
for (int i=0; i < sizeof(switchPairs); i++) {
for (int j=0; j < sizeof(switchPairs[i]); j++) {
if (switchPairs[i][j] == switchId) {
if (j == 0) {
return switchPairs[i][1];
} else {
return switchPairs[i][0];
}
}
}
}
return 0;
}
| true |
16ee72da4adbe52b5fed2f7d8baa16e38e081bec | C++ | tejas01101001/Competitive-coding | /Graphs/Eulerian/hierholzers-algorithm.cpp | UTF-8 | 1,455 | 3.015625 | 3 | [] | no_license | //Eulerian cycle
const int N = 2e5 + 5;
list<int>adj[N];
int deg[N];
bool vis[N];
int cnt = 0;
stack<int>head,tail;
void dfs(int s)
{
vis[s] = true;
cnt++;
for (auto u : adj[s])
{
if (vis[u])
continue;
dfs(u);
}
}
int main()
{
int n, m, x, y;
cin >> n >> m;
forz(i,m)
{
cin >> x >> y;
adj[x].pb(y);
adj[y].pb(x);
++deg[x];
++deg[y];
}
int f = 1;
for (int i = 1; i <= n; i++)
{
if (int(adj[i].size()) == 0)
cnt++;
if (int(adj[i].size()) % 2)
f = 0;
}
dfs(1);
if (cnt != n || f == 0)
{
//Eulerian Cycle Exsists only if graph is connected
//Nodes with zero degree maynnot be in the component
//and all nodes have even degrees
cout << "IMPOSSIBLE";
return 0;
}
head.push(1);
while (!head.empty())
{
while (deg[head.top()])
{
int v = adj[head.top()].back();
adj[head.top()].pop_back();
adj[v].remove(head.top());
--deg[head.top()];
head.push(v);
--deg[v];
}
while (!head.empty() && !deg[head.top()])
{
tail.push(head.top());
head.pop();
}
}
while (!tail.empty())
{
cout << tail.top() << " ";
tail.pop();
}
run_time();
return 0;
} | true |
73bd50a8fa70e5a58d9712cfd922153d432dfd66 | C++ | andrewmashhadi/Advanced_Programming | /HW2/Charts.h | UTF-8 | 3,490 | 3.71875 | 4 | [] | no_license | /*
Andrew Mashhadi
ID: 905092387
PIC 10C
Programming Homework #2
Honor Pledge:
I pledge that I have neither given nor received
unauthorized assistance on this assignment.
*/
#ifndef CHARTS_H
#define CHARTS_H
#include <iostream>
#include <vector>
class Chart
{
public:
class Iterator
{
private:
size_t position;
const Chart* in_chart;
public:
/* Default constructor for nested Iterator class. Sets member variable position to 0 and
member variable in_chart to nullptr.
*/
Iterator();
/* Constructor with parameters for nested Iterator class.
@param p is what the member variable position will be set to
@param i is what the member variable in_chart will be pointing to
*/
Iterator(size_t p, const Chart* i);
/* Overloaded prefix increment operator for this nested Iterator. Increments the position member
variable.
@return a reference to this recently updated Iterator object.
*/
Iterator& operator++();
/* Overloaded postfix increment operator for this nested Iterator. Increments the position member
variable.
@param dummy int variable to specify that this increment operator is postfix.
@return a copy of this Iterator object before having position incremented.
*/
Iterator operator++(int dummy);
/* Overloaded equals to operator to return true if this Iterator's position variable is the same
as the right Iterators.
@param right is the right Iterator we are comparing this Iterator object to.
@return true if this is Iterator's position variable is the same as the right Iterator's. False otherwise
*/
bool operator==(const Iterator& right) const;
/* Overloaded not equals to operator to return true if this is Iterator's position variable is not the same
as the right Iterators.
@param right is the right Iterator we are comparing this Iterator object to.
@return true if this is Iterator's position variable is not the same as the right Iterator's. False otherwise
*/
bool operator!=(const Iterator& right) const;
/* Overloaded de-referenceing operator to access the data from the Chart this Iterator is refering to.
@return the data this Iterator is refering to, which is from the vector within the Chart that in_char is pointing at.
*/
int operator*() const;
};
/* Adds an item to the chart.
@param item to add.
@return void.
*/
void add(int item);
/* This function is a function meant to be redefined in the derived class to visually display the data
in the chart, but will only display a statement saying it cannot draw the data in this base class.
@retun void.
*/
virtual void draw() const;
/* First item of the chart.
*/
Iterator begin() const;
/* Last item of the chart.
*/
Iterator end() const;
virtual ~Chart();
protected:
std::vector<int> data;
};
class BarChart : public Chart
{
public:
/* This function redefines the draw function from base class Chart. It is used to visually display
the data in the base class's protected vector of ints, data.
@retun void.
*/
virtual void draw() const;
};
#endif
| true |
a00bad2f2a2d9b4cba02b7e3ac252fb35be4053e | C++ | nickLehr/CardinalNick_CSC17a_43950 | /Projects/Project 2/CSC17A_Project2/Deck.h | UTF-8 | 538 | 2.828125 | 3 | [] | no_license | /*
* File: Deck.h
* Author: Owner
*
* Created on May 27, 2015, 10:35 AM
*/
#ifndef DECK_H
#define DECK_H
#include "Card.h"
#include <string>
class Deck{
private:
Card *gameDeck;
void createDeck(std::string);
void addWilds();
int size;
public:
Deck();
//Copy constructor.
Deck(Deck&);
virtual ~Deck();
void setUp();
void setUpHand();
void shuffleDeck();
void outputDeck();
virtual Card draw();
};
#endif /* DECK_H */
| true |
3bd85f46e1d5927db394ec117290b79000310fc3 | C++ | ILyoan/MySnippets | /problem-solving/acmicpc.net/2294.cpp | UTF-8 | 771 | 2.546875 | 3 | [] | no_license | // baekjoon online judge 2294 (www.acmicpc.net/problem/2294)
// Category: DP
// Difficulty: Easy
#include <stdio.h>
const int MAX_N = 100;
const int MAX_K = 10000;
int N, K;
int coin[MAX_N + 1];
int mem[MAX_K + 1];
int main() {
scanf("%d%d", &N, &K);
for (int i = 0; i <= K; ++i) {
mem[i] = -1;
}
for (int i = 0; i < N; ++i) {
scanf("%d", &coin[i]);
}
mem[0] = 0;
for (int to = 1; to <= K; ++to) {
for (int i = 0; i < N; ++i) {
int from = to - coin[i];
if (from >= 0 && mem[from] != -1) {
if (mem[to] == -1 || mem[to] > mem[from] + 1) {
mem[to] = mem[from] + 1;
}
}
}
}
printf("%d\n", mem[K]);
return 0;
}
| true |
2fa444d8ff7cc9a4d9343c01aaf88e3109497106 | C++ | billpwchan/COMP-2011-Programs | /Program-14/Temperature/temperature_test.cpp | UTF-8 | 583 | 3.65625 | 4 | [] | no_license | #include "temperature.h" /* File: temperature_test.cpp */
int main()
{
char scale;
double degree;
temperature x; // Use default constructor
x.print( ); cout << endl; // Check the default values
cout << "Enter temperature (e.g., 98.6 F): ";
while (cin >> degree >> scale)
{
x.set(degree, scale);
x.fahrenheit(); x.print(); cout << endl;// Convert to Fahrenheit
x.celsius(); x.print(); cout << endl; // Convert to Celsius
cout << endl << "Enter temperature (e.g., 98.6 F): ";
};
return 0;
}
| true |
b720091d470e95ff6c082266ec575daf5cec0ff6 | C++ | JJungwoo/algorithm | /baekjoon/math1/1929.cpp | UHC | 559 | 3.390625 | 3 | [] | no_license | /*
[BOJ] 1929. Ҽ ϱ
https://www.acmicpc.net/problem/1929
*
#include <iostream>
using namespace std;
int factor[1000001];
void eratosthenes(int n) {
factor[0] = factor[1] = -1;
for (int i = 2; i <= n; ++i)
factor[i] = i;
int sqrtn = int(sqrt(n));
for (int i = 2; i <= sqrtn; ++i) {
if (factor[i] == i) {
for (int j = i*i; j <= n; j += i)
if (factor[j] == j)
factor[j] = i;
}
}
}
int main()
{
int m, n;
scanf("%d %d", &m, &n);
eratosthenes(n);
for (int i = m; i < n; i++)
printf("%d\n", factor[i]);
return 0;
}
*/ | true |
31546286d8d4d16f4f6ed55ca35d225e1a3c0b1d | C++ | JanaSabuj/Light-OJ | /Graph Theory/1040 - Donation.cpp | UTF-8 | 1,895 | 2.578125 | 3 | [] | no_license | //Built by Sabuj Jana(greenindia) from Jadavpur University,Kolkata,India
//God is Great
#include <bits/stdc++.h>
using namespace std;
#define crap ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define endl "\n"
#define int long long int
const int INF = 1e9 + 5; //billion
#define pb push_back
#define mp make_pair
#define MAX 53
int id[MAX];
int n;
void initialize() {
for (int i = 0; i < MAX; ++i)
{
/* code */
id[i] = i;
}
}
int root(int x) {
while (id[x] != x) {
id[x] = id[id[x]];
x = id[x];
}
return x;
}
void union1(int x, int y) {
id[root(x)] = id[root(y)];
}
int kruskal(vector< pair<int, pair<int, int>>> g ) {
sort(g.begin(), g.end());
initialize( );
int x, y, wt, mc = 0, line = 0;
for (auto edg : g) {
wt = edg.first;
x = edg.second.first;
y = edg.second.second;
if (root(x ) != root(y )) {
mc += wt;
union1(x, y );
line++;
}
}
if (line == n - 1)
return mc;
else
return -1;
}
signed main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
freopen("error.txt", "w", stderr);
crap;
int t;
cin >> t;
int tc = 0;
while (t--) {
n = 0;
cin >> n;
int cost = 0, totalcost = 0;
std::vector<pair<int, pair<int, int>>> g;
for (int i = 0; i < n; ++i)
{
/* code */
for (int j = 0; j < n; j++) {
int x;
cin >> x;
if (i == j) cost += x;
else {
if (x != 0) {
g.pb({x, {i, j}});
totalcost += x;
}
}
}
}
int val = kruskal(g);
if (val != -1)
{ cost += totalcost - val;
cout << "Case " << ++tc << ":" << " " << cost << endl;
}
else {
cout << "Case " << ++tc << ":" << " " << -1 << endl;
}
}
//end of while
return 0;
}
| true |
eb513ce2d86f4baa23b69f624ecae3d934221bd5 | C++ | hailingu/leet_lint_code | /leet_lint_code/lint_code/binary_tree_level_order_traversal_ii.cpp | UTF-8 | 1,161 | 2.890625 | 3 | [] | no_license | // Copyright © 2018 Hailin Gu. All rights reserved.
// License(GPL)
// Author: Hailin Gu
// This is a answer of lint code problem 70.
#ifndef LEETLINTCODE_LINTCODE_BINARYTREELEVELORDERTRAVERSALII_CPP
#define LEETLINTCODE_LINTCODE_BINARYTREELEVELORDERTRAVERSALII_CPP
#include <queue>
#include <vector>
#include <math.h>
#include <algorithm>
class TreeNode {
public:
TreeNode(int val) {
this->val = val;
this->left = this->right = NULL;
}
int val;
TreeNode *left, *right;
};
class BinaryTreeLevelOrderTraversalII {
public:
std::vector<std::vector<int>> levelOrderBottom(TreeNode* root) {
std::vector<std::vector<int>> v;
levelOrderHelp(root, v, 0);
std::reverse(v.begin(), v.end());
return v;
}
void levelOrderHelp(TreeNode* root, std::vector<std::vector<int>> &v, int level) {
if (NULL == root) return ;
int len = (int) v.size();
if (len - 1 < level) v.push_back(std::vector<int>());
v[level].push_back(root->val);
levelOrderHelp(root->left, v, level + 1);
levelOrderHelp(root->right, v, level + 1);
}
};
#endif // LEETLINTCODE_LINTCODE_BINARYTREELEVELORDERTRAVERSALII_CPP
| true |
93985da8f15b1b6271fe2d15eddea6c26e785e9c | C++ | kgandhi09/C-Cpp | /Shape/src/main.cpp | UTF-8 | 1,912 | 3.703125 | 4 | [] | no_license | /*
* main.cpp
*
* Created on: Nov 21, 2019
* Author: kushal
*/
#include <string>
#include <stdlib.h>
#include <stdbool.h>
#include <iostream>
using namespace std;
class Shape{
protected:
string name;
public:
Shape(string n){
name = n;
}
//virtual ~Shape() = 0;
void setName(string n){
name = n;
}
string getName() {
return name;
}
// pure virtual function
virtual double getArea() = 0;
};
class Circle : public Shape{
double radius;
public:
Circle(string name, double r) : Shape(name){
radius = r;
}
//~Circle();
void setRadius(double r){
radius = r;
}
double getRadius(){
return radius;
}
virtual double getArea(){
return 3.1415*radius*radius;
}
};
class Rectangle : public Shape{
protected:
double base, width;
public:
Rectangle(string n, double b, double w) : Shape(n){
base = b;
width = w;
}
//~Rectangle(){};
void setBase(double b){
base = b;
}
double getBase(){
return base;
}
void setWidth(double w){
width = w;
}
double getWidth(){
return width;
}
virtual double getArea(){
return base*width;
}
};
class Triangle : public Shape{
protected:
double base, width;
public:
Triangle(string n, double b, double w) : Shape(n){
base = b;
width = w;
}
//~Triangle(){}
virtual double getArea(){
return 0.5*base*width;
}
};
int main(int argc, char** argv){
Circle* c = new Circle("circle", 3.6);
cout << c->getName() << endl;
cout << c->getRadius() << endl;
Rectangle* r = new Rectangle("rect", 5, 10);
cout << r->getName()<< endl;
cout << r->getBase() << endl;
cout << r->getWidth() << endl;
r->setBase(10);
r->setWidth(5);
cout << r->getBase() << endl;
cout << r->getWidth() << endl;
Triangle* t = new Triangle("triangle", 3,4);
Shape* shapes[3] = {c,r,t};
for(int i = 0; i< 3; i++){
cout << "Shape : " << shapes[i]->getName() << " Area : " << shapes[i]->getArea() << endl;
}
}
| true |
d475f61da2c92b272907a8f3a81adcfe75c181eb | C++ | Pragad/LearnCpp | /ThreadsMutex.cpp | UTF-8 | 5,523 | 3.90625 | 4 | [] | no_license | #include <iostream>
#include <thread>
#include <mutex>
#include <vector>
using namespace std;
// -----------------------------------------------------------------------------------------
// PROBLEM 1. Increment a value using mutex
// -----------------------------------------------------------------------------------------
// A Global variable x that will be shared by the threads
uint32_t x = 0;
void incrementX()
{
for (uint32_t i = 0; i < 100; i++)
{
x = x + 1;
}
}
mutex mtx2;
void incrementXMtx()
{
// With unique_lock, we don't have to manually unlock. When the function goes out of scope
// automatic unlock of the mutex happens
unique_lock<mutex> lock(mtx2);
for (uint32_t i = 0; i < 100; i++)
{
x = x + 1;
}
}
// -----------------------------------------------------------------------------------------
// PROBLEM 2. Print Chars using Mutex
//
// Race Condition Here.
// We can't predict the order of execution.
// The order of execution depends on thread scheduling algorithm
// Multiple Runs of the same program will give different output
// -----------------------------------------------------------------------------------------
void printChars(uint32_t num, char ch)
{
for (uint32_t i = 0; i < num; i++)
{
cout << ch << " ";
}
cout << endl;
}
// With Mutex to protect the critical section
// Declare a mutex variable
mutex mtx;
void printCharsMutex(uint32_t num, char ch)
{
unique_lock<mutex> lock(mtx);
for (uint32_t i = 0; i < num; i++)
{
cout << ch << " ";
}
cout << endl;
}
// -----------------------------------------------------------------------------------------
// PROBLEM 3. Another example of Mutex, Unique_lock
// http://baptiste-wicht.com/posts/2012/03/cp11-concurrency-tutorial-part-2-protect-shared-data.html
// -----------------------------------------------------------------------------------------
class PersonCountNoMtx
{
public:
int _value;
PersonCountNoMtx() : _value(0) { }
void increment()
{
_value++;
}
};
class PersonCountWithMtx
{
public:
std::mutex mtx;
int _value;
PersonCountWithMtx() : _value(0) { }
void increment()
{
mtx.lock();
_value++; // IMP: If Exception happens and we crash then the lock does not get released
mtx.unlock();
}
};
class PersonCountUniqLock
{
public:
std::mutex mtx;
int _value;
PersonCountUniqLock() : _value(0) { }
void increment()
{
unique_lock<mutex> uniqLock(mtx); // Unlock gets called when we go out of scope
_value++;
}
};
// -----------------------------------------------------------------------------------------
// Main Function
// -----------------------------------------------------------------------------------------
int main()
{
// Example 1
{
cout << endl << "Problem 1" << endl;
x = 0;
thread th5 (incrementX);
thread th6 (incrementX);
th5.join();
th6.join();
cout << "Without Mutex X Val: " << x << endl;
x = 0;
thread th7 (incrementXMtx);
thread th8 (incrementXMtx);
th7.join();
th8.join();
cout << "With Mutex X Val: " << x << endl;
}
// Example 2
{
cout << endl << "Problem 2" << endl;
cout << "Without Mutex" << endl;
thread th1 (printChars, 10, '*');
thread th2 (printChars, 10, '$');
th1.join();
th2.join();
cout << "With Mutex" << endl;
thread th3 (printCharsMutex, 10, '*');
thread th4 (printCharsMutex, 10, '$');
// Main will wait for the threads to finish execution before continuing its work
th3.join();
th4.join();
}
// PROBLEM 3. Another example of Mutex, Unique_lock
{
cout << endl << "Problem 3" << endl;
PersonCountNoMtx ob1;
vector<thread> vecThreads1;
for (uint32_t i = 0; i < 3; i++)
{
// Different ways to create a thread for a Class's member function
//thread th1(&PersonCountNoMtx::increment, PersonCountNoMtx());
//thread th2(&PersonCountNoMtx::increment, &ob1);
vecThreads1.push_back(thread(&PersonCountNoMtx::increment, &ob1));
for (uint32_t j = 0; j < 5; j++)
{
ob1.increment();
}
}
for (auto& th : vecThreads1)
{
th.join();
}
cout << "Thread 1's Value: " << ob1._value << endl;
PersonCountWithMtx ob2;
vector<thread> vecThreads2;
for (uint32_t i = 0; i < 3; i++)
{
vecThreads2.push_back(thread(&PersonCountNoMtx::increment, &ob1));
for (uint32_t j = 0; j < 5; j++)
{
ob2.increment();
}
}
for (auto& th : vecThreads2)
{
th.join();
}
cout << "Thread 2's Value: " << ob2._value << endl;
PersonCountUniqLock ob3;
vector<thread> vecThreads3;
for (uint32_t i = 0; i < 3; i++)
{
vecThreads3.push_back(thread(&PersonCountNoMtx::increment, &ob1));
for (uint32_t j = 0; j < 5; j++)
{
ob3.increment();
}
}
for (auto& th : vecThreads3)
{
th.join();
}
cout << "Thread 3's Value: " << ob3._value << endl;
}
cout << endl;
return 0;
}
| true |
cfabbb68b6d181db72203f0de8587f6d3dab7135 | C++ | salvomob/Esercitazioni_Prog2 | /14_05_2021/classe.h | UTF-8 | 274 | 2.5625 | 3 | [] | no_license | #ifndef CLASSE_H
#define CLASSE_H
#include<iostream>
class Classe{
private:
Studente **studenti;
int n;//numero massimo studenti in classe
int myn;//numero effettivo studenti in classe
public:
Classe(int n);
void setStudente(Studente& s);
void show();
};
#endif
| true |
0742ee3b722dcecdd019833de6eaef5c54db9875 | C++ | sagar-sam/Spoj-Solutions | /gopuDigitDiv.cpp | UTF-8 | 504 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
long long int n;
scanf("%lld",&n);
long long int sum=0;
long long int m=n;
for(int i=1;i<=n;i=i*10)
{
sum=sum+m%10;
m=m/10;
}
while(true)
{
if(n%sum==0)
break;
else
{
if(n%10==0)
{
long long int m=n;
while(m%10==9)
{
sum=sum-9;
m=m/10;
}
}
n++;
sum++;
}
}
printf("%lld\n",n);
}
return 0;
}
| true |
fa5b67e09da189f1ebf0e540dfa26269b14c2388 | C++ | Thibaut34/TP1_CPP | /chambre.cpp | UTF-8 | 1,066 | 3 | 3 | [] | no_license | #include "chambre.h"
#include<string>
#include "date.h"
#include <iostream>
Chambre :: Chambre(int identifiant, std::string type ,double prix){
_identifiant=identifiant;
_type=type;
_prix=prix;
}
int Chambre::getidentifiant() const{
return _identifiant;
}
std ::string Chambre::gettype() const{
return _type;
}
double Chambre::getprix() const{
return _prix;
}
void Chambre::setidentifiant(int identifiant){
_identifiant=identifiant;
}
void Chambre::settype(std::string type){
_type=type;
}
void Chambre::setprix(double prix){
_prix=prix;
}
void Chambre::setchambre(int identifiant ,std::string type , double prix){
Chambre::setidentifiant(identifiant);
Chambre::settype(type);
Chambre::setprix(prix);
}
Chambre ::~Chambre(){
//std::cout << " Destructor: " << _identifiant << "/" << _type << "/" << _prix << '\n';
}
std::ostream& operator<<(std::ostream& os, const Chambre chambre){
os<< chambre.getidentifiant() << "/" << chambre.gettype() << "/" << chambre.getprix() << "\n" ;
return os;
}
| true |
c932fdfe404d3dfb4282c234fdc5d40e09ccb10e | C++ | beatalochowska/programs | /przyjaciele/main.cpp | WINDOWS-1250 | 741 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include "przyjaciele.h"
using namespace std;
void judge(Point pkt, Rectangle p)
{
if((pkt.x >= p.x) && (pkt.x <= p.x + p.width) && (pkt.y >= p.y) && (pkt.y <= p.y + p.height))
cout << endl << "Punkt " << pkt.name << " nalezy do prostokata: " << p.name;
else
cout << endl << "Punkt " << pkt.name << " lezy poza prostokatem: " << p.name;
}
int main()
{
cout << "Zdefiniuj punkt i prostokt i sprawdz czy punkt zawiera sie w prostokacie." << endl;
cout << "--------------------------------------------------------------------------" <<endl;
Point pkt1("A", 3, 17);
Rectangle p1("prostokat", 0, 0, 6, 4);
pkt1.load();
p1.load();
judge (pkt1, p1);
return 0;
}
| true |
737efe09e14ba01e09737d2b8af4a8e7458a4647 | C++ | vukics/cppqed | /CPPQEDcore/structure/Liouvillean.h | UTF-8 | 6,404 | 2.859375 | 3 | [
"BSL-1.0"
] | permissive | // Copyright András Vukics 2006–2022. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)
/// \briefFileDefault
#ifndef CPPQEDCORE_STRUCTURE_LIOUVILLEAN_H_INCLUDED
#define CPPQEDCORE_STRUCTURE_LIOUVILLEAN_H_INCLUDED
#include "LiouvilleanAveragedCommon.h"
#include "TimeDependence.h"
#include "LazyDensityOperator.h"
#include "StateVector.h"
namespace structure {
struct SuperoperatorNotImplementedException
{
explicit SuperoperatorNotImplementedException(size_t m) : m_(m) {}
size_t m_;
};
/// The interface every system having Liouvillean time-evolution must present towards the trajectory drivers
/**
* The time-evolution must be Markovian where the Lindblad form of the Master equation is the most general one possible:
* \f[\dot\rho=\frac1{i\hbar}\comm{H}\rho+\sum_m\lp J_m\rho J_m^\dag-\frac12\comm{J_m^\dag J_m}{\rho}_+\rp\f]
* The class represents the set of \f$J_m\f$ operators (Lindblads or quantum jump operators) of arbitrary number,
* either for Master equation or Monte Carlo wave-function evolution (in the latter case it calculates the jump rates as well).
*
* \tparamRANK
*
* \note No matter how complex the quantum system, the framework always assigns a unique ordinal to each jump corresponding to every subsystem
*
* \note It is always possible to forgo the explicit calculation of certain jump rates because the rate can be calculated also on the basis of the Liouvillean::actWithJ function by the
* \link quantumtrajectory::MCWF_Trajectory MCWF stepper\endlink. The fact that such a fallback is desired can be signalled by setting a negative value for the rate of the given jump
* (“special jump”). \see \ref specialjump
*
* \see The design is very similar to Exact, but here the choice is not between TwoTime/OneTime dependence, but OneTime/NoTime.
*
*/
template<int RANK>
class Liouvillean : public LiouvilleanAveragedCommonRanked<RANK>
{
public:
static const int N_RANK=RANK;
private:
typedef LiouvilleanAveragedCommonRanked<RANK> Base;
public:
virtual ~Liouvillean() {}
/// Returns the set of jump rates \f$\bra{\Psi}J_m^\dagger J_m\ket{\Psi},\f$ where the Lindblads are in general time-dependent
/** Simply redirects to LiouvilleanAveragedCommonRanked::average, so that this function does not appear in the interface for implementers. */
const Rates rates(double t, const quantumdata::StateVector<RANK>& psi) const {return Base::average(t,psi);}
/// Performs the quantum jump operation \f$\ket\Psi\rightarrow J_m(t)\ket\Psi\f$
void actWithJ(double t, ///<[in] \f$t\f$
StateVectorLow<RANK>& psi, ///<[in/out] \f$\ket\Psi\f$
size_t m ///<[out] \f$m\f$
) const {return actWithJ_v(t,psi,m);}
/// Calculates \f$\Lcal\rho=J_m(t)\rho J_m(t)^\dagger\f$ and adds it to `drhodt`
void actWithSuperoperator(double t, ///<[in] time
const DensityOperatorLow<RANK>& rho, ///<[in] density operator
DensityOperatorLow<RANK>& drhodt, ///<[in/out] density operator
size_t m ///<[in] ordinal of jump operator
) const {actWithSuperoperator_v(t,rho,drhodt,m);}
private:
virtual void actWithJ_v(double, StateVectorLow<RANK>&, size_t) const = 0;
virtual void actWithSuperoperator_v(double, const DensityOperatorLow<RANK>&, DensityOperatorLow<RANK>&, size_t m) const {throw SuperoperatorNotImplementedException(m);}
};
template <int RANK>
using LiouvilleanPtr=std::shared_ptr<const Liouvillean<RANK>>;
/// Implements the general Liouvillean interface by dispatching the two possible \link time::DispatcherIsTimeDependent time-dependence levels\endlink
/**
* \tparamRANK
* \tparam IS_TIME_DEPENDENT describes whether the \f$J_m\f$s are time-dependent. `true`: OneTime – `false`: NoTime
*
*/
template<int RANK, bool IS_TIME_DEPENDENT>
class LiouvilleanTimeDependenceDispatched : public Liouvillean<RANK>
{
public:
typedef time::DispatcherIsTimeDependent_t<IS_TIME_DEPENDENT> Time;
private:
void actWithJ_v(double t, StateVectorLow<RANK>& psi, size_t lindbladNo) const final {actWithJ_v(Time(t),psi,lindbladNo);} ///< Redirects the virtual inherited from Liouvillean<RANK>
const Rates average_v(double t, const quantumdata::LazyDensityOperator<RANK>& matrix) const final {return rates_v(Time(t),matrix);} ///< Redirects the virtual inherited from LiouvilleanAveragedCommonRanked
void actWithSuperoperator_v(double t, const DensityOperatorLow<RANK>& rho, DensityOperatorLow<RANK>& drhodt, size_t m) const final {actWithSuperoperator_v(Time(t),rho,drhodt,m);}
virtual void actWithJ_v(Time, StateVectorLow<RANK>&, size_t ) const = 0;
virtual const Rates rates_v(Time, const quantumdata::LazyDensityOperator<RANK>&) const = 0;
virtual void actWithSuperoperator_v(Time, const DensityOperatorLow<RANK>&, DensityOperatorLow<RANK>&, size_t m) const {throw SuperoperatorNotImplementedException(m);}
};
/** \page specialjump The notion of “special jumps” in the framework
*
* Implementers of Liouvillean (typically, certain free elements) may decide to forgo the explicit calculation of the jump rate corresponding to any of the Lindblad operators,
* because the action of the Lindblad on a state vector contains enough information about the jump rate as well. This is signalled by a negative jump rate towards the framework.
*
* The motivation for this is usually that the explicit calculation of a given jump rate is cumbersome and error-prone in some cases.
*
* The quantumtrajectory::MCWF_trajectory class, when encountering a negative jump rate, will reach for the Liouvillean::actWithJ function to calculate the corresponding rate.
*
* Assume that \f$J_m\f$ is the set of Lindblads, and for \f$m=\text{at}\f$ the jump rate is found negative. In this case, \f$\ket{\Psi_\text{at}}=J_\text{at}\ket\Psi\f$ is
* calculated and cached by the trajectory driver (cf. quantumtrajectory::MCWF_trajectory::calculateSpecialRates) and the given jump rate is taken as \f$\norm{\ket{\Psi_\text{at}}}^2\f$.
*
* \note In certain cases, the use of a special jump can be less efficient than the explicit calculation of the rate.
*
*/
} // structure
#endif // CPPQEDCORE_STRUCTURE_LIOUVILLEAN_H_INCLUDED
| true |
fdb545018e1a532e56d7ae13f511ab107d872045 | C++ | joaosfvieira/list2 | /equal/include/equal.h | UTF-8 | 2,198 | 3.796875 | 4 | [] | no_license | #ifndef GRAAL_H
#define GRAAL_H
#include <utility>
using std::pair;
#include <iterator>
using std::distance;
#include <algorithm>
using std::sort;
namespace graal {
/*!
* @tparam InputIt1 iterator para o range.
* @tparam InputIt2 iterator para o segundo range.
* @tparam Equal para a função eq.
*
* @param first1 Ponteiro para o primeiro elemento do range
* @param last1 Ponteiro para a posição logo após o último elemento do range
* @param first2 Ponteiro para o primeiro elemento do segundo range
* @param eq Uma função que retorna true se o elemento é igual ao segundo, ou falso caso contrário. A assinatura da função de comparação deve ser bool eq( const Type &a, const Type &b)
*
* @return Retorna verdadeiro se os ranges são iguais, falso caso contrário
*
*/
template<class InputIt1, class InputIt2, class Equal>
bool equal(InputIt1 first1, InputIt1 last1, InputIt2 first2, Equal eq)
{
InputIt1 itf1 = first1, itl1 = last1;
InputIt2 itf2 = first2;
while(itf1 != itl1){
if(eq(*itf1, *itf2)==0){
return false;
}
++itf1;
++itf2;
}
return true;
}
/*!
* @tparam InputIt1 iterator para o range.
* @tparam InputIt2 iterator para o segundo range.
* @tparam Equal para a função eq.
*
* @param first1 Ponteiro para o primeiro elemento do range
* @param last1 Ponteiro para a posição logo após o último elemento do range
* @param first2 Ponteiro para o primeiro elemento do segundo range
* @param last2 Ponteiro para a posição logo após o último elemento do segundo range
* @param eq Uma função que retorna true se o elemento é igual ao segundo, ou falso caso contrário. A assinatura da função de comparação deve ser bool eq( const Type &a, const Type &b)
*
* @return Retorna verdadeiro se os ranges são iguais, falso caso contrário
*
*/
template<class InputIt1, class InputIt2, class Equal>
bool equal(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,
Equal eq )
{
InputIt1 itf1 = first1, itl1 = last1;
InputIt2 itf2 = first2;
while(itf1 != itl1){
if(eq(*itf1, *itf2)==0){
return false;
}
++itf1;
++itf2;
}
return true;
}
}
#endif
| true |
db293ea056542876ba0ebc043df87ea47e3b44e7 | C++ | SubhradeepSS/dsa | /String/Find the diff.cpp | UTF-8 | 610 | 3.453125 | 3 | [] | no_license | /* Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:
s = "abcd"
t = "abcde"
Output:
e */
class Solution {
public:
char findTheDifference(string s, string t) {
int n=s.size();
vector<int> count(26,0);
for(char ch:s){
count[ch-'a']++;
}
for(char ch:t){
if(count[ch-'a']==0)
return ch;
count[ch-'a']--;
}
return 'a';
}
}; | true |
a28afb4c5fdb01c9a0c101fdf18bbd5665ed385c | C++ | nahueldefazio/tp2 | /lista.h | UTF-8 | 1,655 | 2.765625 | 3 | [] | no_license | //
// Created by SuckMyPocket on 17/11/2020.
//
#ifndef UNTITLED_LISTA_H
#define UNTITLED_LISTA_H
#include <string>
#include "nodo.h"
#include "lista.h"
#include "agua.h"
#include "aire.h"
#include "fuego.h"
#include "tierra.h"
using namespace std;
class Lista {
private:
Nodo* primero;
int cantidad; // largo de la lista
Nodo *obtener_nodo(int pos);
Nodo *actual;
public:
//Constructor
//Pos:Crea una lista
Lista();
//Pre: posicion > 0 posiscion >= cantidad +1
//Pos: inserta el dato d en la posicion pos, la pos 1 es la 1era
void alta(Dato d);
//Pre: 0 < posicion <= cantidad
//Pos: saca elelemento que esta en la posicion
void baja (int pos);
//Pre: 0 < posicion <= cantidad
//Pos: devuelve el dato que esta en la posicion
Dato consulta(int pos);
bool vacia();
//Destructor
//Pos: libera espacio en memoria
virtual ~Lista();
//Pos: devuelve la longuitud de la lista
int obtener_cantidad();
//Pos: pasa el nodo actual al primero (reinicia el nodo actual)
void reiniciar();
bool hay_siguiente();
//Pos: devuelve
Dato siguiente();
//Pos: vuelve la posicion de la lista en donde se encuentra ese "nombre"
int pos_nombre(string nombre);
//Pre: no hay nombres repetidos y el formato del archivo es el correcto
//Pos: lee los datos del archivo.csv
void leer_datos();
//Pos: hace la carga de datos ,mientras se lee el archivo
void cargar_datos(string elemento, string nombre, string escudo, string vida);
};
#endif //UNTITLED_LISTA_H
| true |
3d260aaae403d99202687046f848cbd201509ba5 | C++ | WeenyJY/year17 | /stage1/Cplusplus/Reference/Containers/common/common-print.hpp | UTF-8 | 710 | 3.28125 | 3 | [] | no_license | // file : common-print.hpp
#ifndef COMMON_PRINT_HPP
#define COMMON_PRINT_HPP
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <forward_list>
using namespace std;
template <class T>
void printInfo(string who, const vector<T>& myvector )
{
cout<<who<<" contains:";
for(auto & x : myvector)
cout<<"\t"<<x;
cout<<"\n";
}
template <class T>
void printInfo(string who, const list<T>& mylist)
{
cout<<who<<" contains:";
for(auto & x : mylist)
cout<<"\t"<<x;
cout<<"\n";
}
template <class T>
void printInfo(string who, const forward_list<T>& mylist)
{
cout<<who<<" contains:";
for(auto & x : mylist)
cout<<"\t"<<x;
cout<<"\n";
}
#endif /*COMMON_PRINT_HPP*/
| true |
a18df84d2d2dcc23aef420b677f3dcfb90da5360 | C++ | brighthush/code-store | /projects/text2vec/src/VocabWord.h | UTF-8 | 1,493 | 2.515625 | 3 | [] | no_license | /*************************************************************************
> File Name: VocabWord.h
> Author: bright
> Mail: luzihao@software.ict.ac.cn
> Created Time: Mon 05 Jan 2015 09:47:17 AM CST
************************************************************************/
#ifndef __VOCAB_WORD__H__
#define __VOCAB_WORD__H__
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "glMember.h"
class VocabWord
{
private:
long long cn; //occurrence count for a word
long long *point;
char *word, *code, codelen;
public:
VocabWord():cn(0), point(NULL), word(NULL), code(NULL), codelen(0) {}
bool operator<(const VocabWord &b) const
{
if(cn < b.cn) return false;
return true;
}
void set_cn(long long cn) { this->cn = cn; }
long long get_cn() { return cn; }
void set_word(char *word)
{
if(this->word!=NULL) free(this->word);
this->word = (char *)calloc(strlen(word)+1, sizeof(char));
strcpy(this->word, word);
}
char* get_word() { return word; }
LL* calloc_point() { point = (LL *)calloc(MAX_CODE_LENGTH, sizeof(LL)); return point; }
char* calloc_code() { code = (char *)calloc(MAX_CODE_LENGTH, sizeof(char)); return code; }
LL* get_point() { return point; }
char* get_code() { return code; }
void set_codelen(int codelen) { this->codelen = codelen; }
int get_codelen() { return codelen; }
VocabWord& operator++() { ++cn; return *this; }
};
#endif
| true |
df95ce207c096784614a7c3d58e7ddbe0f4120d9 | C++ | Solayman/Arduino | /2_led/2_led.ino | UTF-8 | 364 | 2.59375 | 3 | [] | no_license | #define led1 8
#define led2 9
void setup() {
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
}
void loop() {
//FOR FIRST LED
digitalWrite(led1,HIGH);
delay(2000);
digitalWrite(led1,LOW);
delay(3000);
//FOR SECOND LED
digitalWrite(led2,HIGH);
delay(2000);
digitalWrite(led2,LOW);
delay(3000);
}
| true |
e7874c1631fe401dd1ec476bae1e2f53600e2003 | C++ | eibow1012/quadruped_control | /quadruped_controller/include/quadruped_controller/math/numerics.hpp | UTF-8 | 1,463 | 3.296875 | 3 | [] | no_license | /**
* @file numerics.hpp
* @date 2021-03-12
* @author Boston Cleek
* @brief Numerical utility functions
*/
#ifndef NUMERICS_HPP
#define NUMERICS_HPP
// Linear Algebra
#include <armadillo>
namespace quadruped_controller
{
namespace math
{
using arma::vec;
using arma::vec3;
constexpr double PI = 3.14159265358979323846;
/**
* @brief approximately compare two floating-point numbers
* @param d1 - a number to compare
* @param d2 - a second number to compare
* @param epsilon - absolute threshold required for equality
* @return true if abs(d1 - d2) < epsilon
*/
bool almost_equal(double d1, double d2, double epsilon = 1.0e-12);
/**
* @brief Normalize angle [0 2PI)
* @param angle - radians
* @return normalized angle
*/
double normalize_angle_2PI(double angle);
/**
* @brief Normalize angle [0 PI)
* @param angle - radians
* @return normalized angle
*/
double normalize_angle_PI(double rad);
// /**
// * @brief Normalize angle [0 2PI)
// * @param angles - vector in radians
// * @return vector of normalized angles
// */
// vec normalize_angle_2PI(vec angles);
/**
* @brief Normalize angle [0 2PI)
* @param angles - vector in radians
* @return vector of normalized angles
*/
vec3 normalize_angle_2PI(vec3 angles);
/**
* @brief Normalize angle [0 PI)
* @param angles - vector in radians
* @return vector of normalized angles
*/
vec3 normalize_angle_PI(vec3 angles);
} // namespace math
} // namespace quadruped_controller
#endif
| true |
cb84639c8099b9ca8900ad285fa0aebc50220e14 | C++ | seshbot/new-cpp-project | /pcx/test/TestServiceRegistry.cpp | UTF-8 | 6,225 | 2.5625 | 3 | [] | no_license |
#include <boost/test/unit_test.hpp>
using namespace boost::unit_test;
#include <set>
#include <pcx/IndexPool.h>
#include <pcx/ServiceRegistry.h>
using namespace pcx;
BOOST_AUTO_TEST_SUITE( ServiceRegistrySuite )
BOOST_AUTO_TEST_CASE( overFillPool )
{
auto list = IndexPool(10);
long idx;
for (int i = 0; i < 10; i++)
{
idx = list.Allocate();
}
try
{
list.Allocate();
BOOST_CHECK( false );
}
catch (...)
{
}
list.Free(idx);
BOOST_CHECK(idx == list.Allocate());
}
BOOST_AUTO_TEST_CASE( reallocation )
{
auto list = IndexPool(10);
for (int i = 0; i < 10; i++)
{
list.Allocate();
}
std::set<long> indexes;
for (size_t i = 1; i < 10; i += 2)
{
indexes.insert(i);
}
std::for_each(indexes.begin(), indexes.end(), [&](long idx)
{
list.Free(idx);
});
std::set<long> remainingIndexes;
list.ForEach([&](long idx)
{
BOOST_CHECK(remainingIndexes.insert(idx).second);
});
BOOST_CHECK(10 == remainingIndexes.size() + indexes.size());
{
auto it = indexes.begin();
for (; it != indexes.end(); ++it)
{
BOOST_CHECK(remainingIndexes.find(*it) == remainingIndexes.end());
}
}
std::set<long> reallocIndexes;
for (size_t i = 0; i < indexes.size(); ++i)
{
reallocIndexes.insert(list.Allocate());
}
BOOST_CHECK(indexes.size() == reallocIndexes.size());
{
auto it1 = indexes.begin();
auto it2 = reallocIndexes.begin();
for (; it1 != indexes.end(); ++it1, ++it2)
{
BOOST_CHECK(*it1 == *it2);
}
}
}
BOOST_AUTO_TEST_CASE( ServiceRegistry_different_registration_types )
{
bool ptrDisposed = false;
bool refDisposed = false;
bool registeredDisposed = false;
struct MockService1
{
bool & disposeFlag_;
MockService1(bool& disposeFlag) : disposeFlag_(disposeFlag) { }
~MockService1() { disposeFlag_ = true; }
};
struct MockService2
{
bool & disposeFlag_;
MockService2(bool& disposeFlag) : disposeFlag_(disposeFlag) { }
~MockService2() { disposeFlag_ = true; }
};
struct MockService3
{
MockService3(ServiceRegistry& services) : disposeFlag_(nullptr) { }
~MockService3() { if (nullptr == disposeFlag_) throw std::exception(); *disposeFlag_ = true; }
bool * disposeFlag_;
void SetDisposeFlag(bool* disposeFlag) { disposeFlag_ = disposeFlag; }
};
MockService1 refService(refDisposed);
{
ServiceRegistry services;
services.add(refService);
services.add(std::unique_ptr<MockService2>(new MockService2(ptrDisposed)));
services.add<MockService3>();
services.find<MockService3>().SetDisposeFlag(®isteredDisposed);
// these should not throw
services.find<MockService2>();
services.find<MockService3>();
}
BOOST_CHECK(!refDisposed);
BOOST_CHECK(ptrDisposed);
BOOST_CHECK(registeredDisposed);
}
BOOST_AUTO_TEST_CASE( ServiceRegistry_simple )
{
struct MockService1 { };
struct MockService2 { MockService2(ServiceRegistry& services) { } };
struct MockService3 { MockService3(ServiceRegistry& services) { } };
struct MockService4 { MockService4(ServiceRegistry& services) { } };
ServiceRegistry services;
services.add<MockService2>().dependsOn<MockService1>();
services.add(std::unique_ptr<MockService1>(new MockService1()));
services.add<MockService3>().dependsOn<MockService1>();
services.add<MockService4>().dependsOn<MockService2>();
// should not throw
services.find<MockService1>();
services.find<MockService2>();
services.find<MockService3>();
services.find<MockService4>();
}
BOOST_AUTO_TEST_CASE( ServiceRegistry_dep_failure )
{
struct MockService1 { MockService1() { } };
struct MockService2 { MockService2(ServiceRegistry& services) { } };
struct MockService3 { MockService3(ServiceRegistry& services) { } };
ServiceRegistry services;
services.add<MockService2>().dependsOn<MockService1>();
try
{
// MockService1 dependency not yet satisfied
services.find<MockService2>();
BOOST_CHECK(false);
}
catch (...)
{
}
}
BOOST_AUTO_TEST_CASE( ServiceRegistry_dep_cycle )
{
struct MockService1 { MockService1(ServiceRegistry& services) { } };
struct MockService2 { MockService2(ServiceRegistry& services) { } };
struct MockService3 { MockService3(ServiceRegistry& services) { } };
ServiceRegistry services;
services.add<MockService2>().dependsOn<MockService1>();
services.add<MockService1>().dependsOn<MockService3>();
services.add<MockService3>().dependsOn<MockService2>();
try
{
// not yet registered
services.find<MockService1>();
BOOST_CHECK(false);
}
catch (...)
{
}
}
BOOST_AUTO_TEST_CASE( ServiceRegistry_dep_ordering )
{
static int counter = 0;
struct MockService2 { MockService2(ServiceRegistry& services)
{
BOOST_CHECK(++counter == 2);
}};
struct MockService5 { MockService5(ServiceRegistry& services)
{
BOOST_CHECK(++counter == 5);
}};
struct MockService1 { MockService1(ServiceRegistry& services)
{
BOOST_CHECK(++counter == 1);
}};
struct MockService4 { MockService4(ServiceRegistry& services)
{
BOOST_CHECK(++counter == 4);
}};
struct MockService3 { MockService3(ServiceRegistry& services)
{
BOOST_CHECK(++counter == 3);
}};
// deps 3->2->1 5->4
ServiceRegistry services;
services.add<MockService3>().dependsOn<MockService2>();
services.add<MockService2>().dependsOn<MockService1>();
services.add<MockService4>();
services.add<MockService1>();
services.add<MockService5>().dependsOn<MockService4>();
services.find<MockService3>();
BOOST_CHECK(counter == 3);
services.find<MockService4>();
BOOST_CHECK(counter == 4);
services.find<MockService5>();
BOOST_CHECK(counter == 5);
}
BOOST_AUTO_TEST_SUITE_END()
| true |
e73f4fb36c19d657115a92ab63f43cfb292dfe26 | C++ | Idhrendur/RayTracingInSeveralWeekends | /Source/hittable.h | UTF-8 | 803 | 2.828125 | 3 | [
"MIT"
] | permissive | #ifndef HITTABLE_H
#define HITTABLE_H
#include "ray.h"
#include "vector.h"
#include <optional>
namespace RayTracer
{
struct HitRecord
{
Vector point;
Vector normal;
float t = 0.0F;
bool frontFace = true;
void setFaceNormal(const Ray& ray, const Vector& outwardNormal)
{
frontFace = ray.direction().dot(outwardNormal) < 0;
normal = frontFace ? outwardNormal : -outwardNormal;
}
};
class Hittable
{
public:
Hittable() = default;
Hittable(const Hittable&) = default;
Hittable(Hittable&&) = default;
Hittable& operator=(const Hittable&) = default;
Hittable& operator=(Hittable&&) = default;
virtual ~Hittable() = default;
[[nodiscard]] virtual std::optional<HitRecord> hit(const Ray& ray, float tMin, float tMax) const = 0;
};
} // namespace RayTracer
#endif // HITTABLE_H | true |
ce1ff75a2aafa4b9a43a72d960a3965d1e93e9d6 | C++ | RullDeef/cg-lab | /lab_4/src/core/brescirren.cpp | UTF-8 | 2,128 | 2.890625 | 3 | [] | no_license | #include "brescirren.hpp"
void core::BresenhemCircleRenderer::draw(QImage& image, const Circle& circle, QColor color)
{
beginTiming();
if (circle.r == 0.0)
{
int x = std::round(circle.x);
int y = std::round(circle.y);
image.setPixel(x, y, color.rgba());
}
else
{
int x0 = std::round(circle.x);
int y0 = std::round(circle.y);
int R = std::round(circle.r);
int x = 0;
int y = R;
int d = 2 * (1 - R);
image.setPixel(x0, y0 + R, color.rgba());
image.setPixel(x0, y0 - R, color.rgba());
image.setPixel(x0 + R, y0, color.rgba());
image.setPixel(x0 - R, y0, color.rgba());
while (y >= x)
{
if (d < 0)
{
if (2 * (d + y) - 1 < 0) // horizontal move
{
x++;
d += 2 * x + 1;
}
else // diagonal move
{
x++;
y--;
d += 2 * (x - y + 1);
}
}
else if (d > 0)
{
if (2 * (d - x) - 1 < 0) // diagonal move
{
x++;
y--;
d += 2 * (x - y + 1);
}
else // vertical move
{
y--;
d += -2 * y + 1;
}
}
else // diagonal move
{
x++;
y--;
d += 2 * (x - y + 1);
}
image.setPixel(x0 + x, y0 + y, color.rgba());
image.setPixel(x0 - x, y0 + y, color.rgba());
image.setPixel(x0 - x, y0 - y, color.rgba());
image.setPixel(x0 + x, y0 - y, color.rgba());
image.setPixel(x0 + y, y0 + x, color.rgba());
image.setPixel(x0 - y, y0 + x, color.rgba());
image.setPixel(x0 - y, y0 - x, color.rgba());
image.setPixel(x0 + y, y0 - x, color.rgba());
}
}
endTiming();
}
| true |
a9272541469d7249bea2c7208117aefea7a51583 | C++ | gpard77/cs162 | /final/getChoice.cpp | UTF-8 | 588 | 3.28125 | 3 | [] | no_license | /************************************************************************
* getChoice
*
* This function validates the user's menu selection
************************************************************************/
int getChoice()
{
int choice;
while (!(cin >> choice))
{
cout << "Must be a number: " << endl;
cin.clear();
cin.ignore(100, '\n');
}
while (choice < 1 || choice > 10)
{
cout << "The only valid choices are 1-10." << endl;
cout << "Please re-enter: ";
cin >> choice;
}
return choice;
}
| true |
b09b8b32299641f26912f6ba64b72446460001dc | C++ | erzasilva/Arcade | /Vec2D.h | UTF-8 | 1,507 | 3.328125 | 3 | [] | no_license | #include <iostream>
#ifndef Vec2D_H
#define Vec2D_H
class Vec2D
{
public:
static const Vec2D ZERO;
Vec2D() : Vec2D(0, 0) {}
Vec2D(float x, float y) : mX(x), mY(y) {}
inline void SetX(float x) { mX = x; }
inline void SetY(float y) { mY = y; }
inline float GetX() const { return mX; }
inline float GetY() const { return mY; }
//Operator Overloads
//Ostream Overload
friend std::ostream& operator<<(std::ostream& consoleOut, const Vec2D& vec);
//Comparison Overloads
bool operator==(const Vec2D& V2) const;
bool operator!=(const Vec2D& V2) const;
//Unary Overloads
Vec2D operator-() const ;
//Scalar
Vec2D operator*(float scale) const;
Vec2D operator/(float scale) const;
Vec2D& operator*=(float scale);
Vec2D& operator/=(float scale);
friend Vec2D operator*(float scale, Vec2D& V1);
//Vector Math Operator overloads
Vec2D operator+(const Vec2D& V1) const;
Vec2D operator-(const Vec2D& V1) const;
Vec2D& operator+=(const Vec2D& V1);
Vec2D& operator-=(const Vec2D& V1);
//Helpers
float Mag2() const;
float Mag() const;
Vec2D GetUnitVec() const;
Vec2D& Normalize();
float Distance(const Vec2D& V2) const;
float Dot(const Vec2D& V2) const;
Vec2D ProjectOnto(const Vec2D& V2) const;
float AngleBetween(const Vec2D& V2) const;
Vec2D Reflect(const Vec2D& normal) const;
void Rotate(float angle, const Vec2D& aroundPoint);
Vec2D RotationResult(float angle, const Vec2D& aroundPoint) const;
private:
float mX, mY;
};
#endif | true |
a5611d2a46673f247167a2bb5de2b3a6c8c62e8a | C++ | yanggang98/PEViewMFC | /PEViewMFC/PEView.cpp | GB18030 | 25,140 | 2.59375 | 3 | [] | no_license | #include "pch.h"
#include "PEView.h"
#include <fstream>
#include "PEViewMFCDlg.h"
#include <thread>
using namespace std;
DWORD FileSize(CString Filepath)
{
//ļ
HANDLE hFile = CreateFile(Filepath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
//жļǷʧܣʧ
if (INVALID_HANDLE_VALUE == hFile)
{
return 0;
}
DWORD dwFileSize = 0;
dwFileSize = GetFileSize(hFile, NULL);
//رļ
CloseHandle(hFile);
//ļС
return dwFileSize;
}
//pe캯ļϢ뻺
pe::pe(CString FilePath)
{
//ļС
int size = FileSize(FilePath);
//ļСΪ0ļ·ʧ
if(size <=0)
{
g_FileSize = 0;
g_DosAddress = NULL;
g_NtFileAddress = NULL;
g_OptionalAddress = NULL;
}
else
{
//ļСĻ
PBYTE l_buffer = (PBYTE)malloc(size);
ifstream l_FileIfstream;
//
l_FileIfstream.open(FilePath, ios::binary);
l_FileIfstream.seekg(0);
//ļ뻺
l_FileIfstream.read((char*)l_buffer, size);
//ر
l_FileIfstream.close();
//ȫֱֵ
g_DosAddress = l_buffer;
g_FileSize = size;
PIMAGE_DOS_HEADER l_DosAddress = (PIMAGE_DOS_HEADER)g_DosAddress;
g_NtFileAddress = g_DosAddress + l_DosAddress->e_lfanew + 0x4;
g_OptionalAddress = g_DosAddress + l_DosAddress->e_lfanew + 0x18;
}
}
void pe::showDoSHeader(CPEViewMFCDlg *dlg)
{
//ȡDOSͷṹ
PIMAGE_DOS_HEADER l_dosHeader = (PIMAGE_DOS_HEADER)g_DosAddress;
//ӡϢ
CString strText;
CRect rect;
//Ϣ
dlg->mlist.DeleteAllItems();
int a = dlg->mlist.GetHeaderCtrl()->GetItemCount();
for (int i = 0; i < a; i++)
{
dlg->mlist.DeleteColumn(0);
}
//ñͷϢ
dlg->mlist.GetClientRect(&rect);
dlg->mlist.InsertColumn(0, L"", LVCFMT_CENTER, rect.Width() / 3, -1);
dlg->mlist.InsertColumn(1, L"ֵ", LVCFMT_CENTER, rect.Width() / 3, -1);
strText.Format(TEXT("%08X"), l_dosHeader->e_magic);
dlg->mlist.InsertItem(0,_T("Signature"));
dlg->mlist.SetItemText(0, 1, strText);
strText.Format(TEXT("%08X"), l_dosHeader->e_lfanew);
dlg->mlist.InsertItem(1, _T("offset to New Exe Header"));
dlg->mlist.SetItemText(1, 1, strText);
}
void pe::showNtFileHeader(CPEViewMFCDlg* dlg)
{
//ȡFIleͷṹ
PIMAGE_FILE_HEADER l_fileHeader = (PIMAGE_FILE_HEADER)g_NtFileAddress;
//ӡϢ
CString strText;
CRect rect;
//Ϣ
dlg->mlist.DeleteAllItems();
int a=dlg->mlist.GetHeaderCtrl()->GetItemCount();
for (int i = 0; i < a; i++)
{
dlg->mlist.DeleteColumn(0);
}
//ñͷϢ
dlg->mlist.GetClientRect(&rect);
dlg->mlist.InsertColumn(0, L"", LVCFMT_CENTER, rect.Width() / 3, -1);
dlg->mlist.InsertColumn(1, L"ֵ", LVCFMT_CENTER, rect.Width() / 3, -1);
//Machine
strText.Format(TEXT("%08X"), l_fileHeader->Machine);
dlg->mlist.InsertItem(0, _T("Machine"));
dlg->mlist.SetItemText(0, 1, strText);
//NumberOfSections
strText.Format(TEXT("%08X"), l_fileHeader->NumberOfSections);
dlg->mlist.InsertItem(1, _T("NumberOfSections"));
dlg->mlist.SetItemText(1, 1, strText);
//TimeDateStamp
strText.Format(TEXT("%08X"), l_fileHeader->TimeDateStamp);
dlg->mlist.InsertItem(2, _T("TimeDateStamp"));
dlg->mlist.SetItemText(2, 1, strText);
//PointerToSymbolTable
strText.Format(TEXT("%08X"), l_fileHeader->PointerToSymbolTable);
dlg->mlist.InsertItem(3, _T("PointerToSymbolTable"));
dlg->mlist.SetItemText(3, 1, strText);
//NumberOfSymbols
strText.Format(TEXT("%08X"), l_fileHeader->NumberOfSymbols);
dlg->mlist.InsertItem(4, _T("NumberOfSymbols"));
dlg->mlist.SetItemText(4, 1, strText);
//SizeOfOptionalHeader
strText.Format(TEXT("%08X"), l_fileHeader->SizeOfOptionalHeader);
dlg->mlist.InsertItem(5, _T("SizeOfOptionalHeader"));
dlg->mlist.SetItemText(5, 1, strText);
//Characteristics
strText.Format(TEXT("%08X"), l_fileHeader->Characteristics);
dlg->mlist.InsertItem(6, _T("Characteristics"));
dlg->mlist.SetItemText(6, 1, strText);
}
void pe::showOptionaHeader(CPEViewMFCDlg* dlg)
{
//ȡѡͷṹ
PIMAGE_OPTIONAL_HEADER l_OptionalHeader = (PIMAGE_OPTIONAL_HEADER)g_OptionalAddress;
//ӡϢ
CString strText;
CRect rect;
//Ϣ
dlg->mlist.DeleteAllItems();
int a = dlg->mlist.GetHeaderCtrl()->GetItemCount();
for (int i = 0; i < a; i++)
{
dlg->mlist.DeleteColumn(0);
}
//ñͷϢ
dlg->mlist.GetClientRect(&rect);
dlg->mlist.InsertColumn(0, L"", LVCFMT_CENTER, rect.Width() / 3, -1);
dlg->mlist.InsertColumn(1, L"ֵ", LVCFMT_CENTER, rect.Width() / 3, -1);
//Magic
strText.Format(TEXT("%08X"), l_OptionalHeader->Magic);
dlg->mlist.InsertItem(0, _T("Magic"));
dlg->mlist.SetItemText(0, 1, strText);
//SizeOfCode
strText.Format(TEXT("%08X"), l_OptionalHeader->SizeOfCode);
dlg->mlist.InsertItem(1, _T("SizeOfCode"));
dlg->mlist.SetItemText(1, 1, strText);
//AddressOfEntryPoint
strText.Format(TEXT("%08X"), l_OptionalHeader->AddressOfEntryPoint);
dlg->mlist.InsertItem(2, _T("AddressOfEntryPoint"));
dlg->mlist.SetItemText(2, 1, strText);
//ImageBase
strText.Format(TEXT("%08X"), l_OptionalHeader->ImageBase);
dlg->mlist.InsertItem(3, _T("ImageBase"));
dlg->mlist.SetItemText(3, 1, strText);
//SectionAlignment
strText.Format(TEXT("%08X"), l_OptionalHeader->SectionAlignment);
dlg->mlist.InsertItem(4, _T("SectionAlignment"));
dlg->mlist.SetItemText(4, 1, strText);
//FileAlignment
strText.Format(TEXT("%08X"), l_OptionalHeader->FileAlignment);
dlg->mlist.InsertItem(5, _T("FileAlignment"));
dlg->mlist.SetItemText(5, 1, strText);
//SizeOfImage
strText.Format(TEXT("%08X"), l_OptionalHeader->SizeOfImage);
dlg->mlist.InsertItem(6, _T("SizeOfImage"));
dlg->mlist.SetItemText(6, 1, strText);
//SizeOfHeaders
strText.Format(TEXT("%08X"), l_OptionalHeader->SizeOfHeaders);
dlg->mlist.InsertItem(7, _T("SizeOfHeaders"));
dlg->mlist.SetItemText(7, 1, strText);
}
// ڴƫƵļƫƵת
int pe::zzRvaToRaw(int RVA)
{
PIMAGE_SECTION_HEADER l_pSectionHeader;//ͷָ
PIMAGE_FILE_HEADER l_fileHeader;//Fileͷָ
int l_NumberOfSections = NULL;//ͷ
//ȡһĽṹ
l_pSectionHeader = (PIMAGE_SECTION_HEADER)( g_OptionalAddress + ((PIMAGE_FILE_HEADER)g_NtFileAddress)->SizeOfOptionalHeader);
//ȡFileͷṹ
l_fileHeader = (PIMAGE_FILE_HEADER)g_NtFileAddress;
//ȡ
l_NumberOfSections = l_fileHeader->NumberOfSections;
//н
for (int i = 0; i < l_NumberOfSections; i++)
{
//ʼλõڴƫ RVA ,˵RVA һ
if (RVA < l_pSectionHeader[i].VirtualAddress)
{
//ļƫƣRVAȥڽʼλõڴƫ,ڽļƫ
int Result = RVA - l_pSectionHeader[i - 1].VirtualAddress + l_pSectionHeader[i - 1].PointerToRawData;
return Result;
}
}
//RVA һʼڴƫ
int Result = RVA - l_pSectionHeader[l_NumberOfSections - 1].VirtualAddress + l_pSectionHeader[l_NumberOfSections - 1].PointerToRawData;
return Result;
}
void pe::showImportDirectoryTable(CPEViewMFCDlg* dlg)
{
//ȡѡͷṹ
PIMAGE_OPTIONAL_HEADER l_OptionalHeader = (PIMAGE_OPTIONAL_HEADER)g_OptionalAddress;
PIMAGE_DATA_DIRECTORY l_PDateDirectory;
PIMAGE_IMPORT_DESCRIPTOR l_PImportDescriptor;
CString strText;
l_PDateDirectory = l_OptionalHeader->DataDirectory;
CRect rect;
//Ϣ
dlg->mlist.DeleteAllItems();
int a = dlg->mlist.GetHeaderCtrl()->GetItemCount();
for (int i = 0; i < a; i++)
{
dlg->mlist.DeleteColumn(0);
}
dlg->mlist.GetClientRect(&rect);
dlg->mlist.InsertColumn(0, L"OriginalFirstThunk", LVCFMT_CENTER, rect.Width() / 3, -1);
dlg->mlist.InsertColumn(1, L"FirstThunk", LVCFMT_CENTER, rect.Width() / 3, -1);
dlg->mlist.InsertColumn(2, L"Name", LVCFMT_CENTER, rect.Width() / 3, -1);
//ȡIIDļƫ
int Raw = zzRvaToRaw(l_PDateDirectory[1].VirtualAddress);
//ȡIIDһṹָ
l_PImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)(g_DosAddress + Raw);
strText.Format(TEXT("-------------------IMAGE_IMPORT_DESCRIPTOR--------------\r\n"));
//еIIDṹ壬һṹΪ0
int i = 0;
while (l_PImportDescriptor->Name != 0x0)
{
//ȡṹԱnameļƫ
int NameIndex = zzRvaToRaw(l_PImportDescriptor->Name);
PCHAR l_pName;
//ȡnameʵʵַ
l_pName = (PCHAR)(g_DosAddress+NameIndex);
//asciiΪUnicode
int unicodeLen = MultiByteToWideChar(CP_ACP, 0, l_pName, -1, nullptr, 0);
wchar_t* pUnicode = (wchar_t*)malloc(sizeof(wchar_t) * unicodeLen);
MultiByteToWideChar(CP_ACP, 0, l_pName, -1, pUnicode, unicodeLen);
//ӡϢ
//OriginalFirstThunk
strText.Format(TEXT("%08X"), l_PImportDescriptor->OriginalFirstThunk);
dlg->mlist.InsertItem(i, strText);
//FirstThunk
strText.Format(TEXT("%s"), l_PImportDescriptor->FirstThunk);
dlg->mlist.SetItemText(i,1, strText);
//name
strText.Format(TEXT("%08X"), pUnicode);
dlg->mlist.SetItemText(i, 2, strText);
l_PImportDescriptor++;
i++;
}
}
void pe::showImportAddressTable(CPEViewMFCDlg* dlg)
{
PIMAGE_OPTIONAL_HEADER l_OptionalHeader = (PIMAGE_OPTIONAL_HEADER)g_OptionalAddress;
PIMAGE_DATA_DIRECTORY l_PDateDirectory;
PIMAGE_IMPORT_DESCRIPTOR l_PImportDescriptor;
CString strText;
l_PDateDirectory = l_OptionalHeader->DataDirectory;
// ȡIIDļƫ
int Raw = zzRvaToRaw(l_PDateDirectory[1].VirtualAddress);
//ȡIIDһṹָ
l_PImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)(g_DosAddress + Raw);
strText.Format(TEXT("-------------------IMPORT_ADDRESS_TABLE--------------\r\n"));
strText.Format(TEXT("%s RVA DATE \r\n"),strText);
CRect rect;
//Ϣ
dlg->mlist.DeleteAllItems();
int a = dlg->mlist.GetHeaderCtrl()->GetItemCount();
for (int i = 0; i < a; i++)
{
dlg->mlist.DeleteColumn(0);
}
dlg->mlist.GetClientRect(&rect);
dlg->mlist.InsertColumn(0, L"RVA", LVCFMT_CENTER, rect.Width() / 3, -1);
dlg->mlist.InsertColumn(1, L"DATE", LVCFMT_CENTER, rect.Width() / 3, -1);
dlg->mlist.InsertColumn(2, L"/", LVCFMT_CENTER, rect.Width() / 3, -1);
//еIIDṹ壬һṹΪ0
int i = 0;
while (l_PImportDescriptor->Name != 0x0)
{
//ȡַڴƫ
int RVA_1 = l_PImportDescriptor->FirstThunk;
//ȡַļƫ
int RAW_1 = zzRvaToRaw(RVA_1);//RVAתΪRAW
//ַṹָ
PIMAGE_THUNK_DATA l_pThunkData =(PIMAGE_THUNK_DATA)(g_DosAddress + RAW_1);
// IMAGE_THUNK_DAT
while (*(PDWORD)l_pThunkData!=0x0)
{
//жŵ뻹Ƶ
if (((*(PDWORD)l_pThunkData) >> 31) == 1)
{
//ŵ룬ӡϢ
strText.Format(TEXT("%08X"), RVA_1);
dlg->mlist.InsertItem(i, strText);
strText.Format(TEXT("%08X"), (*(PDWORD)l_pThunkData));
dlg->mlist.SetItemText(i, 1, strText);
strText.Format(TEXT("%08X"), (*(PDWORD)l_pThunkData) & 0x7fffffff);
dlg->mlist.SetItemText(i, 2, strText);
i++;
RVA_1 += 4;
l_pThunkData++;
continue;
}
//Ƶ
PIMAGE_IMPORT_BY_NAME l_pName = (PIMAGE_IMPORT_BY_NAME)(g_DosAddress + zzRvaToRaw(l_pThunkData->u1.AddressOfData));
//asciiתUnicode
int unicodeLen = MultiByteToWideChar(CP_ACP, 0, l_pName->Name, -1, nullptr, 0);
wchar_t* pUnicode = (wchar_t*)malloc(sizeof(wchar_t) * unicodeLen);
MultiByteToWideChar(CP_ACP, 0, l_pName->Name, -1, pUnicode, unicodeLen);
//ӡϢ
//RVA
strText.Format(TEXT("%08X"), RVA_1);
dlg->mlist.InsertItem(i, strText);
//DATE
strText.Format(TEXT("%08X"), (*(PDWORD)l_pThunkData));
dlg->mlist.SetItemText(i, 1, strText);
//
strText.Format(TEXT("%s"), pUnicode);
dlg->mlist.SetItemText(i, 2, strText);
i++;
RVA_1 += 4;
l_pThunkData++;
}
//asciiתUnicode
int Name = zzRvaToRaw(l_PImportDescriptor->Name);
PCHAR l_Name;//ĬƳȲ50
l_Name = (PCHAR)(g_DosAddress + Name);
int unicodeLen = MultiByteToWideChar(CP_ACP, 0, l_Name, -1, nullptr, 0);
wchar_t* Unicode = (wchar_t*)malloc(sizeof(wchar_t) * unicodeLen);
MultiByteToWideChar(CP_ACP, 0, l_Name, -1, Unicode, unicodeLen);
//ӡϢ
//RVA
strText.Format(TEXT("%08X"), RVA_1);
dlg->mlist.InsertItem(i, strText);
strText.Format(TEXT("%08X"), 0x00000000);
dlg->mlist.SetItemText(i, 1, strText);
//dll
strText.Format(TEXT("%s"), Unicode);
dlg->mlist.SetItemText(i, 2, strText);
i++;
dlg->mlist.InsertItem(i, L"");
i++;
std::free(Unicode);
l_PImportDescriptor++;
}
}
void pe::showExportDirectory(CPEViewMFCDlg* dlg)
{
PIMAGE_OPTIONAL_HEADER l_OptionalHeader = (PIMAGE_OPTIONAL_HEADER)g_OptionalAddress;
PIMAGE_DATA_DIRECTORY l_PDateDirectory;
PIMAGE_EXPORT_DIRECTORY l_pExportDirectory;
CString strText;
l_PDateDirectory = l_OptionalHeader->DataDirectory;
//жǷڵ
if (l_PDateDirectory[0].VirtualAddress == 0x0)
{
dlg->MessageBox(L"ûе");
return ;
}
//ȡļƫ
int Raw = zzRvaToRaw(l_PDateDirectory[0].VirtualAddress);
//ȡĽṹָ
l_pExportDirectory = (PIMAGE_EXPORT_DIRECTORY)(g_DosAddress + Raw);
//ַ
int l_nameRva = l_pExportDirectory->AddressOfNames;
DWORD* l_pNameAddress = (DWORD*)(g_DosAddress + zzRvaToRaw(l_nameRva));
//ַַ
int l_funRva = l_pExportDirectory->AddressOfFunctions;
DWORD* l_pfunAddress = (DWORD*)(g_DosAddress + zzRvaToRaw(l_funRva));
//кַ
int l_pNameOrdinals = l_pExportDirectory->AddressOfNameOrdinals;
WORD* l_NameOrdinalsAddress = (WORD*)(g_DosAddress + zzRvaToRaw(l_pNameOrdinals));
CRect rect;
//Ϣ
dlg->mlist.DeleteAllItems();
int a = dlg->mlist.GetHeaderCtrl()->GetItemCount();
for (int i = 0; i < a; i++)
{
dlg->mlist.DeleteColumn(0);
}
//ñͷ
dlg->mlist.GetClientRect(&rect);
dlg->mlist.InsertColumn(0, L"", LVCFMT_CENTER, rect.Width() / 3, -1);
dlg->mlist.InsertColumn(1, L"RVA", LVCFMT_CENTER, rect.Width() / 3, -1);
dlg->mlist.InsertColumn(2, L"", LVCFMT_CENTER, rect.Width() / 3, -1);
//ַ
int index = 0;
for (int i = 0; i < l_pExportDirectory->NumberOfFunctions; i++)
{
bool flag = false;
//ждŵֵǷ0
if (l_pfunAddress[i] == 0x0)
{
continue;
}
//к
for (int j = 0; j < l_pExportDirectory->NumberOfNames; j++)
{
//Ƚкеֵ͵ַ±Ƿ
if (l_NameOrdinalsAddress[j] == i)
{
PCHAR l_Name;
l_Name = (PCHAR)(g_DosAddress + zzRvaToRaw(l_pNameAddress[j]));
int unicodeLen = MultiByteToWideChar(CP_ACP, 0, l_Name, -1, nullptr, 0);
wchar_t* Unicode = (wchar_t*)malloc(sizeof(wchar_t) * unicodeLen);
MultiByteToWideChar(CP_ACP, 0, l_Name, -1, Unicode, unicodeLen);
//ӡϢ
//
strText.Format(TEXT("%08X"), i + l_pExportDirectory->Base);
dlg->mlist.InsertItem(index, strText);
//RVA
strText.Format(TEXT("%08X"), l_pfunAddress[i]);
dlg->mlist.SetItemText(index, 1, strText);
//
strText.Format(TEXT("%s"), Unicode);
dlg->mlist.SetItemText(index, 2, strText);
index++;
std::free(Unicode);
flag = true;
}
}
//жǷкŵǷеַ±
if (flag == false)
{
//ӡϢ
//
strText.Format(TEXT("%08X"), i + l_pExportDirectory->Base);
dlg->mlist.InsertItem(index, strText);
//RVA
strText.Format(TEXT("%08X"), l_pfunAddress[i]);
dlg->mlist.SetItemText(index, 1, strText);
//
strText.Format(TEXT("%s"), "");
dlg->mlist.SetItemText(index, 2, strText);
index++;
}
}
}
void pe::showImportNameTable(CPEViewMFCDlg* dlg)
{
PIMAGE_OPTIONAL_HEADER l_OptionalHeader = (PIMAGE_OPTIONAL_HEADER)g_OptionalAddress;
PIMAGE_DATA_DIRECTORY l_PDateDirectory;
PIMAGE_IMPORT_DESCRIPTOR l_PImportDescriptor;
CString strText;
l_PDateDirectory = l_OptionalHeader->DataDirectory;
// ȡIIDļƫ
int Raw = zzRvaToRaw(l_PDateDirectory[1].VirtualAddress);
//ȡIIDһṹָ
l_PImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)(g_DosAddress + Raw);
strText.Format(TEXT("-------------------IMPORT_ADDRESS_TABLE--------------\r\n"));
strText.Format(TEXT("%s RVA DATE \r\n"), strText);
CRect rect;
//Ϣ
dlg->mlist.DeleteAllItems();
int a = dlg->mlist.GetHeaderCtrl()->GetItemCount();
for (int i = 0; i < a; i++)
{
dlg->mlist.DeleteColumn(0);
}
dlg->mlist.GetClientRect(&rect);
dlg->mlist.InsertColumn(0, L"RVA", LVCFMT_CENTER, rect.Width() / 3, -1);
dlg->mlist.InsertColumn(1, L"DATE", LVCFMT_CENTER, rect.Width() / 3, -1);
dlg->mlist.InsertColumn(2, L"/", LVCFMT_CENTER, rect.Width() / 3, -1);
//еIIDṹ壬һṹΪ0
int i = 0;
while (l_PImportDescriptor->Name != 0x0)
{
//ȡַڴƫ
int RVA_1 = l_PImportDescriptor->OriginalFirstThunk;
//ȡַļƫ
int RAW_1 = zzRvaToRaw(RVA_1);//RVAתΪRAW
//ַṹָ
PIMAGE_THUNK_DATA l_pThunkData = (PIMAGE_THUNK_DATA)(g_DosAddress + RAW_1);
// IMAGE_THUNK_DAT
while (*(PDWORD)l_pThunkData != 0x0)
{
//жŵ뻹Ƶ
if (((*(PDWORD)l_pThunkData) >> 31) == 1)
{
//ŵ룬ӡϢ
strText.Format(TEXT("%08X"), RVA_1);
dlg->mlist.InsertItem(i, strText);
strText.Format(TEXT("%08X"), (*(PDWORD)l_pThunkData));
dlg->mlist.SetItemText(i, 1, strText);
strText.Format(TEXT("%08X"), (*(PDWORD)l_pThunkData) & 0x7fffffff);
dlg->mlist.SetItemText(i, 2, strText);
i++;
RVA_1 += 4;
l_pThunkData++;
continue;
}
//Ƶ
PIMAGE_IMPORT_BY_NAME l_pName = (PIMAGE_IMPORT_BY_NAME)(g_DosAddress + zzRvaToRaw(l_pThunkData->u1.AddressOfData));
//asciiתUnicode
int unicodeLen = MultiByteToWideChar(CP_ACP, 0, l_pName->Name, -1, nullptr, 0);
wchar_t* pUnicode = (wchar_t*)malloc(sizeof(wchar_t) * unicodeLen);
MultiByteToWideChar(CP_ACP, 0, l_pName->Name, -1, pUnicode, unicodeLen);
//ӡϢ
//RVA
strText.Format(TEXT("%08X"), RVA_1);
dlg->mlist.InsertItem(i, strText);
//DATE
strText.Format(TEXT("%08X"), (*(PDWORD)l_pThunkData));
dlg->mlist.SetItemText(i, 1, strText);
//
strText.Format(TEXT("%s"), pUnicode);
dlg->mlist.SetItemText(i, 2, strText);
i++;
RVA_1 += 4;
l_pThunkData++;
}
//asciiתUnicode
int Name = zzRvaToRaw(l_PImportDescriptor->Name);
PCHAR l_Name;
l_Name = (PCHAR)(g_DosAddress + Name);
int unicodeLen = MultiByteToWideChar(CP_ACP, 0, l_Name, -1, nullptr, 0);
wchar_t* Unicode = (wchar_t*)malloc(sizeof(wchar_t) * unicodeLen);
MultiByteToWideChar(CP_ACP, 0, l_Name, -1, Unicode, unicodeLen);
//ӡϢ
//RVA
strText.Format(TEXT("%08X"), RVA_1);
dlg->mlist.InsertItem(i, strText);
strText.Format(TEXT("%08X"), 0x00000000);
dlg->mlist.SetItemText(i, 1, strText);
//dll
strText.Format(TEXT("%s"), Unicode);
dlg->mlist.SetItemText(i, 2, strText);
i++;
dlg->mlist.InsertItem(i, L"");
i++;
std::free(Unicode);
l_PImportDescriptor++;
}
}
void pe::showBaeRelocationTable(CPEViewMFCDlg* dlg)
{
PIMAGE_OPTIONAL_HEADER l_OptionalHeader = (PIMAGE_OPTIONAL_HEADER)g_OptionalAddress;
PIMAGE_DATA_DIRECTORY l_PDateDirectory;
PIMAGE_EXPORT_DIRECTORY l_pExportDirectory;
CString strText;
PIMAGE_BASE_RELOCATION l_pBaeRelocation;
l_PDateDirectory = l_OptionalHeader->DataDirectory;
int l_BaeRelocation = l_PDateDirectory[5].VirtualAddress;
int l_BaeRelocationSize = l_PDateDirectory[5].Size;
//жǷضλ
if (l_BaeRelocation == 0)
{
dlg->MessageBox(L"ûضλ");
return;
}
l_pBaeRelocation =(PIMAGE_BASE_RELOCATION) (g_DosAddress+zzRvaToRaw(l_PDateDirectory[5].VirtualAddress));
CRect rect;
//Ϣ
dlg->mlist.DeleteAllItems();
int a = dlg->mlist.GetHeaderCtrl()->GetItemCount();
for (int i = 0; i < a; i++)
{
dlg->mlist.DeleteColumn(0);
}
//ñͷϢ
dlg->mlist.GetClientRect(&rect);
dlg->mlist.InsertColumn(0, L"RVA", LVCFMT_CENTER, rect.Width() / 3, -1);
dlg->mlist.InsertColumn(1, L"FOA", LVCFMT_CENTER, rect.Width() / 3, -1);
dlg->mlist.InsertColumn(2, L"", LVCFMT_CENTER, rect.Width() / 3, -1);
int l_sum = 0;
int index = 0;
do
{
l_BaeRelocation = l_BaeRelocation + 8;
short int* l_pValue = (short int*)((PBYTE)l_pBaeRelocation + 8);
while (l_pValue < (short int*)((PBYTE)l_pBaeRelocation + (l_pBaeRelocation->SizeOfBlock)))
{
//RVA
strText.Format(TEXT("%08X"), (*l_pValue & 0xfff) + l_pBaeRelocation->VirtualAddress);
dlg->mlist.InsertItem(index, strText);
//FOA
strText.Format(TEXT("%08X"), zzRvaToRaw((*l_pValue & 0xFFF) + l_pBaeRelocation->VirtualAddress));
dlg->mlist.SetItemText(index, 1, strText);
//
//ضλ
switch ((*l_pValue & 0xf000) >> 12)
{
case 0:
strText.Format(TEXT("IMAGE_REL_BASED_ABSOLUTE"));
break;
case 3:
strText.Format(TEXT("IMAGE_REL_BASED_HIGHLOW"));
break;
default:
strText.Format(TEXT("IMAGE_REL_BASED_DIR64"));
break;
}
dlg->mlist.SetItemText(index, 2, strText);
index++;
l_BaeRelocation = l_BaeRelocation + 2;
l_pValue++;
}
l_sum = l_sum + l_pBaeRelocation->SizeOfBlock;
l_pBaeRelocation = (PIMAGE_BASE_RELOCATION)((PBYTE)l_pBaeRelocation + (l_pBaeRelocation->SizeOfBlock));
} while (l_sum < l_BaeRelocationSize);
}
pe::~pe()
{
g_DosAddress = NULL;
g_FileSize = NULL;
g_NtFileAddress = NULL;
g_OptionalAddress = NULL;
}
| true |
3c2fe4d2327fcb6c2f29658ee21336889c24f93e | C++ | LeonardoDelgado1905/Programming-Language | /Lexico/anl_lexico.cpp | UTF-8 | 1,035 | 2.828125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
string caracteres[10];
int main(){
freopen("arreglos.txt", "w", stdout);
string symbols[] = {
"booleano",
"caracter",
"entero",
"real",
"cadena",
"fin_principal",
"fin_principal",
"leer",
"imprimir",
"si ",
"entonces",
"fin_si",
"si_no",
"mientras ",
"hacer",
"fin_mientras",
"para ",
"fin_para",
"seleccionar ",
"entre",
"caso ",
"romper",
"defecto",
"fin_seleccionar",
"estructura ",
"fin_estructura",
"funcion ",
"retornar ",
"fin_funcion",
"verdadero",
"falso",
};
cout<< "[";
for (char i = 'a'; i <= 'z'; ++i){
cout<<"'"<<i<<"', ";
}
cout<<"]"<<endl;
cout<< "[";
for (char i = 'A'; i <= 'Z'; ++i){
cout<<"'"<<i<<"', ";
}
cout<<"]"<<endl;
cout<< "[";
for (char i = '0'; i <= '9'; ++i){
cout<<"'"<<i<<"', ";
}
cout<<"]"<<endl;
int len = *(&symbols + 1) - symbols;
cout<< "[";
for (int i; i < len; ++i){
cout<<"'"<<symbols[i]<<"', ";
}
cout<<"]"<<endl;
return 0;
} | true |
facfc30a132963609f9a51c7d5f8a521a5567a9f | C++ | robocupmipt/Communication | /test.cpp | UTF-8 | 2,346 | 2.75 | 3 | [] | no_license | #include"include/queue_config.h"
#include<iostream>
#define PERMISSION 0777
#define MESSAGE_TYPE 1
#define CHECK(nameFunction, retValue) \
do { \
if(retValue == -1) \
{ \
perror(nameFunction);\
return 1; \
} \
else \
printf("%s succeeded\n", nameFunction); \
} while(0) \
enum GameState
{
initial = 0,
ready,
set,
playing,
finished
};
struct msgBuf
{
long type;
int state;
};
struct OutputData
{
enum GameState state;
};
int main(int argc, char *argv[])
{
if(argc != 2)
{
printf("Arg error\n");
return 1;
}
const char file[] = "key";
if(atoi(argv[1]) == 1) //transmitter
{
printf("Transmitter\n");
key_t key = ftok(file, 0);
CHECK("ftok", key);
printf("Key = %d\n", key);
int msgid = msgget(key, PERMISSION | IPC_CREAT | IPC_EXCL);
if(msgid < 0)
{
if(errno == EEXIST)
{
printf("Already exist. Need to remove\n");
msgid = msgget(key, PERMISSION);
CHECK("msgget", msgid);
/*
CHECK("msgctl", msgctl(msgid, IPC_RMID, (struct msqid_ds *)NULL));
msgid = msgget(key, PERMISSION | IPC_CREAT | IPC_EXCL);
CHECK("msgid", msgid);
*/
}
else
{
perror("msgget");
return 4;
}
}
else
printf("Message queue get succesfully\n");
printf("Let's get transmitted\n");
struct msgBuf buf;
buf.type = MESSAGE_TYPE;
do {
std::cout << "enter state " << std::endl;
std::cin >> buf.state;
int result = msgsnd(msgid, (struct msgbuf *)&buf, sizeof(int), 0);
CHECK("msgsnd", result);
} while(1);
}
else if(atoi(argv[1]) == 0) //reciever
{
printf("Receiver\n");
key_t key = ftok(file, 0);
CHECK("ftok", key);
printf("Key = %d\n", key);
int msgid;
do msgid = msgget(key, PERMISSION);
while((msgid == -1) && (errno ==ENOENT));
if(msgid == -1)
{
printf("Some error");
return 4;
}
printf("msgget succeed\n");
printf("Let's get received\n");
struct msgBuf buf;
int length;
do {
length = msgrcv(msgid, (struct msg_buf *)&buf, sizeof(int), 0, 0);
std::cout << "received" << std::endl;
CHECK("msgrcv", length);
std::cout << "type " << buf.type << std::endl;
std::cout << "state " << buf.state << std::endl;
}
while(1);
}
else
{
printf("Arg error\n");
return 1;
}
return 0;
}
| true |
f8a0e6dc7a0684291d94e638df1509d4cc07d82b | C++ | iampiyush/Algorithms_interview | /removeDuplicatesFromString.cpp | UTF-8 | 1,813 | 2.84375 | 3 | [] | no_license | // Find MISSING eLEMENTS using Sorting...
// time complexity 0(n)...
// space complexity 0(1)....
#include<iostream>
#include<cstdio>
#include<ctime>
#include<unistd.h>
#include<algorithm>
using namespace std;
// swap two variables...
void swap(int &x,int &y)
{
int temp;
temp=x;
x=y;
y=temp;
}
void removeDuplicateBitVector(char str[])
{
int i,j;
int len,index;
unsigned char mymap[26];
len=strlen(str);
for(i=0;i<26;i++)
mymap[i]=0;
j=0;
for(i=0;i<len;i++)
{
if(str[i]>='a' && str[i]<='z')
{
index=str[i]-'a';
if(mymap[index]==0)
{
str[j]=str[i];
mymap[index]=1;
j++;
}
}
else
{
//assert(0);
cout<<"Wrong Input\n";
break;
}
}
str[j]='\0';
return ;
}
// method considering '\0' as special token
void removeDuplicate2(char str[])
{
int len,i,j,k;
int countUnique;
int state;
len=strlen(str);
//countUnique=0;
i=0;
j=0;
while(i<len)
{
if(str[i]!='\0')
{
str[j]=str[i];
for(k=j+1;k<len;k++)
{
if(str[k]==str[j])
str[k]='\0';
}
j++;
}
i++;
}
str[j]='\0';
return ;
}
void removeDuplicate(char str[])
{
int len,i,j,k;
int state;
len=strlen(str);
i=0;
j=0;
while(i<len)
{
if(str[i]!='$')
{
str[j]=str[i];
for(k=j+1;k<len;k++)
{
if(str[k]==str[j])
str[k]='$';
}
j++;
}
i++;
}
str[j]='\0';
return ;
}
int main()
{
int a[100];
int b[100];
int t,size,i;
char buf[100];
cin>>t;
while(t--)
{
//cin>>buf;
gets(buf);
removeDuplicateBitVector(buf);
cout<<buf<<endl;
}
return 0;
}
| true |
fd491bea3d0067e7f15fd3e5e8bc3741c09e5501 | C++ | KreiserLee/CPP-Study | /2/Ex2.9.cpp | UTF-8 | 212 | 2.71875 | 3 | [] | no_license | #include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int a, b = 10;
int x(110);
a = b = 100;
cout << a << b << endl;
cout << x << endl;
return 0;
} | true |
ec3edf620eb743d2c06de14a27647822c3f35b1d | C++ | lnugentgibson/terrain-erosion | /graphics/analysis/calc_norm.cc | UTF-8 | 3,154 | 2.515625 | 3 | [] | no_license | #include <cstring>
#include <fstream>
#include <sstream>
#include "cxxopts/cxxopts.h"
#include "graphics/analysis/differential.h"
#include "graphics/image/binary/binimg.h"
using graphics::analysis::Differential;
using graphics::image::InputSpecifier;
using graphics::image::OutputSpecifier;
using graphics::image::binary::MapNeighborhood;
using graphics::image::binary::TransformerFactory;
int main(int argc, char *argv[]) {
cxxopts::Options options(argv[0],
"converts a grayscale image from binary to ppm");
options.add_options()("i,input", "first binary image file path",
cxxopts::value<std::string>())(
"d,depth", "from min", cxxopts::value<float>())("s,smoothing", "from min",
cxxopts::value<int>())(
"o,output", "ppm image file path", cxxopts::value<std::string>());
auto result = options.parse(argc, argv);
float d = result["d"].as<float>();
int smoothing = result["s"].as<int>();
std::ifstream ifs(result["i"].as<std::string>().c_str(),
std::ios::in | std::ios::binary);
std::stringstream fsd;
fsd << result["o"].as<std::string>() << "_diff.bin";
std::string filenamed = fsd.str();
std::ofstream ofsd(filenamed.c_str(), std::ios::out | std::ios::binary);
auto builder = TransformerFactory::get().Create("Differentiator");
builder->SetFloatParam("d", d);
auto transformer = (*builder)();
MapNeighborhood(InputSpecifier(&ifs, sizeof(float)),
OutputSpecifier(&ofsd, sizeof(Differential)), smoothing,
transformer.get());
ifs.close();
ofsd.close();
std::ifstream ifsd(filenamed.c_str(), std::ios::in | std::ios::binary);
std::stringstream fsx;
fsx << result["o"].as<std::string>() << "_dx.bin";
std::string filenamex = fsx.str();
std::ofstream ofsx(filenamex.c_str(), std::ios::out | std::ios::binary);
builder = TransformerFactory::get().Create("DifferentialDXExtractor");
transformer = (*builder)();
Map(InputSpecifier(&ifsd, sizeof(Differential)),
OutputSpecifier(&ofsx, sizeof(float)), transformer.get());
ofsx.close();
// ifsd.clear();
ifsd.seekg(0, std::ios::beg);
std::stringstream fsy;
fsy << result["o"].as<std::string>() << "_dy.bin";
std::string filenamey = fsy.str();
std::ofstream ofsy(filenamey.c_str(), std::ios::out | std::ios::binary);
builder = TransformerFactory::get().Create("DifferentialDYExtractor");
transformer = (*builder)();
Map(InputSpecifier(&ifsd, sizeof(Differential)),
OutputSpecifier(&ofsy, sizeof(float)), transformer.get());
ofsy.close();
// ifsd.clear();
ifsd.seekg(0, std::ios::beg);
std::stringstream fsn;
fsn << result["o"].as<std::string>() << "_norm.bin";
std::string filenamen = fsn.str();
std::ofstream ofsn(filenamen.c_str(), std::ios::out | std::ios::binary);
builder = TransformerFactory::get().Create("DifferentialNormalExtractor");
transformer = (*builder)();
Map(InputSpecifier(&ifsd, sizeof(Differential)),
OutputSpecifier(&ofsn, sizeof(float), 3), transformer.get());
ofsn.close();
ifsd.close();
return 0;
} | true |
f4c72b4878741a02d304d01fe5fbbee31b765295 | C++ | jayantawasthi575/dsalgo450 | /ds323.cpp | UTF-8 | 846 | 3.078125 | 3 | [] | no_license | class Solution {
public:
void dfs(vector<vector<int>>& image,int sr,int sc,int newColor,int rows,int cols,int source)
{
if(sr<0 || sr>=rows || sc<0 ||sc>=cols)
return;
else if(image[sr][sc]!=source)
return;
image[sr][sc]=newColor;
dfs(image,sr-1,sc,newColor,rows,cols,source);
dfs(image,sr+1,sc,newColor,rows,cols,source);
dfs(image,sr,sc-1,newColor,rows,cols,source);
dfs(image,sr,sc+1,newColor,rows,cols,source);
}
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
if(newColor==image[sr][sc])
return image;
int rows=image.size();
int cols=image[0].size();
int source=image[sr][sc];
dfs(image,sr,sc,newColor,rows,cols,source);
return image;
}
}; | true |
cd7346eafc9ce43b37604e1ab67dafda12b23668 | C++ | RajatBachhawat/Railway-Booking-System | /src/BookingClasses.cpp | UTF-8 | 36,771 | 2.515625 | 3 | [] | no_license |
//Rajat Bachhawat
//Roll No: 19CS10073
//BookingClasses.cpp
#include "BookingClasses.h"
#include "Divyaang.h"
// Names defined as static constants
template<> const string BookingClasses::ACFirstClass::sName = "AC First Class";
template<> const string BookingClasses::ExecutiveChairCar::sName = "Executive Chair Car";
template<> const string BookingClasses::AC2Tier::sName = "AC 2 Tier";
template<> const string BookingClasses::FirstClass::sName = "First Class";
template<> const string BookingClasses::AC3Tier::sName = "AC 3 Tier";
template<> const string BookingClasses::ACChairCar::sName = "AC Chair Car";
template<> const string BookingClasses::Sleeper::sName = "Sleeper";
template<> const string BookingClasses::SecondSitting::sName = "Second Sitting";
// Number of Tiers defined as static constants
template<> const int BookingClasses::ACFirstClass::sNumberOfTiers = 2;
template<> const int BookingClasses::ExecutiveChairCar::sNumberOfTiers = 0;
template<> const int BookingClasses::AC2Tier::sNumberOfTiers = 2;
template<> const int BookingClasses::FirstClass::sNumberOfTiers = 2;
template<> const int BookingClasses::AC3Tier::sNumberOfTiers = 3;
template<> const int BookingClasses::ACChairCar::sNumberOfTiers = 0;
template<> const int BookingClasses::Sleeper::sNumberOfTiers = 3;
template<> const int BookingClasses::SecondSitting::sNumberOfTiers = 0;
// Sitting/Sleeping status defined as static constants
template<> const bool BookingClasses::ACFirstClass::sSitting = false;
template<> const bool BookingClasses::ExecutiveChairCar::sSitting = true;
template<> const bool BookingClasses::AC2Tier::sSitting = false;
template<> const bool BookingClasses::FirstClass::sSitting = false;
template<> const bool BookingClasses::AC3Tier::sSitting = false;
template<> const bool BookingClasses::ACChairCar::sSitting = true;
template<> const bool BookingClasses::Sleeper::sSitting = false;
template<> const bool BookingClasses::SecondSitting::sSitting = true;
// AC/Non-AC status defined as static constants
template<> const bool BookingClasses::ACFirstClass::sAC = true;
template<> const bool BookingClasses::ExecutiveChairCar::sAC = true;
template<> const bool BookingClasses::AC2Tier::sAC = true;
template<> const bool BookingClasses::FirstClass::sAC = false;
template<> const bool BookingClasses::AC3Tier::sAC = true;
template<> const bool BookingClasses::ACChairCar::sAC = true;
template<> const bool BookingClasses::Sleeper::sAC = false;
template<> const bool BookingClasses::SecondSitting::sAC = false;
// Tatkal Load Factor defined as static constants
template<> const double BookingClasses::ACFirstClass::sTatkalLoadFactor = 0.3;
template<> const double BookingClasses::ExecutiveChairCar::sTatkalLoadFactor = 0.3;
template<> const double BookingClasses::AC2Tier::sTatkalLoadFactor = 0.3;
template<> const double BookingClasses::FirstClass::sTatkalLoadFactor = 0.3;
template<> const double BookingClasses::AC3Tier::sTatkalLoadFactor = 0.3;
template<> const double BookingClasses::ACChairCar::sTatkalLoadFactor = 0.3;
template<> const double BookingClasses::Sleeper::sTatkalLoadFactor = 0.3;
template<> const double BookingClasses::SecondSitting::sTatkalLoadFactor = 0.1;
// Minimum Tatkal Charge defined as static constants
template<> const double BookingClasses::ACFirstClass::sMinTatkalCharge = 400.0;
template<> const double BookingClasses::ExecutiveChairCar::sMinTatkalCharge = 400.0;
template<> const double BookingClasses::AC2Tier::sMinTatkalCharge = 400.0;
template<> const double BookingClasses::FirstClass::sMinTatkalCharge = 400.0;
template<> const double BookingClasses::AC3Tier::sMinTatkalCharge = 300.0;
template<> const double BookingClasses::ACChairCar::sMinTatkalCharge = 125.0;
template<> const double BookingClasses::Sleeper::sMinTatkalCharge = 100.0;
template<> const double BookingClasses::SecondSitting::sMinTatkalCharge = 10.0;
// Maximum Tatkal Charge defined as static constants
template<> const double BookingClasses::ACFirstClass::sMaxTatkalCharge = 500.0;
template<> const double BookingClasses::ExecutiveChairCar::sMaxTatkalCharge = 500.0;
template<> const double BookingClasses::AC2Tier::sMaxTatkalCharge = 500.0;
template<> const double BookingClasses::FirstClass::sMaxTatkalCharge = 500.0;
template<> const double BookingClasses::AC3Tier::sMaxTatkalCharge = 400.0;
template<> const double BookingClasses::ACChairCar::sMaxTatkalCharge = 225.0;
template<> const double BookingClasses::Sleeper::sMaxTatkalCharge = 200.0;
template<> const double BookingClasses::SecondSitting::sMaxTatkalCharge = 15.0;
// Minimum Tatkal Distance defined as static constants
template<> const double BookingClasses::ACFirstClass::sMinTatkalDistance = 500.0;
template<> const double BookingClasses::ExecutiveChairCar::sMinTatkalDistance = 250.0;
template<> const double BookingClasses::AC2Tier::sMinTatkalDistance = 500.0;
template<> const double BookingClasses::FirstClass::sMinTatkalDistance = 500.0;
template<> const double BookingClasses::AC3Tier::sMinTatkalDistance = 500.0;
template<> const double BookingClasses::ACChairCar::sMinTatkalDistance = 250.0;
template<> const double BookingClasses::Sleeper::sMinTatkalDistance = 500.0;
template<> const double BookingClasses::SecondSitting::sMinTatkalDistance = 100.0;
BookingClasses::BookingClasses()
{
#ifdef _DEBUG
cout << "Class Booking Classes"<<" ++CONSTRUCTED++" << endl;
#endif
}; //Ctor
BookingClasses::~BookingClasses()
{
#ifdef _DEBUG
cout << "Class Booking Classes"<< " ++DESTRUCTED++" << endl;
#endif
}; //Virtual dtor for polymorphic hierarchy
ostream &operator<<(ostream &out, const BookingClasses &bclass)
{
out << "Travel Class = " << bclass.GetName() << "\n";
if (bclass.IsSitting() == false)
out << " : "
<< "Mode: "
<< "Sleeping"
<< "\n";
else
out << " : "
<< "Mode: "
<< "Sitting"
<< "\n";
if (bclass.IsAC() == false)
out << " : "
<< "Comfort: "
<< "Non-AC"
<< "\n";
else
out << " : "
<< "Comfort: "
<< "AC"
<< "\n";
out << " : "
<< "Bunks: " << bclass.GetNumberOfTiers() << "\n";
if (bclass.IsLuxury() == false)
out << " : "
<< "Luxury: "
<< "No"
<< "\n";
else
out << " : "
<< "Luxury: "
<< "Yes"
<< "\n";
return out;
}
template<typename T>
BookingClassTypes<T>::BookingClassTypes() {
#ifdef _DEBUG
cout << "Booking Class (SubType)= \n" << *this << " ++CONSTRUCTED++" << endl;
#endif
};
template<typename T>
BookingClassTypes<T>::~BookingClassTypes() {
#ifdef _DEBUG
cout << "Booking Class (SubType) = \n" << *this << " ++DESTRUCTED++" << endl;
#endif
};
template<typename T>
const BookingClassTypes<T> &BookingClassTypes<T>::Type(){
static const BookingClassTypes<T> obj;
return obj;
}
template<typename T>
double BookingClassTypes<T>::GetTatkalLoadFactor() const {
return BookingClassTypes<T>::sTatkalLoadFactor;
}
template<typename T>
double BookingClassTypes<T>::GetMinTatkalCharge() const {
return BookingClassTypes<T>::sMinTatkalCharge;
}
template<typename T>
double BookingClassTypes<T>::GetMaxTatkalCharge() const {
return BookingClassTypes<T>::sMaxTatkalCharge;
}
template<typename T>
double BookingClassTypes<T>::GetMinTatkalDistance() const {
return BookingClassTypes<T>::sMinTatkalDistance;
}
template<typename T>
double BookingClassTypes<T>::GetLoadFactor() const {
return BookingClassTypes<T>::sLoadFactor;
}
template<typename T>
string BookingClassTypes<T>::GetName() const {
return BookingClassTypes<T>::sName;
}
template<typename T>
int BookingClassTypes<T>::GetNumberOfTiers() const {
return BookingClassTypes<T>::sNumberOfTiers;
}
template<typename T>
double BookingClassTypes<T>::GetReservationCharge() const {
return BookingClassTypes<T>::sReservationCharge;
}
template<typename T>
bool BookingClassTypes<T>::IsAC() const {
return BookingClassTypes<T>::sAC;
}
template<typename T>
bool BookingClassTypes<T>::IsLuxury() const {
return BookingClassTypes<T>::sLuxury;
}
template<typename T>
bool BookingClassTypes<T>::IsSitting() const {
return BookingClassTypes<T>::sSitting;
}
// Utility function that is used by GetConcessionFactor of Concessions
template<typename T>
double BookingClassTypes<T>::GetConcessionForDivyaang(const Divyaang *dis) const {
return dis->GetDivyaangConcessionFactor(*this);
}
// -------- TESTING FUNCTION AHEAD --------
void BookingClasses::UnitTest()
{
int totalCount = 91;
cout << "\n\nClass - BookingClasses\n\n";
//Test methods of BookingClasses::AC3Tier
const BookingClasses::AC3Tier &AC3TierObj = BookingClasses::AC3Tier::Type();
double loadFactorTest = AC3TierObj.GetLoadFactor();
double rChargeTest = AC3TierObj.GetReservationCharge();
string nameTest = AC3TierObj.GetName();
bool ACTest = AC3TierObj.IsAC();
bool luxuryTest = AC3TierObj.IsLuxury();
bool sittingTest = AC3TierObj.IsSitting();
int numTest = AC3TierObj.GetNumberOfTiers();
double resTest = AC3TierObj.GetReservationCharge();
double tLoadTest = AC3TierObj.GetTatkalLoadFactor();
double tMinCharge = AC3TierObj.GetMinTatkalCharge();
double tMaxCharge = AC3TierObj.GetMaxTatkalCharge();
unsigned int tMinDist = AC3TierObj.GetMinTatkalDistance();
cout << "Test No. 1: AC3Tier::GetLoadFactor() returns the correct load factor: ";
if (loadFactorTest == 2.5)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 2: AC3Tier::GetName() returns the correct name: ";
if (nameTest == "AC 3 Tier")
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 3: AC3Tier::IsAC() returns correct AC status: ";
if (ACTest == true)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 4: AC3Tier::IsLuxury() returns correct luxury status: ";
if (luxuryTest == false)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 5: AC3Tier::IsSitting() returns correct sitting status: ";
if (sittingTest == false)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 6: AC3Tier::GetNumberOfTiers() returns the correct number of tiers: ";
if (numTest == 3)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 7: AC3Tier::GetReservationCharge() returns the correct reservation charge: ";
if (resTest == 40)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 8: AC3Tier::GetTatkalLoadFactor() returns the correct tatkal load factor: ";
if (tLoadTest == 0.3)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 9: AC3Tier::GetMinTatkalCharge() returns the correct minimum tatkal charge: ";
if (tMinCharge == 300)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 10: AC3Tier::GetMaxTatkalCharge() returns the correct maximum tatkal charge: ";
if (tMaxCharge == 400)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 11: AC3Tier::GetMinTatkalDist() returns the correct minimum tatkal distance: ";
if (tMinDist == 500)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
//Test methods of BookingClasses::Sleeper
const BookingClasses::Sleeper &SleeperObj = BookingClasses::Sleeper::Type();
loadFactorTest = SleeperObj.GetLoadFactor();
rChargeTest = SleeperObj.GetReservationCharge();
nameTest = SleeperObj.GetName();
ACTest = SleeperObj.IsAC();
luxuryTest = SleeperObj.IsLuxury();
sittingTest = SleeperObj.IsSitting();
numTest = SleeperObj.GetNumberOfTiers();
resTest = SleeperObj.GetReservationCharge();
tLoadTest = SleeperObj.GetTatkalLoadFactor();
tMinCharge = SleeperObj.GetMinTatkalCharge();
tMaxCharge = SleeperObj.GetMaxTatkalCharge();
tMinDist = SleeperObj.GetMinTatkalDistance();
cout << "Test No. 12: Sleeper::GetLoadFactor() returns the correct load factor: ";
if (loadFactorTest == 1)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 13: Sleeper::GetName() returns the correct name: ";
if (nameTest == "Sleeper")
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 14: Sleeper::IsAC() returns correct AC status: ";
if (ACTest == false)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 15: Sleeper::IsLuxury() returns correct luxury status: ";
if (luxuryTest == false)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 16: Sleeper::IsSitting() returns correct sitting status: ";
if (sittingTest == false)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 17: Sleeper::GetNumberOfTiers() returns the correct number of tiers: ";
if (numTest == 3)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 18: Sleeper::GetReservationCharge() returns the correct reservation charge: ";
if (resTest == 20)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 19: Sleeper::GetTatkalLoadFactor() returns the correct tatkal load factor: ";
if (tLoadTest == 0.3)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 20: Sleeper::GetMinTatkalCharge() returns the correct minimum tatkal charge: ";
if (tMinCharge == 100)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 21: Sleeper::GetMaxTatkalCharge() returns the correct maximum tatkal charge: ";
if (tMaxCharge == 200)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 22: Sleeper::GetMinTatkalDist() returns the correct minimum tatkal distance: ";
if (tMinDist == 500)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
//Test methods of BookingClasses::AC2Tier
const BookingClasses::AC2Tier &AC2TierObj = BookingClasses::AC2Tier::Type();
loadFactorTest = AC2TierObj.GetLoadFactor();
rChargeTest = AC2TierObj.GetReservationCharge();
nameTest = AC2TierObj.GetName();
ACTest = AC2TierObj.IsAC();
luxuryTest = AC2TierObj.IsLuxury();
sittingTest = AC2TierObj.IsSitting();
numTest = AC2TierObj.GetNumberOfTiers();
resTest = AC2TierObj.GetReservationCharge();
tLoadTest = AC2TierObj.GetTatkalLoadFactor();
tMinCharge = AC2TierObj.GetMinTatkalCharge();
tMaxCharge = AC2TierObj.GetMaxTatkalCharge();
tMinDist = AC2TierObj.GetMinTatkalDistance();
cout << "Test No. 23: AC2Tier::GetLoadFactor() returns the correct load factor: ";
if (loadFactorTest == 4)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 24: AC2Tier::GetName() returns the correct name: ";
if (nameTest == "AC 2 Tier")
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 25: AC2Tier::IsAC() returns correct AC status: ";
if (ACTest == true)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 26: AC2Tier::IsLuxury() returns correct luxury status: ";
if (luxuryTest == false)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 27: AC2Tier::IsSitting() returns correct sitting status: ";
if (sittingTest == false)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 28: AC2Tier::GetNumberOfTiers() returns the correct number of tiers: ";
if (numTest == 2)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 29: AC2Tier::GetReservationCharge() returns the correct reservation charge: ";
if (resTest == 50)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 30: AC2Tier::GetTatkalLoadFactor() returns the correct tatkal load factor: ";
if (tLoadTest == 0.3)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 31: AC2Tier::GetMinTatkalCharge() returns the correct minimum tatkal charge: ";
if (tMinCharge == 400)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 32: AC2Tier::GetMaxTatkalCharge() returns the correct maximum tatkal charge: ";
if (tMaxCharge == 500)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 33: AC2Tier::GetMinTatkalDist() returns the correct minimum tatkal distance: ";
if (tMinDist == 500)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
//Test methods of BookingClasses::ACFirstClass
const BookingClasses::ACFirstClass &ACFirstClassObj = BookingClasses::ACFirstClass::Type();
loadFactorTest = ACFirstClassObj.GetLoadFactor();
rChargeTest = ACFirstClassObj.GetReservationCharge();
nameTest = ACFirstClassObj.GetName();
ACTest = ACFirstClassObj.IsAC();
luxuryTest = ACFirstClassObj.IsLuxury();
sittingTest = ACFirstClassObj.IsSitting();
numTest = ACFirstClassObj.GetNumberOfTiers();
resTest = ACFirstClassObj.GetReservationCharge();
tLoadTest = ACFirstClassObj.GetTatkalLoadFactor();
tMinCharge = ACFirstClassObj.GetMinTatkalCharge();
tMaxCharge = ACFirstClassObj.GetMaxTatkalCharge();
tMinDist = ACFirstClassObj.GetMinTatkalDistance();
cout << "Test No. 34: ACFirstClass::GetLoadFactor() returns the correct load factor: ";
if (loadFactorTest == 6.5)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 35: ACFirstClass::GetName() returns the correct name: ";
if (nameTest == "AC First Class")
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 36: ACFirstClass::IsAC() returns correct AC status: ";
if (ACTest == true)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 37: ACFirstClass::IsLuxury() returns correct luxury status: ";
if (luxuryTest == true)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 38: ACFirstClass::IsSitting() returns correct sitting status: ";
if (sittingTest == false)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 39: ACFirstClass::GetNumberOfTiers() returns the correct number of tiers: ";
if (numTest == 2)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 40: ACFirstClass::GetReservationCharge() returns the correct reservation charge: ";
if (resTest == 60)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 41: ACFirstClass::GetTatkalLoadFactor() returns the correct tatkal load factor: ";
if (tLoadTest == 0.3)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 42: ACFirstClass::GetMinTatkalCharge() returns the correct minimum tatkal charge: ";
if (tMinCharge == 400)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 43: ACFirstClass::GetMaxTatkalCharge() returns the correct maximum tatkal charge: ";
if (tMaxCharge == 500)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 44: ACFirstClass::GetMinTatkalDist() returns the correct minimum tatkal distance: ";
if (tMinDist == 500)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
//Test methods of BookingClasses::FirstClass
const BookingClasses::FirstClass &FirstClassObj = BookingClasses::FirstClass::Type();
loadFactorTest = FirstClassObj.GetLoadFactor();
rChargeTest = FirstClassObj.GetReservationCharge();
nameTest = FirstClassObj.GetName();
ACTest = FirstClassObj.IsAC();
luxuryTest = FirstClassObj.IsLuxury();
sittingTest = FirstClassObj.IsSitting();
numTest = FirstClassObj.GetNumberOfTiers();
resTest = FirstClassObj.GetReservationCharge();
tLoadTest = FirstClassObj.GetTatkalLoadFactor();
tMinCharge = FirstClassObj.GetMinTatkalCharge();
tMaxCharge = FirstClassObj.GetMaxTatkalCharge();
tMinDist = FirstClassObj.GetMinTatkalDistance();
cout << "Test No. 45: FirstClass::GetLoadFactor() returns the correct load factor: ";
if (loadFactorTest == 3)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 46: FirstClass::GetName() returns the correct name: ";
if (nameTest == "First Class")
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 47: FirstClass::IsAC() returns correct AC status: ";
if (ACTest == false)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 48: FirstClass::IsLuxury() returns correct luxury status: ";
if (luxuryTest == true)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 49: FirstClass::IsSitting() returns correct sitting status: ";
if (sittingTest == false)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 50: FirstClass::GetNumberOfTiers() returns the correct number of tiers: ";
if (numTest == 2)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 51: FirstClass::GetReservationCharge() returns the correct reservation charge: ";
if (resTest == 50)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 52: FirstClass::GetTatkalLoadFactor() returns the correct tatkal load factor: ";
if (tLoadTest == 0.3)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 53: FirstClass::GetMinTatkalCharge() returns the correct minimum tatkal charge: ";
if (tMinCharge == 400)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 54: FirstClass::GetMaxTatkalCharge() returns the correct maximum tatkal charge: ";
if (tMaxCharge == 500)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 55: FirstClass::GetMinTatkalDist() returns the correct minimum tatkal distance: ";
if (tMinDist == 500)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
//Test methods of BookingClasses::ACChairCar
const BookingClasses::ACChairCar &ACChairCarObj = BookingClasses::ACChairCar::Type();
loadFactorTest = ACChairCarObj.GetLoadFactor();
rChargeTest = ACChairCarObj.GetReservationCharge();
nameTest = ACChairCarObj.GetName();
ACTest = ACChairCarObj.IsAC();
luxuryTest = ACChairCarObj.IsLuxury();
sittingTest = ACChairCarObj.IsSitting();
numTest = ACChairCarObj.GetNumberOfTiers();
resTest = ACChairCarObj.GetReservationCharge();
tLoadTest = ACChairCarObj.GetTatkalLoadFactor();
tMinCharge = ACChairCarObj.GetMinTatkalCharge();
tMaxCharge = ACChairCarObj.GetMaxTatkalCharge();
tMinDist = ACChairCarObj.GetMinTatkalDistance();
cout << "Test No. 56: ACChairCar::GetLoadFactor() returns the correct load factor: ";
if (loadFactorTest == 2)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 57: ACChairCar::GetName() returns the correct name: ";
if (nameTest == "AC Chair Car")
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 58: ACChairCar::IsAC() returns correct AC status: ";
if (ACTest == true)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 59: ACChairCar::IsLuxury() returns correct luxury status: ";
if (luxuryTest == false)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 60: ACChairCar::IsSitting() returns correct sitting status: ";
if (sittingTest == true)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 61: ACChairCar::GetNumberOfTiers() returns the correct number of tiers: ";
if (numTest == 0)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 62: ACChairCar::GetReservationCharge() returns the correct reservation charge: ";
if (resTest == 40)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 63: ACChairCar::GetTatkalLoadFactor() returns the correct tatkal load factor: ";
if (tLoadTest == 0.3)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 64: ACChairCar::GetMinTatkalCharge() returns the correct minimum tatkal charge: ";
if (tMinCharge == 125)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 65: ACChairCar::GetMaxTatkalCharge() returns the correct maximum tatkal charge: ";
if (tMaxCharge == 225)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 66: ACChairCar::GetMinTatkalDist() returns the correct minimum tatkal distance: ";
if (tMinDist == 250)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
//Test methods of BookingClasses::SecondSitting
const BookingClasses::SecondSitting &SecondSittingObj = BookingClasses::SecondSitting::Type();
loadFactorTest = SecondSittingObj.GetLoadFactor();
rChargeTest = SecondSittingObj.GetReservationCharge();
nameTest = SecondSittingObj.GetName();
ACTest = SecondSittingObj.IsAC();
luxuryTest = SecondSittingObj.IsLuxury();
sittingTest = SecondSittingObj.IsSitting();
numTest = SecondSittingObj.GetNumberOfTiers();
resTest = SecondSittingObj.GetReservationCharge();
tLoadTest = SecondSittingObj.GetTatkalLoadFactor();
tMinCharge = SecondSittingObj.GetMinTatkalCharge();
tMaxCharge = SecondSittingObj.GetMaxTatkalCharge();
tMinDist = SecondSittingObj.GetMinTatkalDistance();
cout << "Test No. 67: SecondSitting::GetLoadFactor() returns the correct load factor: ";
if (loadFactorTest == 0.6)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 68: SecondSitting::GetName() returns the correct name: ";
if (nameTest == "Second Sitting")
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 69: SecondSitting::IsAC() returns correct AC status: ";
if (ACTest == false)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 70: SecondSitting::IsLuxury() returns correct luxury status: ";
if (luxuryTest == false)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 71: SecondSitting::IsSitting() returns correct sitting status: ";
if (sittingTest == true)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 72: SecondSitting::GetNumberOfTiers() returns the correct number of tiers: ";
if (numTest == 0)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 73: SecondSitting::GetReservationCharge() returns the correct reservation charge: ";
if (resTest == 15)
{
totalCount--;
}
else{
cout << "Test failed when calling SecondSitting::GetReservationCharge() \n";
}
cout << "Test No. 74: SecondSitting::GetTatkalLoadFactor() returns the correct tatkal load factor: ";
if (tLoadTest == 0.1)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 75: SecondSitting::GetMinTatkalCharge() returns the correct minimum tatkal charge: ";
if (tMinCharge == 10)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 76: SecondSitting::GetMaxTatkalCharge() returns the correct maximum tatkal charge: ";
if (tMaxCharge == 15)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 77: SecondSitting::GetMinTatkalDist() returns the correct minimum tatkal distance: ";
if (tMinDist == 100)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
//Test methods of BookingClasses::ExecutiveChairCar
const BookingClasses::ExecutiveChairCar &ExecutiveChairCarObj = BookingClasses::ExecutiveChairCar::Type();
loadFactorTest = ExecutiveChairCarObj.GetLoadFactor();
rChargeTest = ExecutiveChairCarObj.GetReservationCharge();
nameTest = ExecutiveChairCarObj.GetName();
ACTest = ExecutiveChairCarObj.IsAC();
luxuryTest = ExecutiveChairCarObj.IsLuxury();
sittingTest = ExecutiveChairCarObj.IsSitting();
numTest = ExecutiveChairCarObj.GetNumberOfTiers();
resTest = ExecutiveChairCarObj.GetReservationCharge();
tLoadTest = ExecutiveChairCarObj.GetTatkalLoadFactor();
tMinCharge = ExecutiveChairCarObj.GetMinTatkalCharge();
tMaxCharge = ExecutiveChairCarObj.GetMaxTatkalCharge();
tMinDist = ExecutiveChairCarObj.GetMinTatkalDistance();
cout << "Test No. 78: ExecutiveChairCar::GetLoadFactor() returns the correct load factor: ";
if (loadFactorTest == 5)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 79: ExecutiveChairCar::GetName() returns the correct name: ";
if (nameTest == "Executive Chair Car")
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 80: ExecutiveChairCar::IsAC() returns correct AC status: ";
if (ACTest == true)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 81: ExecutiveChairCar::IsLuxury() returns correct luxury status: ";
if (luxuryTest == true)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 82: ExecutiveChairCar::IsSitting() returns correct sitting status: ";
if (sittingTest == true)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 83: ExecutiveChairCar::GetNumberOfTiers() returns the correct number of tiers: ";
if (numTest == 0)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 84: ExecutiveChairCar::GetReservationCharge() returns the correct reservation charge: ";
if (resTest == 60)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 85: ExecutiveChairCar::GetTatkalLoadFactor() returns the correct tatkal load factor: ";
if (tLoadTest == 0.3)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 86: ExecutiveChairCar::GetMinTatkalCharge() returns the correct minimum tatkal charge: ";
if (tMinCharge == 400)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 87: ExecutiveChairCar::GetMaxTatkalCharge() returns the correct maximum tatkal charge: ";
if (tMaxCharge == 500)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout << "Test No. 88: ExecutiveChairCar::GetMinTatkalDist() returns the correct minimum tatkal distance: ";
if (tMinDist == 250)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
//Test Output streaming operator for BookingClassTypes<T>
string outputGolden="Called From: AC 2 Tier\nTravel Class = AC 2 Tier\n : Mode: Sleeping\n : Comfort: AC\n : Bunks: 2\n : Luxury: No\n";
stringstream ss;
const BookingClasses::AC2Tier& aTest = AC2Tier::Type();
ss<<aTest;
cout << "Test No. 89: Output streaming operator for BookingClasses<T> (BookingClasses::AC2Tier): ";
if(ss.str()==outputGolden)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
// Test on BookingClasses
// Test working of polymorphic hierarchy by comparing the GetName() function return value
cout << "Test No. 90: Testing the correct working of polymorphic heirarchy (using GetName()): ";
const BookingClasses &obj = BookingClasses::AC3Tier::Type();
if(obj.GetName()=="AC 3 Tier") {
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
//Test Output streaming operator for BookingClasses
cout << "Test No. 91: Output streaming operator for BookingClasses: ";
outputGolden="Travel Class = AC 2 Tier\n : Mode: Sleeping\n : Comfort: AC\n : Bunks: 2\n : Luxury: No\n";
const BookingClasses& bTest = AC2Tier::Type();
stringstream ss_;
ss_<<bTest;
if(ss_.str()==outputGolden)
{
totalCount--;
cout<<"PASS\n";
}
else{
cout << "FAIL\n";
}
cout<<"\n----- VERDICT : ";
if(totalCount==0)
{
cout<<"PASS -----\n";
}
else
{
cout<<totalCount<<"/91 Tests have failed -----\n";
}
}
| true |
cbf5cc809917ae42d9a1d98f2f1a5f1cc252983f | C++ | JINWOO-0715/Data-structure | /오목_step_3(스택,큐,무르기,파일입출력)/오목_step_3(스택,큐,무르기,파일입출력).cpp | UHC | 9,473 | 2.71875 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#define MAX 19
#define WHITE 1
#define BLACK 2
#define PAN 0
struct Point
{
int x;
int y;
int stone;
};
Point stack[361];
void makepan();
int point_x;
int point_y;
int baducpan[MAX][MAX];
int top = -1;
int save = -1;
int turn = 2;
//void findstone();
void MakeStone();
void BackStone();
int main()
{
int a = 0;
while (1)
{
makepan();
printf("1:ǥ 2: 3: \n");
scanf_s("%d", &a);
switch (a)
{
case 1:
MakeStone();
break;
case 2:
BackStone();
break;
case 3:
exit(0);
break;
default:
break;
}
}
return 0;
}
void makepan()
{
system("cls");
printf("-------------------------------------------------------\n");
for (int i = 0; i < MAX; i++)
{
for (int j = 0; j < MAX; j++)
{
if (baducpan[i][j] == WHITE)
{
printf_s(" ");
}
else if (baducpan[i][j] == BLACK)
{
printf_s(" ");
}
else printf_s(" + ");
}
printf("%d", i);
printf_s("\n");
}
printf(" 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18\n");
printf("-------------------------------------------------------\n");
// findstone();
}/*
void findstone()
{
int count_1 = 0, count_2 = 0, count_3 = 0, count_4 = 0, count_5 = 0, count_6 = 0;
int countblock = 0, countwhite = 0;
int max_white = 0, max_black = 0, a = 0, b = 0, c = 0;
int white_max[MAX], black_max[MAX];
for (int i = 0; i < MAX; i++)
{
for (int j = 0; j < MAX; j++)
{
if (baducpan[i][j] == BLACK)
{
count_1 += 1;
countblock++;
}
else if (baducpan[i][j] == WHITE)
{
count_2 += 1;
countwhite++;
}
if (baducpan[j][i] == BLACK)
{
count_3 += 1;
}
else if (baducpan[j][i] == WHITE)
{
count_4 += 1;
}
}
printf("%d :%d :%d %d :%d %d\n", i, count_1, count_2, i, count_3, count_4);
count_1 = 0, count_2 = 0, count_3 = 0, count_4 = 0;
for (int j = 0; j < MAX; j++)
{
if (baducpan[i][j] == BLACK)
{
if (baducpan[i][j + 1] == BLACK || baducpan[i][j - 1] == BLACK)
count_1 += 1;
}
else if (baducpan[i][j] == WHITE)
{
if (baducpan[i][j + 1] == WHITE || baducpan[i][j - 1] == WHITE)
count_2 += 1;
}
if (baducpan[j][i] == BLACK)
{
if (baducpan[j + 1][i] == BLACK || baducpan[j - 1][i] == BLACK)
count_3 += 1;
}
else if (baducpan[j][i] == WHITE)
{
if (baducpan[j + 1][i] == WHITE || baducpan[j - 1][i] == WHITE)
count_4 += 1;
}
}
if (count_1 > count_2)
{
printf(" :%d ", count_1);
}
else if (count_1 < count_2)
{
printf(" :%d ", count_2);
}
else if (count_1 == count_2 && count_1 != 0)
{
printf(" :%d ", count_2);
}
else
{
printf(" ");
}
if (count_3 > count_4)
{
printf(" :%d\n", count_3);
}
else if (count_3 < count_4)
{
printf(" :%d\n", count_4);
}
else if (count_3 == count_4 && count_3 != 0)
{
printf(" :%d\n", count_3);
}
else
{
printf("\n");
}
black_max[a] = count_1;
white_max[a] = count_2;
a++;
count_1 = 0, count_2 = 0, count_3 = 0, count_4 = 0;
}
printf(" : %d, : %d \n", countblock, countwhite);
for (int i = 0; i < MAX; i++)
{
if (white_max[i] > max_white)
{
max_white = white_max[i];
b = i;
}
if (black_max[i] > max_black)
{
max_black = black_max[i];
c = i;
}
}
if (max_white > max_black)
{
printf("ְ ǥ :");
for (int i = 0; i < MAX; i++)
{
if (baducpan[b][i] == WHITE)
{
if (baducpan[b][i + 1] == WHITE || baducpan[b][i - 1] == WHITE)
{
printf("(%d,%d)", b, i);
}
}
}
printf("\n");
}
else if (max_white < max_black)
{
printf("ְ ǥ : ");
for (int i = 0; i < MAX; i++)
{
if (baducpan[c][i] == BLACK)
{
if (baducpan[c][i + 1] == BLACK || baducpan[c][i - 1] == BLACK)
{
printf("(%d,%d)", c, i);
}
}
}
printf("\n");
}
else if (max_white == max_black && max_white != 0)
{
printf(" :%d \n", max_white);
max_white = 0;
max_black = 0;
}
a = 0;
printf(" 밢 / \n");
for (int k = 0; k < 37; k++)
{
for (int i = 0; i < MAX; i++)
{
for (int j = 0; j < MAX; j++)
{
if (i + j == k)
{
if (baducpan[i][j] == BLACK)
{
if (baducpan[i - 1][j + 1] == BLACK || baducpan[i + 1][j - 1] == BLACK)
count_5 += 1;
}
if (baducpan[i][j] == WHITE)
{
if (baducpan[i - 1][j + 1] == WHITE || baducpan[i + 1][j - 1] == WHITE)
count_6 += 1;
}
}
}
}
if (count_5 > count_6)
{
printf(" %d", count_5);
}
else if (count_5 < count_6)
{
printf(" %d", count_6);
}
else if (count_5 == count_6 && count_5 != 0)
{
printf(" %d", count_5);
}
else
{
printf(" %d ", k);
}
if (k == 10)
{
printf("\n");
}
if (k == 20)
{
printf("\n");
}
if (k == 30)
{
printf("\n");
}
count_5 = 0;
count_6 = 0;
}
printf("\n");
printf(" 밢 \n");
for (int k = 18; k >= -18; k--)
{
for (int i = 0; i < MAX; i++)
{
for (int j = 0; j < MAX; j++)
{
if (i - j == k)
{
if (baducpan[i][j] == BLACK)
{
if (baducpan[i + 1][j + 1] == BLACK || baducpan[i - 1][j - 1] == BLACK)
count_5 += 1;
}
if (baducpan[i][j] == WHITE)
{
if (baducpan[i + 1][j + 1] == WHITE || baducpan[i - 1][j - 1] == WHITE)
count_6 += 1;
}
}
}
}
if (count_5 > count_6)
{
printf(" %d", count_5);
}
else if (count_5 < count_6)
{
printf(" %d", count_6);
}
else if (count_5 == count_6 && count_5 != 0)
{
printf(" %d", count_5);
}
else
{
printf(" %d ", k);
}
if (k == -10)
{
printf("\n");
}
if (k == 0)
{
printf("\n");
}
if (k == 10)
{
printf("\n");
}
count_5 = 0;
count_6 = 0;
}
printf("\n");
}*/
void MakeStone()
{
while (save != 361)
{
if (turn % 2 == 0)
{
printf_s("浹 ǥ Էϼ 100 100 Դϴ.\n");
scanf_s("%d %d", &point_x, &point_y);
while (1)
{
if (point_x == 100 && point_y == 100)
{
return;
}
if (point_x >= 0 && point_x < 19 && point_y >= 0 && point_y < 19)
{
if (baducpan[point_x][point_y] == WHITE || baducpan[point_x][point_y] == BLACK)
{
rewind(stdin);
printf("߸Է߽ϴ \n");
scanf_s("%d %d", &point_x, &point_y);
}
else
{
break;
}
}
else
{
rewind(stdin);
printf("߸Է߽ϴ \n");
scanf_s("%d %d", &point_x, &point_y);
}
}
baducpan[point_x][point_y] = BLACK;
top++;
stack[top].x = point_x;
stack[top].y = point_y;
stack[top].stone = BLACK;
save = top;
turn++;
makepan();
}
else {
printf_s("鵹 ǥ Էϼ 100 100 Դϴ.\n");
scanf_s("%d %d", &point_x, &point_y);
while (1)
{
if (point_x == 100 && point_y == 100)
{
return;
}
if (point_x > -1 && point_x < 19 && point_y > -1 && point_y < 19)
{
if (baducpan[point_x][point_y] == WHITE || baducpan[point_x][point_y] == BLACK)
{
rewind(stdin);
printf("߸Է߽ϴ. \n");
scanf_s("%d %d", &point_x, &point_y);
}
else
{
break;
}
}
else
{
rewind(stdin);
printf("߸Է߽ϴ \n");
scanf_s("%d %d", &point_x, &point_y);
}
}
baducpan[point_x][point_y] = WHITE;
top++;
stack[top].x = point_x;
stack[top].y = point_y;
stack[top].stone = WHITE;
save = top;
turn++;
makepan();
}
}
}
void BackStone()
{
FILE *fw;
FILE *fr;
int a = 0;
while (1)
{
printf("1: 2: 3: 4:ҷ 5:ư\n");
scanf("%d", &a);
if (a == 1)
{
if (top == -1)
{
printf(" \n");
}
else
{
baducpan[stack[top].x][stack[top].y] = PAN;
top--;
turn--;
makepan();
}
}
else if (a == 2)
{
if (save == top)
{
printf("⸦ Ұ \n");
}
else
{
top++;
baducpan[stack[top].x][stack[top].y] = stack[top].stone;
turn++;
makepan();
}
}
else if (a == 3)
{
fopen_s(&fw, "one.text", "wt");
for (int i = 0; i < MAX; i++)
{
for (int j = 0; j < MAX; j++)
{
fprintf(fw, " %d", baducpan[i][j]);
}
fprintf(fw, "\n");
}
fprintf(fw, " %d", turn);
fprintf(fw, "\n");
fprintf(fw, " %d", top);
fprintf(fw, "\n");
fprintf(fw, " %d", save);
fprintf(fw, "\n");
for (int i = 0; i <= save; i++)
{
fprintf(fw, " %d", stack[i].x);
fprintf(fw, " %d", stack[i].y);
fprintf(fw, " %d", stack[i].stone);
}
fclose(fw);
}
else if (a == 4)
{
fopen_s(&fr, "one.text", "rt");
for (int i = 0; i < MAX; i++)
{
for (int j = 0; j < MAX; j++)
{
fscanf(fr, " %d", &baducpan[i][j]);
}
fscanf(fr, "\n");
}
fscanf(fr, " %d", &turn);
fscanf(fr, "\n");
fscanf(fr, " %d", &top);
fscanf(fr, "\n");
fscanf(fr, " %d", &save);
fscanf(fr, "\n");
for (int i = 0; i <= save; i++)
{
fscanf(fr, " %d", &stack[i].x);
fscanf(fr, " %d", &stack[i].y);
fscanf(fr, " %d", &stack[i].stone);
}
fclose(fr);
makepan();
}
else if (a == 5)
{
return;
}
}
} | true |
cca0643e3e1ec16d7487235edc15cbf51bfc1239 | C++ | Tudat/tudat | /include/tudat/astro/aerodynamics/windModel.h | UTF-8 | 5,374 | 2.5625 | 3 | [] | permissive | /* Copyright (c) 2010-2019, Delft University of Technology
* All rigths reserved
*
* This file is part of the Tudat. Redistribution and use in source and
* binary forms, with or without modification, are permitted exclusively
* under the terms of the Modified BSD license. You should have received
* a copy of the license with this file. If not, please or visit:
* http://tudat.tudelft.nl/LICENSE.
*
*/
#ifndef TUDAT_WIND_MODEL_H
#define TUDAT_WIND_MODEL_H
#include <Eigen/Core>
#include <memory>
#include <functional>
#include <tudat/astro/reference_frames/referenceFrameTransformations.h>
namespace tudat
{
namespace aerodynamics
{
//! Base class for a wind model.
/*!
* Base class for a wind model. The wind vector is defined as the local velocity of the atmosphere expressed in the
* frame corotating with the body.
*/
class WindModel
{
public:
//! Constructor.
WindModel( const reference_frames::AerodynamicsReferenceFrames associatedFrame =
reference_frames::vertical_frame ):
associatedFrame_( associatedFrame )
{
if( !( associatedFrame == reference_frames::inertial_frame ||
associatedFrame == reference_frames::corotating_frame ||
associatedFrame == reference_frames::vertical_frame ) )
{
throw std::runtime_error(
"Error when creating wind model, definition must be in inertial, corotating or vertical frame" );
}
}
//! Destructor.
virtual ~WindModel( ){ }
//! Function (pure virtual) to retrieve wind velocity vector in body-fixed, body-centered frame of body with atmosphere
/*!
* Function (pure virtual) to retrieve wind velocity vector in body-fixed, body-centered frame of body with atmosphere
* \param currentAltitude Altitude at which wind vector is to be retrieved.
* \param currentLongitude Longitude at which wind vector is to be retrieved.
* \param currentLatitude Latitude at which wind vector is to be retrieved.
* \param currentTime Time at which wind vector is to be retrieved.
* \return Wind velocity vector in body-fixed, body-centered frame of body with atmosphere
*/
virtual Eigen::Vector3d getCurrentBodyFixedCartesianWindVelocity(
const double currentAltitude,
const double currentLongitude,
const double currentLatitude,
const double currentTime ) = 0;
reference_frames::AerodynamicsReferenceFrames getAssociatedFrame( )
{
return associatedFrame_;
}
protected:
reference_frames::AerodynamicsReferenceFrames associatedFrame_;
};
class ConstantWindModel: public WindModel
{
public:
ConstantWindModel(
const Eigen::Vector3d constantWindVelocity,
const reference_frames::AerodynamicsReferenceFrames associatedFrame =
reference_frames::vertical_frame ):
WindModel( associatedFrame ), constantWindVelocity_( constantWindVelocity ){ }
Eigen::Vector3d getCurrentBodyFixedCartesianWindVelocity(
const double currentAltitude,
const double currentLongitude,
const double currentLatitude,
const double currentTime )
{
return constantWindVelocity_;
}
private:
Eigen::Vector3d constantWindVelocity_;
};
//! Class for computing the wind velocity vector from a custom, user-defined function.
class CustomWindModel: public WindModel
{
public:
//! Constructor
/*!
* Constructor
* \param windFunction Function that returns wind vector as a function of altitude, longitude, latitude and time (in that
* order).
*/
CustomWindModel(
const std::function< Eigen::Vector3d( const double, const double, const double, const double ) > windFunction,
const reference_frames::AerodynamicsReferenceFrames associatedFrame =
reference_frames::vertical_frame ):
WindModel( associatedFrame ), windFunction_( windFunction ){ }
//! Destructor
~CustomWindModel( ){ }
//! Function to retrieve wind velocity vector in body-fixed, body-centered frame of body with atmosphere
/*!
* Function to retrieve wind velocity vector in body-fixed, body-centered frame of body with atmosphere
* \param currentAltitude Altitude at which wind vector is to be retrieved.
* \param currentLongitude Longitude at which wind vector is to be retrieved.
* \param currentLatitude Latitude at which wind vector is to be retrieved.
* \param currentTime Time at which wind vector is to be retrieved.
* \return Wind velocity vector in body-fixed, body-centered frame of body with atmosphere
*/
Eigen::Vector3d getCurrentBodyFixedCartesianWindVelocity(
const double currentAltitude,
const double currentLongitude,
const double currentLatitude,
const double currentTime )
{
return windFunction_( currentAltitude, currentLongitude, currentLatitude, currentTime );
}
private:
//! Function that returns wind vector as a function of altitude, longitude, latitude and time (in that order).
std::function< Eigen::Vector3d( const double, const double, const double, const double ) > windFunction_;
};
} // namespace aerodynamics
} // namespace tudat
#endif // TUDAT_WIND_MODEL_H
| true |
ad6c0de3ff8a0cefe58a770a34714880aa7a9e73 | C++ | BobDeng1974/openGeeL | /openGeeL/renderer/shadowmapping/cascadedmap.h | UTF-8 | 1,428 | 2.59375 | 3 | [] | no_license | #ifndef CASCADEDSHADOWMAP_H
#define CASCADEDSHADOWMAP_H
#include <vec3.hpp>
#include <mat4x4.hpp>
#include "shadowmapconfig.h"
#include "shadowmap.h"
#define MAPCOUNT 4
namespace geeL {
struct CascadedMap {
float cascadeEnd;
float cascadeEndClip;
glm::mat4 lightTransform;
};
class CascadedShadowmap : public Shadowmap {
public:
CascadedShadowmap(const Light& light, std::unique_ptr<Texture> innerTexture,
float shadowBias, ShadowmapResolution resolution);
virtual Resolution getScreenResolution() const;
protected:
float shadowBias;
CascadedShadowmap(const CascadedShadowmap& other) = delete;
CascadedShadowmap& operator= (const CascadedShadowmap& other) = delete;
};
class CascadedDirectionalShadowmap : public CascadedShadowmap {
public:
CascadedDirectionalShadowmap(const Light& light, const SceneCamera& camera,
float shadowBias, ShadowmapResolution resolution);
virtual void bindData(const Shader& shader, const std::string& name);
virtual void removeMap(Shader& shader);
virtual void draw(const SceneCamera* const camera, const RenderScene& scene,
ShadowmapRepository& repository);
//Set split planes (between cameras near and far clip plane)
void setCascades(const SceneCamera& camera);
virtual TextureType getTextureType() const;
private:
CascadedMap shadowMaps[MAPCOUNT];
void computeLightTransforms(const SceneCamera& camera);
};
}
#endif
| true |
922218df57d432c2aca97ad8c4937152c0f07f28 | C++ | andrewli77/MINOBS-anc | /tabulist.cpp | UTF-8 | 415 | 3.03125 | 3 | [] | no_license | #include "tabulist.h"
#include "debug.h"
TabuList::TabuList(int size) : MAX_SIZE(size) { }
void TabuList::add(const Ordering &o) {
_list.push_back(o);
if (_list.size() > MAX_SIZE) {
_list.pop_front();
}
}
bool TabuList::contains(const Ordering &o) {
int n = _list.size();
for (int i = 0; i < n; i++) {
if (o.equals(_list[i])) {
return true;
}
}
return false;
} | true |
5f574fdf87992fe479d61ab03db0d2f0cf81dfc9 | C++ | jonathlela/vast | /branches/VAST-0.3.4/ACE_wrappers/ace/Truncate.h | UTF-8 | 2,134 | 2.78125 | 3 | [] | no_license | // -*- C++ -*-
//=============================================================================
/**
* @file Truncate.h
*
* Truncate.h,v 4.3 2006/02/24 17:33:32 shuston Exp
*
* @author Steve Huston <shuston@riverace.com>
*/
//=============================================================================
#ifndef ACE_TRUNCATE_H
#define ACE_TRUNCATE_H
#include /**/ "ace/pre.h"
#include "ace/config-all.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#include "ace/Global_Macros.h"
#if !defined(ACE_LACKS_NUMERIC_LIMITS)
// some platforms pollute the namespace by defining max() and min() macros
# ifdef max
# undef max
# endif
# ifdef min
# undef min
# endif
# include <limits>
#else
# include "ace/os_include/os_limits.h"
#endif /* ACE_LACKS_NUMERIC_LIMITS */
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
namespace ACE_Utils
{
/**
* @class Truncate
*
* @brief Helper function to truncate an integral value to an int.
*
* Very useful since ACE methods return int very often and the value's
* source is often a different-size integral type, such as size_t.
* This function hides the truncation logic and resolves compiler
* diagnostics.
*
* @internal Internal use only.
*/
template<typename X>
inline int Truncate (const X& val)
{
#if !defined (ACE_LACKS_NUMERIC_LIMITS)
if (val > static_cast<X> (std::numeric_limits<int>::max ()))
return std::numeric_limits<int>::max ();
#else
if (val > static_cast<X> (INT_MAX))
return INT_MAX;
#endif /* ACE_LACKS_NUMERIC_LIMITS */
return static_cast<int> (val);
}
// Specialize one for size_t to alleviate the explicit instantiation pain.
template<>
inline int Truncate<size_t> (const size_t& val)
{
#if !defined (ACE_LACKS_NUMERIC_LIMITS)
if (val > static_cast<size_t> (std::numeric_limits<int>::max ()))
return std::numeric_limits<int>::max ();
#else
if (val > static_cast<size_t> (INT_MAX))
return INT_MAX;
#endif /* ACE_LACKS_NUMERIC_LIMITS */
return static_cast<int> (val);
}
} // namespace ACE_Utils
ACE_END_VERSIONED_NAMESPACE_DECL
#include /**/ "ace/post.h"
#endif /* ACE_TRUNCATE_H*/
| true |
5607b27c5604a8295eef2a389136d86884616bd2 | C++ | mrinalvig/CIS-17A---Final-Project | /Final Project/Final Project/Abilities.h | UTF-8 | 218 | 2.8125 | 3 | [] | no_license | #pragma once
#include <string>
class Abilities
{
private:
std::string abilities;
public:
Abilities(std::string abilities);
~Abilities();
std::string getAbilities() const { return " " + abilities; };
};
| true |
76a499af4c50f4c80c8f30fddd10193b47ca22d3 | C++ | ColinGilbert/grandpa-animation | /Include/IAnimation.h | UTF-8 | 905 | 2.78125 | 3 | [] | no_license | #ifndef __GRP_I_ANIMATION_H__
#define __GRP_I_ANIMATION_H__
namespace grp
{
enum AnimationMode
{
ANIMATION_SINGLE = 0,
ANIMATION_LOOP,
ANIMATION_PINGPONG
};
enum AnimationSampleType
{
SAMPLE_STEP = 0,
SAMPLE_LINEAR,
SAMPLE_SPLINE
};
class IAnimation
{
public:
virtual float getDuration() const = 0;
virtual void setTime(float time) = 0;
virtual float getTime() const = 0;
virtual void setTimeScale(float timeScale) = 0;
virtual float getTimeScale() const = 0;
virtual void setWeight(float weight, float fadeTime = 0.2f) = 0;
virtual float getWeight() const = 0;
virtual int getPriority() const = 0;
virtual void setPlayMode(AnimationMode mode) = 0;
virtual AnimationMode getPlayMode() const = 0;
virtual void setUserData(void* data) = 0;
virtual void* getUserData() const = 0;
protected:
virtual ~IAnimation(){}
};
}
#endif
| true |
16a272b9baa448ea1013d1f930a59b69e2491601 | C++ | HanpyBin/CP-Note | /leetcode/排序/1833/solution.cpp | UTF-8 | 632 | 2.53125 | 3 | [] | no_license | class Solution
{
public:
int maxIceCream(vector<int>& costs, int coins)
{
// int n = costs.size();
// vector<int> dp(coins+1);
// for (int i = 1; i <= n; i++)
// for (int j = coins; j >= 0; j--)
// if (j+costs[i-1] <= coins)
// dp[j] = max(dp[j+costs[i-1]]+1, dp[j]);
// return dp[0];
sort(costs.begin(), costs.end());
int res = 0;
int n = costs.size();
for (int i = 0; i < n; i++)
{
coins -= costs[i];
if (coins < 0)
return i;
}
return n;
}
}; | true |
038fb6e7aaaa5d0dac41c5991be19f698ea1ad0e | C++ | w0lker/ACM | /leetcode/leetcode_Plus_One.cpp | UTF-8 | 621 | 3.109375 | 3 | [] | no_license | #include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
vector<int> tmp(digits);
reverse(tmp.begin(),tmp.end());
vector<int> vec;
int N = tmp.size();
int sum = 0;
int i=0;
for(;i<N && tmp[i]==9;i++){
vec.push_back(0);
}
if(i==N){
vec.push_back(1);
}else{
vec.push_back(1+tmp[i++]);
for(;i<N;i++){
vec.push_back(tmp[i]);
}
}
reverse(vec.begin(),vec.end());
return vec;
}
}; | true |
261f73379edc464755a0320e33d04d843a0ebe89 | C++ | AlvioSim/kentosim | /src/statistics/median.h | UTF-8 | 772 | 2.84375 | 3 | [] | no_license | #ifndef STATISTICSMEDIAN_H
#define STATISTICSMEDIAN_H
#include <statistics/statisticalestimator.h>
#include <vector>
using namespace std;
using std::vector;
namespace Statistics {
/**
* @author Francesc Guim,C6-E201,93 401 16 50, <fguim@pcmas.ac.upc.edu>
*/
/**
* Implements the statistic of Median - given a set of values returns the median (non biased estimator of the average).
* @see the statisticalestimator class
*/
class Median : public StatisticalEstimator{
public:
Median();
~Median();
virtual Simulator::Metric* computeValue();
void setValues(vector< double >* theValue);
vector< double >* getvalues() const;
private:
vector<double>* values; /**< The reference to the vector that hols all the values to whom the stimator will be computed */
};
}
#endif
| true |
eff20ca55335e8940d7357805627f4e96514ef51 | C++ | originlake/leetcode | /src/c++/searchRange.cpp | UTF-8 | 1,038 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <conio.h>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
if (nums.empty()) return vector<int>{-1, -1};
vector<int> ans;
int n = nums.size();
int i = 0, j = n - 1, k = -1, m;
while (i <= j) {
m = (i + j) / 2;
if (nums[m] == target) {
k = m;
break;
}
else if (nums[m] < target) {
i = m+1;
}
else {
j = m - 1;
}
}
if (k == -1) return vector<int>{-1, -1};
else {
i = k;
j = k;
while (i - 1 >= 0 && nums[k] == nums[i - 1]) {
i--;
}
while (j + 1 < n&&nums[k] == nums[j + 1]) {
j++;
}
ans.push_back(i);
ans.push_back(j);
}
return ans;
}
};
int main() {
vector<int> a = {1,1,2,3,3,4,4,5,5,5,5,5,6,7,8,9,11 };
vector<int> b = Solution().searchRange(a, 1);
for (int i = 0; i < b.size(); i++) {
cout << b[i] << " ";
}
return 0;
}
| true |
29882f554c8ef76d2a146e743da8db77eb5360f2 | C++ | free-bit/PokeTournament-HW | /PokeWater.cpp | UTF-8 | 2,094 | 3.21875 | 3 | [] | no_license | #include "PokeWater.h"
PokeWater::PokeWater(int ID, const std::string& pokemonName): Pokemon(ID,pokemonName)
{
HP=700;
ATK=50;
MAG_DEF=10;
PHY_DEF=20;
drowning=false;
burning=false;
electrified=false;
rooted=false;
//Default values
defHP=700;
defATK=50;
defMAG_DEF=10;
defPHY_DEF=20;
}
void PokeWater::getDamage()//MAG-Attack (Attacked Pokemon)
{
if(isBurning() && HP>0)
{
cout<<"\t\t\t"<<name<<"("<<HP<<") "<<getEffectName(BURNING)<<"!!"<<endl;
setHP(getHP()-max(0,BURN_DAMAGE-getMAG_DEF()));
}
if(isElectrified() && HP>0)
{
cout<<"\t\t\t"<<name<<"("<<HP<<") "<<getEffectName(ELECTRIFIED)<<"!!!!"<<endl;
setHP(getHP()-max(0,ELECTRIFY_DAMAGE*2-getMAG_DEF()));
}
if(isRooted() && HP>0)
{
cout<<"\t\t\t"<<name<<"("<<HP<<") "<<getEffectName(ROOTED)<<"!!"<<endl;
setHP(getHP()-max(0,ROOT_DAMAGE-getMAG_DEF()));
}
}
void PokeWater::attackTo(Pokemon* target, Arena currentArena)//PHY-Attack (Attacking Pokemon)
{
int phyDam=max(1,ATK-target->getPHY_DEF());
string arena=getArenaName(currentArena);
target->setDrowning(true);
if(arena=="Ocean")
cout<<"\t\t\t"<<name<<"("<<HP<<") hit "<<target->getName()<<"("<<target->getHP()<<") "<<phyDam<<"(+)"<<endl;
else if(arena=="ElectriCity" || arena=="Forest")
cout<<"\t\t\t"<<name<<"("<<HP<<") hit "<<target->getName()<<"("<<target->getHP()<<") "<<phyDam<<"(-)"<<endl;
else
cout<<"\t\t\t"<<name<<"("<<HP<<") hit "<<target->getName()<<"("<<target->getHP()<<") "<<phyDam<<"(/)"<<endl;
target->setHP(target->getHP()-phyDam);
}
void PokeWater::levelUp()
{
HP+=70;
ATK+=5;
MAG_DEF+=1;
PHY_DEF+=2;
defHP+=70;
defATK+=5;
defMAG_DEF+=1;
defPHY_DEF+=2;
}
void PokeWater::buff(string arena)
{
if(arena=="Ocean")
(*this)++;
else if(arena=="ElectriCity" || arena=="Forest")
(*this)--;
else
;
}
PokeWater::~PokeWater()
{}
void PokeWater::setBurning(bool burning)
{
this->burning=burning;
}
void PokeWater::setDrowning(bool drowning)
{}
void PokeWater::setElectrified(bool electrified)
{
this->electrified=electrified;
}
void PokeWater::setRooted(bool rooted)
{
this->rooted=rooted;
} | true |
dc855ddebc9ff58552e93f82f9b153a2481a6c14 | C++ | Josh-G91/OOP-Projects | /Banking/savings.h | UTF-8 | 454 | 2.546875 | 3 | [] | no_license | //savings.h
#ifndef SAVINGS_H
#define SAVINGS_H
#include <string>
#include <iostream>
using namespace std;
#include "account.h"
class Savings : public Account
{
protected:
double interestRate;
public:
Savings();
Savings(Customer &c, double bal, double IRate);
virtual void makeDeposit(double deposit);
virtual bool makeWithdrawal(double withdrawal, double balance);
virtual void adjustBalance();
virtual void view();
};
#endif | true |
c96d38251f8f4417774e0ae765493e92192361ce | C++ | alexbie98/vm | /src/action/DirectionalMovementAction.cc | UTF-8 | 667 | 2.53125 | 3 | [] | no_license | #include "action/DirectionalMovementAction.h"
#include "state/State.h"
#include "state/File.h"
using namespace std;
namespace vm {
void DirectionalMovementAction::doAction(State& context){
context.getFile().moveCursor(d);
}
DirectionalMovementAction::DirectionalMovementAction(Direction d,
size_t multi, unique_ptr<Action> nextAction):
Action{multi, move(nextAction)}, d{d} {}
unique_ptr<Action> DirectionalMovementAction::clone(){
unique_ptr<Action> nextClone;
if (nextAction) nextClone = nextAction->clone();
return make_unique<DirectionalMovementAction>(d, multi,
move(nextClone));
}
DirectionalMovementAction::~DirectionalMovementAction() {}
}
| true |
af919efe9828568b64404b9e723986b351eefbf9 | C++ | Zadanka/pp_lista_1 | /zad16.cpp | UTF-8 | 609 | 3.28125 | 3 | [] | no_license | #include <iostream>
using namespace std;
float suma(float a, float b)
{
return a + b;
}
float roznica(float a, float b)
{
return a - b;
}
float iloczyn(float a, float b)
{
return a * b;
}
float iloraz(float a, float b)
{
return a / b;
}
float kwadrat(float a)
{
return a * a;
}
float szescian(float a)
{
return a * a * a;
}
float oblicz(float x)
{
float m1 = suma(iloczyn(10, szescian(x)), iloczyn(3.14, kwadrat(x)));
float m2 = roznica(iloraz(x, 3), iloraz(1, kwadrat(x)));
return iloczyn(m1, m2);
}
int main()
{
cout << oblicz(1.0) << endl;
return 0;
}
| true |
d9c3da3d7b7667ec4ed111ad68a7cced2193ec78 | C++ | Jshondra/CPP_modules | /cpp02/ex01/Fixed.hpp | UTF-8 | 536 | 2.75 | 3 | [] | no_license | #ifndef FIXED_HPP
#define FIXED_HPP
#include <cmath>
#include <iostream>
class Fixed
{
private:
int _fixed_n;
static const int _nbr_b = 8;
public:
Fixed();
Fixed( const int n );
Fixed( const float n );
Fixed( Fixed const & rhc );
~Fixed( void );
Fixed & operator=(Fixed const & rhc);
float toFloat( void ) const;
int toInt( void ) const;
int getRawBits( void ) const;
void setRawBits( int const src );
};
std::ostream& operator<<(std::ostream & str, const Fixed & rhc);
#endif | true |
c4be1c3b00308f2dc2bbaf786d8cf5bde22c25a3 | C++ | TheDoubleB/acpl | /src/Bits.h | UTF-8 | 1,026 | 2.859375 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef ACPL_BITS_H
#define ACPL_BITS_H
namespace acpl
{
class Bits
{
private:
inline Bits() { }
inline virtual ~Bits() { }
public:
template <class tType, class tTypeCompat>
static inline tType Get(const tType &nVar, const tTypeCompat &nMask)
{
return (nVar & static_cast<tType>(nMask));
}
template <class tType, class tTypeCompat>
static inline bool AllSet(const tType &nVar, const tTypeCompat &nMask)
{
return ((nVar & static_cast<tType>(nMask)) == static_cast<tType>(nMask));
}
template <class tType, class tTypeCompat>
static inline bool AnySet(const tType &nVar, const tTypeCompat &nMask)
{
return ((nVar & static_cast<tType>(nMask)) != static_cast<tType>(0));
}
template <class tType, class tTypeCompat>
static inline void Set(tType &nVar, const tTypeCompat &nMask, bool nVal)
{
if (nVal == true)
nVar |= static_cast<tType>(nMask);
else
nVar &= ~static_cast<tType>(nMask);
}
};
}
#endif // ACPL_BITS_H
| true |
24089178c26d189701e332970261ddeabd49d1c1 | C++ | aqc112420/ML-by-c | /ImageAugment.cpp | GB18030 | 2,326 | 2.90625 | 3 | [] | no_license | //c++ǿתȶԱȶȵģ
#include<opencv2\core\core.hpp>
#include<opencv2\highgui\highgui.hpp>
#include<opencv2\imgproc\imgproc.hpp>
#include<iostream>
#include<opencv2\core.hpp>
using namespace cv;
using namespace std;
void Resize(Mat &img, int rows, int cols)
{
resize(img, img, Size(rows, cols), 0, 0, INTER_NEAREST);
}
void random_flip(Mat &img)
{
//Mat dst;
const int arrayNum[4] = { 0, 0, 1, 2 };
int RandIndex = rand() % 4; //generates a random number between 0 and 3
cout << arrayNum[RandIndex] << endl;
if (arrayNum[RandIndex] == 1)
{
flip(img, img, 1);
//return dst;
}
else if (arrayNum[RandIndex] == 2)
{
flip(img, img, 0);
//return dst;
}
else
;
//return img;
}
void on_ContrastAndBright(Mat &img, int contrastValue=80, int brightValue=80)
{
for (int x = 0; x < img.rows; x++)
{
for (int y = 0; y < img.cols; y++)
{
for (int z = 0; z < 3; z++)
{
img.at<Vec3b>(x, y)[z] =
saturate_cast<uchar>((contrastValue*0.01)*(img.at<Vec3b>(x, y)[z]) + brightValue);
}
}
}
}
void RandomBlur(Mat &img, int min = 0, int max = 5)
{
int radius = rand() % max + min;
GaussianBlur(img, img, Size(radius, radius), 0, 0);
}
Mat AddRandomNoise(Mat &img, int sd = 5)
{
int noise_sd = rand() % sd;
cout << noise_sd << endl;
Mat dst;
if (noise_sd > 0)
{
Mat noise(img.size(), img.type());
RNG rng(time(NULL));
rng.fill(noise, RNG::NORMAL, 0, 36);
add(img, noise, dst);
}
else
{
dst = img;
}
return dst;
}
int main()
{
Mat img = imread("E:\\datasets\\aeroscapes\\JPEGImages\\000001_001.jpg");
if (img.empty())
{
cout << "Failed to read img" << endl;
system("pause");
exit(0);
}
for (int i = 0; i < 10; i++)
{
Mat dst = AddRandomNoise(img);
namedWindow("result", WINDOW_NORMAL);
imshow("result", dst);
waitKey(0);
}
system("pause");
return 0;
} | true |
83926e69a3969a093d9026c8c33832229124f251 | C++ | djrieger/mjplusplus | /src/ast/Statement.hpp | UTF-8 | 800 | 2.6875 | 3 | [] | no_license | #ifndef STATEMENT_HPP
#define STATEMENT_HPP
#include "Node.hpp"
#include "../semantic_analysis/SemanticAnalysis.hpp"
namespace ast
{
namespace stmt
{
class Statement : public Node
{
public:
enum Type
{
TYPE_SINGLE,
TYPE_BLOCK,
TYPE_IF
};
virtual Type getType() const;
/**
* @brief analyze a statement for semantic correctness, and recursivly analyze its children
* @return true iff all paths of this statement contsin a return statement
*/
virtual bool analyze(semantic::SemanticAnalysis& sa, shptr<semantic::symbol::SymbolTable> symboltable) const = 0;
virtual unsigned int countVariableDeclarations() const;
virtual void accept(ASTVisitor& visitor) const;
virtual int setVariablePositions(int) const;
};
}
}
#endif
| true |
77e95101fd190bb756481899cc7c0e8666603773 | C++ | aabin/mapmatrix3d-2.0 | /mm3dMapperEvent/nbspAlgorithm.h | UTF-8 | 889 | 2.9375 | 3 | [] | no_license | #pragma once
#include <math.h>
#include <vector>
namespace nbsp {
class pointXYZ {
public:
pointXYZ(double a = 0, double b = 0, double c = 0)
{
x = a; y = b; z = c;
}
pointXYZ operator-(pointXYZ other)
{
pointXYZ t;
t.x = x - other.x;
t.y = y - other.y;
t.z = z - other.z;
return t;
}
pointXYZ& operator=(pointXYZ other)
{
x = other.x;
y = other.y;
z = other.z;
return *this;
}
bool operator==(const pointXYZ &p1)const {
if (x == p1.x && y == p1.y && z == p1.z)
return true;
return false;
}
double x;
double y;
double z;
};
class CNbspAlgorithm
{
public:
void computePoly(std::vector<pointXYZ> vecPts, std::vector<pointXYZ>& vecOutPoly);
private:
float computeAngle(double ux, double uy, double uz, double vx, double vy, double vz,bool bfit = true);
};
} | true |
0d201b9b64ca8e06137d7563bf8796d5e3ec06ea | C++ | nick-keller/crusher_repack | /dialogs/brushselector.cpp | UTF-8 | 1,556 | 2.6875 | 3 | [] | no_license | #include "brushselector.h"
#include "ui_brushselector.h"
BrushSelector::BrushSelector(QWidget *parent) :
QDialog(parent), m_type(None),
ui(new Ui::BrushSelector)
{
ui->setupUi(this);
QObject::connect(ui->noFill, SIGNAL(clicked()), this, SLOT(setTypeNone()));
QObject::connect(ui->blackFill, SIGNAL(clicked()), this, SLOT(setTypeBlack()));
QObject::connect(ui->whiteFill, SIGNAL(clicked()), this, SLOT(setTypeWhite()));
QObject::connect(ui->patternFill, SIGNAL(clicked()), this, SLOT(setTypePattern()));
QObject::connect(ui->widthSelector, SIGNAL(valueChanged(int)), ui->patternMaker, SLOT(setWidth(int)));
QObject::connect(ui->heightSelector, SIGNAL(valueChanged(int)), ui->patternMaker, SLOT(setHeight(int)));
QObject::connect(ui->colorSelector, SIGNAL(currentIndexChanged(int)), ui->patternMaker, SLOT(setColor(int)));
}
BrushSelector::~BrushSelector()
{
delete ui;
}
void BrushSelector::setType(BrushSelector::FillType type)
{
m_type = type;
switch (type) {
case None:
ui->noFill->click();
break;
case Black:
ui->blackFill->click();
break;
case White:
ui->whiteFill->click();
break;
case Pattern:
ui->patternFill->click();
break;
}
}
QPixmap BrushSelector::getPattern()
{
return ui->patternMaker->getPattern();
}
void BrushSelector::setPattern(QPixmap pixmap)
{
ui->widthSelector->setValue(pixmap.width());
ui->heightSelector->setValue(pixmap.height());
ui->patternMaker->setPattern(pixmap);
}
| true |
092697810e867875f66c8f50ac46b592cf32437a | C++ | psimn/Learning-Cpp | /ex3.23.cpp | UTF-8 | 301 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <vector>
int main() {
std::vector<int> ivec{1, 2, -85, 65, 42, -3, 7, 6, 50, 655};
for (auto it = ivec.begin(); it != ivec.end(); ++it) {
*it *= 2;
}
for (auto it = ivec.cbegin(); it != ivec.cend(); ++it) {
std::cout << *it << std::endl;
}
return 0;
} | true |
28f63df3ea4f3e4e84d16e9ae6898b7d4bc13bf9 | C++ | Ikaguia/maratona | /uFind.cpp | UTF-8 | 1,460 | 2.59375 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
#include <math.h>
using namespace std;
#define FOR(cont,max) for(int (cont)=0; (cont)<(int)(max);(cont)++)
#define FOR2(cont,start,max) for(int (cont)=(start); (cont)<(int)(max);(cont)++)
#define ABS(x) (((x)> 0 ) ? (x) :-(x))
#define MAX(x,y) (((x)>(y)) ? (x) : (y))
#define MIN(x,y) (((x)<(y)) ? (x) : (y))
#define BETWEEN(x,a,b) (((x)>=(a)) && ((x)<(b)))
#define SWAP(a,b) int _temp_=(a);(a)=(b);(b)=_temp_;
#define RAND(max) (rand()%(max))
#define RAND2(min,max) (min)+(rand()%((max)-(min)))
struct uFind{
const int size;
int cnt,*id,*sz;
uFind(int n):cnt{n},size{n}{
id=new int[n];
sz=new int[n];
FOR(i,n){
id[i]=i;
sz[i]=1;
}
};
~uFind(){
delete[] id;
delete[] sz;
}
int find(int p){
if(id[p]==p)return p;
return id[p]=find(id[p]);
}
bool connected(int a,int b){
return find(a)==find(b);
}
void merge(int a,int b){
int i=find(a);
int j=find(b);
if(i==j)return;
if(sz[i]>sz[j]){
id[j]=i;
}
else{
id[i]=j;
if(sz[i]==sz[j])sz[j]++;
}
cnt--;
}
};
//programa teste, le um grafo com n vértices, m arestas e faz o queries sobre ele para ver se dois vertices são conexos
int main(){
int n,x,y;
scanf(" %d %d",&n,&m,&o);
uFind(n) u;
FOR(i,m){
scanf(" %d %d",&x,&y);
u.merge(x,y);
}
FOR(i,o){
scanf(" %d %d",&x,&y);
if(u.connected(x,y))printf("Caso %d: Sim\n",i+1);
else printf("Caso %d: Não\n",i+1);
}
return 0;
}
| true |
694c08a3f5408a5a294d28414987dcb57e077242 | C++ | sandalovsergey/fractal | /Func.cpp | UTF-8 | 496 | 2.703125 | 3 | [] | no_license | #include "stdafx.h"
#include "Func.h"
COMPLEX Create(double a, double b)
{
COMPLEX res;
res.Re = a;
res.Im = b;
return res;
}
COMPLEX ComplAddCompl(COMPLEX a, COMPLEX b) {
COMPLEX res;
res.Re = a.Re + b.Re;
res.Im = a.Im + b.Im;
return res;
}
COMPLEX ComplMultCompl(COMPLEX a, COMPLEX b) {
COMPLEX res;
res.Re = a.Re * b.Re - a.Im * b.Im;
res.Im = a.Re * b.Im + a.Im * b.Re;
return res;
}
double Abs(COMPLEX z) {
double res;
res = sqrt(z.Re * z.Re + z.Im * z.Im);
return res;
} | true |
091dfb3960194f929221df9d980b60255512da87 | C++ | SamuelLouisCampbell/chili_framework-1 | /Engine/Scene_FontRendering.cpp | UTF-8 | 2,305 | 3.0625 | 3 | [] | no_license | #include "Scene_FontRendering.h"
#include "Logger.h"
#include <sstream>
#include <algorithm>
Scene_FontRendering::Scene_FontRendering( Keyboard & Kbd, Graphics & Gfx )
:
Scene( Kbd, Gfx )
{
TextFormat::Properties props;
props.fontname = L"Consolas";
props.size = 18.f;
m_consola = Font{ props };
const auto longString = std::string( "\tI'm going to write a long string and try to word wrap this shit, like it's as easy as fucking a whore.\n\nI hope this works." );
Text::TextLayout layout;
layout.align_v = Text::Alignment_V::Middle;
m_text = Text( longString, layout, Rectf( 0.f, 0.f, Sizef( 300.f, 600.f ) ), m_consola );
{
m_marqueePos = Vec2f( 800.f, static_cast< float >( Graphics::GetHeight<int>() - m_consola.GetCharSize().height ) );
const std::string marqueeStr = "This is some scrolling text along the bottom to test out text clipping capabilities.";
const auto rect = Text::EstimateMinRect( marqueeStr, m_consola, Graphics::GetRect<float>() );
auto layout = Text::TextLayout();
layout.endofline = Text::EndOfLine::None;
m_marqueeText = Text( marqueeStr, layout, rect, m_consola );
}
}
void Scene_FontRendering::Update( float DeltaTime )
{
fps = 1.f / DeltaTime;
const auto strPixelLen = m_marqueeText.GetActualBoundary().GetWidth();
const auto speed = 200.f;
m_marqueePos.x -= speed * DeltaTime;
const auto strEnd = m_marqueePos.x + strPixelLen;
if( strEnd <= 0.f )
{
m_marqueePos.x = Graphics::GetSize<float>().width;
}
}
void Scene_FontRendering::Draw() const
{
// Marquee ( scrolling text ) works with the Text class if you use EndOfLine::None
m_graphics.DrawText( m_marqueePos, m_marqueeText, Colors::White );
// Recommended approach, make one instance and reuse.
m_graphics.DrawText( { 0.f, 0.f }, m_text, Colors::Green );
// Not recommended for long strings, but might be ok for short strings.
{
std::stringstream ss;
ss << "FPS: " << fps;
const auto fpsStr = ss.str();
const auto rect = Text::EstimateMinRect( fpsStr, m_consola, Graphics::GetRect<float>() );
const Vec2f pos = { 0.f, 0.f };
Text::TextLayout layout;
layout.endofline = Text::EndOfLine::None;
Text text( fpsStr, layout, rect, m_consola );
m_graphics.DrawText( { pos.x, pos.y + m_consola.GetCharSize().height }, text, Colors::Yellow );
}
}
| true |
23ee51f5f0b2c2d4e6d1295695b49ef89bbbcc62 | C++ | diseraluca/CompetitiveProgramming | /Sites/HackerRank/Arrays_Left_Rotation/C++/Arrays_Left_Rotation/Arrays_Left_Rotation/Arrays_Left_Rotation.cpp | UTF-8 | 878 | 2.96875 | 3 | [
"MIT"
] | permissive | // Copyright 2018 Luca Di Sera
// Contact: disera.luca@gmail.com
// https://github.com/diseraluca
// https://www.linkedin.com/in/luca-di-sera-200023167
//
// This code is licensed under the MIT License.
// More informations can be found in the LICENSE file in the root folder of this repository
//
// Solution to: https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem
//
// 09-10-2018 16:43 : Verdict accepted
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main() {
int size, rotations;
std::cin >> size >> rotations;
std::vector<int> arr{}; arr.reserve(size);
std::copy_n(std::istream_iterator<int>(std::cin), size, back_inserter(arr));
std::vector<int> nArr{}; nArr.resize(size);
for (int i{ 0 }; i < size; ++i) {
nArr[((i + (size - rotations)) % size)] = arr[i];
}
for (auto a : nArr) {
std::cout << a << ' ';
}
} | true |
93c30be49d300085436e582189b74fe9506813c7 | C++ | tliu526/ireg_CA | /RegularGridGenerator.cpp | UTF-8 | 4,346 | 2.890625 | 3 | [] | no_license | /**
Implementation of the RegularGridGenerator.
(c) 2016 Tony Liu.
*/
#include "RegularGridGenerator.h"
#include <cmath>
using namespace std;
const float RegularGridGenerator::OFFSET = 0.5;
RegularGridGenerator::RegularGridGenerator(int mi_x, int ma_x, int mi_y, int ma_y, bool b, int degen) {
min_x = mi_x;
max_x = ma_x;
max_y = ma_y;
min_y = mi_y;
is_toroidal = b;
degeneracy = degen;
init_grid();
init_maps();
generate_graph();
if(degeneracy>0){
map_faces();
degenerate_grid();
generate_graph();
}
grid_type = "Regular";
}
void RegularGridGenerator::init_grid() {
//initialize gen_pts, verts, edges, grid_array
for(int i = min_x; i <= max_x; i++){
//initialize top-down, left-right
for(int j = max_y; j >= min_y; j--){
if(i < max_x && j > min_y) {
float x = i+OFFSET;
float y = j-OFFSET;
Point gen_pt(x, y);
gen_pts.push_back(gen_pt);
if (i < max_x-1) gen_edges.push_back(Edge(gen_pt, Point(x+1,y)));
else if (is_toroidal) gen_edges.push_back(Edge(gen_pt, Point(min_x + OFFSET,y)));
if (j > min_y+1) gen_edges.push_back(Edge(gen_pt, Point(x,y-1)));
else if (is_toroidal) gen_edges.push_back(Edge(gen_pt, Point(x,max_y-OFFSET)));
}
Point v(Point(i, j));
verts.push_back(v);
if(i < max_x) edges.push_back(Edge(v, Point(i+1, j)));
if(j > min_y) edges.push_back(Edge(v, Point(i, j-1)));
}
}
//initialize faces
for(size_t i = 0; i < gen_pts.size(); i++){
faces.push_back(construct_square(gen_pts[i]));
}
}
Poly RegularGridGenerator::construct_square(Point &gen_pt){
vector<Edge> edges;
Point p1(gen_pt.x-OFFSET, gen_pt.y+OFFSET);
Point p2(gen_pt.x-OFFSET, gen_pt.y-OFFSET);
Point p3(gen_pt.x+OFFSET, gen_pt.y+OFFSET);
Point p4(gen_pt.x+OFFSET, gen_pt.y-OFFSET);
edges.push_back(Edge(p1,p2));
edges.push_back(Edge(p1,p3));
edges.push_back(Edge(p3,p4));
edges.push_back(Edge(p2,p4));
return Poly(edges);
}
//pre: init_maps has been called
void RegularGridGenerator::generate_graph() {
graph = Graph<string,Cell>();
typename map<Point, string>::iterator map_it;
for(map_it = rev_gen_pt_map.begin(); map_it != rev_gen_pt_map.end(); map_it++) {
graph.add_vertex(map_it->second, Cell(map_it->first, map_it->second));
}
for(size_t i = 0; i < gen_edges.size(); i++){
string p1 = rev_gen_pt_map[gen_edges[i].p];
string p2 = rev_gen_pt_map[gen_edges[i].q];
graph.add_edge(p1,p2);
}
graph.print_adj_list();
}
int RegularGridGenerator::degenerate_grid(){
if(degeneracy == 0) return 0;
vector<string> keys;
for(map<string, string>::iterator map_it = gen_pt_face_map.begin(); map_it != gen_pt_face_map.end(); map_it++){
keys.push_back(map_it->first);
}
default_random_engine gen;
gen.seed(degeneracy);
shuffle(keys.begin(), keys.end(), gen);
int num_faces_to_remove = int((float(degeneracy)/float(100))*keys.size());
//cout << "Number of faces to remove: " << num_faces_to_remove << endl;
for(int i = 0; i < num_faces_to_remove; i++){
string rm_key = keys[i];
vector<Edge>::iterator iter = gen_edges.begin();
Poly face = face_map[gen_pt_face_map[rm_key]];
cout << pt_map[rm_key] << endl;
while(iter != gen_edges.end()){
if(iter->contains(pt_map[rm_key])){
//cout << "Erasing" << endl;
gen_edges.erase(iter);
}
else{
iter++;
}
}
gen_pts.erase(remove(gen_pts.begin(), gen_pts.end(), pt_map[rm_key]), gen_pts.end());
gen_pt_face_map.erase(rm_key);
rev_gen_pt_map.erase(pt_map[rm_key]);
}
return num_faces_to_remove;
}
/**
int main(int argc, char**argv){
if (argc < 2){
cout << "Provide degen amt" << endl;
return -1;
}
int degen = atoi(argv[1]);
RegularGridGenerator gen(0,64,0,64, true, degen);
gen.grid_to_file("degen_reg_"+to_string(degen));
gen.grid_to_dot("degen_reg_"+to_string(degen));
return 0;
}
*/ | true |
dc278bbb6ab34b1525fd9da5c506cc357f1cc755 | C++ | Rolight/Gao | /LeetCode/732. My Calendar III.cpp | UTF-8 | 2,162 | 3.390625 | 3 | [] | no_license | #include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
class SegNode {
public:
SegNode *lc, *rc;
int val;
int lazy;
SegNode() : lc(NULL), rc(NULL), val(0), lazy(0) {}
};
class MyCalendarThree {
void delete_tree(SegNode *root) {
if (root == NULL) return;
delete_tree(root->lc);
delete_tree(root->rc);
delete root;
}
void push_up(SegNode *rt) {
if (rt->lc != NULL) rt->val = max(rt->lc->val, rt->val);
if (rt->rc != NULL) rt->val = max(rt->rc->val, rt->val);
}
void push_down(SegNode *rt) {
if (rt->lazy == 0) return;
if (rt->lc == NULL) {
rt->lc = new SegNode();
}
if (rt->rc == NULL) {
rt->rc = new SegNode();
}
rt->lc->lazy += rt->lazy;
rt->rc->lazy += rt->lazy;
rt->lc->val += rt->lazy;
rt->rc->val += rt->lazy;
rt->lazy = 0;
}
void update(SegNode *rt, int l, int r, int ql, int qr) {
if (ql <= l && qr >= r) {
rt->lazy += 1;
rt->val += 1;
} else {
int mid = (l + r) / 2;
push_down(rt);
if (ql <= mid) {
if (rt->lc == NULL) rt->lc = new SegNode();
update(rt->lc, l, mid, ql, qr);
}
if (qr > mid) {
if (rt->rc == NULL) rt->rc = new SegNode();
update(rt->rc, mid + 1, r, ql, qr);
}
push_up(rt);
}
}
SegNode *root;
int N;
public:
MyCalendarThree() {
root = new SegNode();
N = 1e9;
}
~MyCalendarThree() { delete_tree(root); }
int book(int start, int end) {
update(root, 0, N, start, end - 1);
return root->val;
}
};
/**
* Your MyCalendarThree object will be instantiated and called as such:
* MyCalendarThree obj = new MyCalendarThree();
* int param_1 = obj.book(start,end);
*/
int main() {
MyCalendarThree *c = new MyCalendarThree();
int l, r;
while (cin >> l >> r) {
cout << c->book(l, r) << endl;
}
return 0;
} | true |
dd812ab28ada575487c6145aa6e3581860dc98e3 | C++ | Prudhviyendluri/Data-Structures | /Dspgm/Queue_using_doubly_linked_list/main.cpp | UTF-8 | 917 | 3.234375 | 3 | [] | no_license | #include "Queue_doubly_Linked_List.h"
#include <string>
using namespace std;
int main(){
Queue_doubly_Linked_List<int> q;
string cmd;
int data;
while(1){
try{
cin >> cmd;
if(cmd == "push" ) cin >> data;
if(cmd == "push" ) q.push(data);
else if(cmd == "pop" ) q.pop();
else if(cmd == "size" ) cout << q.size() << endl;
else if(cmd == "print" ) cout << q << endl;
else if(cmd == "front" ) cout << q.front() << endl;
else if(cmd == "set_front") cin >> data, q.front() = data;
else if(cmd == "set_back" ) cin >> data, q.back() = data;
else if(cmd == "back" ) cout << q.back() << endl;
else if(cmd == "exit" ) break;
else cerr << "Wrong command" << endl;
}
catch(const overflow_error& e) { cerr << e.what() << endl; }
catch(const underflow_error& e){ cerr << e.what() << endl; }
}
return 0;
}
| true |
e7c3b4eeb19355af865b809b2431a6b06151fdab | C++ | lilijreey/class | /stl/it.cpp | UTF-8 | 1,911 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <iterator>
#include <forward_list>
#include <list>
#include <assert.h>
#include <set>
//template <typename Iter>
//void MyAdvance(Iter &it, int n)
//{
//for (int i = 0; int i < n; ++int i)
//{
//++it;
//}
//}
int main() {
std::list<int> v{1,2,3,4,5,6};
auto it = v.begin();
auto it2 = std::next(v.begin(), 3);
std::cout << std::distance(it, it2) << std::endl;
it2 = std::prev(it2, 3);
std::cout << std::distance(it2, v.begin()) << std::endl;
#if 0
std::vector<int> v{1,2,3,4,5,6};
auto it = std::next(v.begin(), 3);
assert(*it == 4);
it = std::next(it);
assert(*it == 5);
it = std::next(it,-2);
assert(*it == 3);
int step = 3;
assert(step == distance(v.begin(),
next(v.begin(), step),
std::vector<int> v{1,2,3,4,5,6};
auto it = v.begin();
//auto it2 = v.begin() + 3;
//auto it2 = it;
//std::advance(it2, 3);
auto it2 = it + 3;
assert(*it2 == 4);
std::cout << std::distance(it , it2) << std::endl;
std::cout << std::distance(it2 , it) << std::endl;
std::forward_list<int> fl ={1,2,3,4};
//auto fit = fl.begin();
//std::advance(fit, 2);
//std::cout << std::distance(fit, fl.begin())
// << std::endl;
//int step = 3;
//auto l = fl.begin();
//auto r = fl.begin();
//advance(r, step);
//assert(step == distance(l, r));
//std::list<int> l{1,2,3,4,3,5,4};
//std::cout << l.size() << std::endl;
//std::forward_list<int> fl = {1,2,3,4,3,5,4};
////std::cout << fl.size() << std::endl;
//std::cout << "size: "
// << std::distance(fl.begin(), fl.end())
// << std::endl;
//std::vector<int> v{ 3, 1, 4 };
//std::forward_list<int> v{ 3, 1, 4 };
//auto vi = v.begin();
//vi += 2;
////std::advance(vi, 2);
//std::advance(vi, -2);
////assert(vi == v.end());
//std::cout << *vi << '\n';
#endif
}
| true |
275219f7165d3379c6797b782998b18b0e08fa16 | C++ | tfrichard/leetcode | /maximalRectangle.cxx | UTF-8 | 805 | 2.671875 | 3 | [] | no_license | class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int res = 0;
int m = matrix.size();
if (m == 0) return res;
int n = matrix[0].size();
if (n == 0) return res;
int dp[m][n];
fill(&dp[0][0], &dp[m][0], 0);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
dp[i][j] = j > 0 ? dp[i][j-1] + 1 : 1;
}
}
}
int min = dp[0][0];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
min = dp[i][j];
int k = i;
while (k >= 0) {
if (min > dp[k][j]) min = dp[k][j];
res = max(res, min * (i - k + 1));
k--;
}
}
}
return res;
}
};
| true |
4f2c2f181a2dd41d93b1a35179df6037cc7c3475 | C++ | fivaladez/Learning-C- | /34_Namespace.cpp | UTF-8 | 1,301 | 3.890625 | 4 | [] | no_license | /*
Using namespace, you can define the context in which names are defined.
In essence, a namespace defines a scope.
Discontiguous Namespaces
A namespace can be defined in several parts and so a namespace is made up of
the sum of its separately defined parts. The separate parts of a namespace
can be spread over multiple files.
Nested Namespaces
Namespaces can be nested where you can define one namespace inside another name space
*/
#include <iostream>
using namespace std;
// first name space
namespace first_space {
void func() {
cout << "Inside first_space" << endl;
}
// second name space
namespace first_space_2 {
void func() {
cout << "Inside first_space_2" << endl;
}
}
}
// second name space
namespace second_space {
void func() {
cout << "Inside second_space" << endl;
}
}
// third name space
namespace third_space {
void func() {
cout << "Inside third_space" << endl;
}
}
using namespace third_space;
int main () {
// Calls function from first name space.
first_space::func();
// Calls function from second name space.
second_space::func();
// Calls function from third name space.
func();
// Calls function from nested first name space
first_space::first_space_2::func();
return 0;
}
| true |
8454e7accac4328e7c5b1deb43c02592cdfd7fdb | C++ | zero-fox/battleship2.0 | /ship.h | UTF-8 | 921 | 2.8125 | 3 | [] | no_license | #ifndef SHIP_H_INCLUDED
#define SHIP_H_INCLUDED
#include <SFML/Graphics.hpp>
#include <SFML/Network.hpp>
#include <SFML/Window.hpp>
#include <iostream>
#include <cmath>
#include "gun.h"
class Ship{
public:
Ship(); //set the origin for sprite
sf::Vector2f get_position();
float get_speed();
float get_rotation_speed();
int get_health();
float get_direction();
sf::Sprite ship_image;
sf::Texture sTexture;
void move_forward(float elapsed); //elapsed time as seconds
void rotate_cw(float elapsed);
void rotate_ccw(float elapsed);
void move_backwards(float elapsed);
void teleport();
void fire_gun();
void refresh_gun();
void change_guns_direction(float new_angle);
Gun gun1;
private:
sf::Vector2f position;
float speed;
float rotation_speed;
int health;
float direction;
float brotation_speed;
};
#endif // SHIP_H_INCLUDED
| true |
fceb7cb9de895659f1faead68bb5e8c892d07d8f | C++ | jlstr/acm | /438 - The circumference of the cirlce/438.cpp | UTF-8 | 585 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include<stdio.h>
#include<math.h>
using namespace std;
struct point{
double x;
double y;
point(double X,double Y){
x=X;
y=Y;
}
};
double operator |(point &a,point &b){
//return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
return hypot(a.x-b.x, a.y-b.y);
}
const double pi = 2*acos(0);
int main(){
double x1,x2,x3,y1,y2,y3;
while(cin>>x1>>y1>>x2>>y2>>x3>>y3){
point p(x1,y1);
point q(x2,y2);
point r(x3,y3);
printf("%.2f\n",fabs(pi*(q|r)*(p|q)*(p|r)/((q.x-p.x)*(r.y-p.y)-(q.y-p.y)*(r.x-p.x))));
}
return 0;
}
| true |
efb36333b50668611d4319e5f0aa901ed1f47338 | C++ | wuwushrek/embedded_outer_ode | /aa/interval.cpp | UTF-8 | 2,214 | 3.21875 | 3 | [] | no_license | #include "interval.h"
#include <algorithm>
using namespace std;
Interval::Interval(real val)
{
this->l_elem = val;
this->r_elem = val;
}
Interval::Interval(real lo , real hi)
{
assert_af(lo <= hi);
this->l_elem = lo;
this->r_elem = hi;
}
Interval::Interval(const Interval &it)
{
this->l_elem = it.l_elem;
this->r_elem = it.r_elem;
}
real Interval::getCenter() const
{
return (this->l_elem + this->r_elem) / 2;
}
real Interval::getMin() const
{
return this->l_elem;
}
real Interval::getMax() const
{
return this->r_elem;
}
real Interval::getRadius() const
{
return (this->r_elem - this->l_elem)/2;
}
real Interval::getRange() const
{
return (this->r_elem - this->l_elem);
}
Interval & Interval::operator = (const Interval &it)
{
this->l_elem = it.l_elem;
this->r_elem = it.r_elem;
return *this;
}
Interval Interval::operator + (const Interval &it) const
{
Interval temp(*this);
temp.r_elem += it.r_elem;
temp.l_elem += it.l_elem;
return temp;
}
Interval Interval::operator - (const Interval &it) const
{
Interval temp(*this);
temp.r_elem -= it.l_elem;
temp.l_elem -= it.r_elem;
return temp;
}
Interval Interval::operator * (const Interval &it) const
{
real x1 = this->l_elem * it.l_elem;
real x2 = this->l_elem * it.r_elem;
real x3 = this->r_elem * it.l_elem;
real x4 = this->r_elem * it.r_elem;
return Interval(min(x1 , min(x2 , min(x3 , x4))), max(x1 , max(x2 , max(x3 , x4))));
}
Interval Interval::operator / (const Interval &it) const
{
assert_af(it.l_elem * it.r_elem > 0);
return *this * Interval(1.0f/it.r_elem , 1.0f/it.l_elem);
}
Interval & Interval::operator += (const Interval &it)
{
this->l_elem += it.l_elem;
this->r_elem += it.r_elem;
return *this;
}
Interval & Interval::operator -= (const Interval &it)
{
this->l_elem -= it.r_elem;
this->r_elem -= it.l_elem;
return *this;
}
#ifdef VERBOSE
void Interval::print_it(FILE *file)
{
if (file != NULL){
fprintf(file ,"%f\t%f\n", this->getMin() , this->getMax());
return ;
}
printf("it = [%f , %f] \n", this->getMin() , this->getMax());
}
#endif
uint8_t subseteq(const Interval &it1 , const Interval &it2)
{
if (it1.r_elem <= it2.r_elem && it1.l_elem >= it2.l_elem)
return 1;
return 0;
} | true |
ce2d17adbdeb2ed6a99570154b8fbc01e2b0087e | C++ | AnatoliiShablov/DA_utils | /main.cpp | UTF-8 | 1,491 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include "format.hpp"
int main() {
std::cout << da::utils::format("This is string with bools: {0} and {1}", true, false) << std::endl;
std::cout << da::utils::format("This is string with ints and floats: {2} and {1} and {0}", 5.5f, 3.0, 12) << std::endl;
std::cout << da::utils::format("This is string with char: {0}", 'a') << std::endl;
std::cout << da::utils::format("This is string with some escapes: %{0%} %%%% %%{0}", 'a') << std::endl;
try {
std::cout << da::utils::format("Line finishs with %") << std::endl;
} catch (std::runtime_error const& error) {
std::cout << error.what() << std::endl;
}
try {
std::cout << da::utils::format("Too big pos {9999999999999999999999999999999999999999999999999999999999999999999}")
<< std::endl;
} catch (std::runtime_error const& error) {
std::cout << error.what() << std::endl;
}
try {
std::cout << da::utils::format("Not escaped {") << std::endl;
} catch (std::runtime_error const& error) {
std::cout << error.what() << std::endl;
}
try {
std::cout << da::utils::format("Not escaped }") << std::endl;
} catch (std::runtime_error const& error) {
std::cout << error.what() << std::endl;
}
try {
std::cout << da::utils::format("Smth bad in {%}") << std::endl;
} catch (std::runtime_error const& error) {
std::cout << error.what() << std::endl;
}
}
| true |