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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
dc60c2ce8d50d7e5aadd24b3fdebe72bf3be499d | C++ | avmovie/learning-notes | /notepad/searchdialog.cpp | UTF-8 | 2,481 | 2.703125 | 3 | [] | no_license | #include "searchdialog.h"
SearchDialog::SearchDialog(Config *config, QWidget *parent) :
QWidget(parent), config(config)
{
setupUi(this);
setWindowIcon(QIcon(tr(":images/notepad.png")));
setWindowTitle(tr("Search & Replace"));
findCombo->setMaxCount(config->maxHistory);
findCombo->addItems(config->findHistory);
findCombo->setCurrentIndex(-1);
replaceCombo->setMaxCount(config->maxHistory);
replaceCombo->addItems(config->replaceHistory);
replaceCombo->setCurrentIndex(-1);
matchCaseCheck->setChecked(config->matchCase);
regExpCheck->setChecked(config->regExp);
connect(findNextButton, SIGNAL(clicked()), SLOT(search()));
connect(findPreviousButton, SIGNAL(clicked()), SLOT(search()));
connect(replaceNextButton, SIGNAL(clicked()), SLOT(replace()));
connect(replacePreviousButton, SIGNAL(clicked()), SLOT(replace()));
connect(replaceAllButton, SIGNAL(clicked()), SLOT(replace()));
}
SearchDialog::~SearchDialog()
{
config->matchCase = matchCaseCheck->isChecked();
config->regExp = regExpCheck->isChecked();
config->findHistory.clear();
for (int i = 0; i < findCombo->count(); i++)
config->findHistory << findCombo->itemText(i);
config->replaceHistory.clear();
for (int i = 0; i < replaceCombo->count(); i++)
config->replaceHistory << replaceCombo->itemText(i);
}
//查找
void SearchDialog::search()
{
update (findCombo);
bool backward = (sender() == findPreviousButton) ? true : false;
emit search(findCombo->currentText(), backward, matchCaseCheck->isChecked(),
regExpCheck->isChecked());
}
//替换
void SearchDialog::replace()
{
update (findCombo);
update (replaceCombo);
if (sender() == replaceAllButton)
{
emit replaceAll(findCombo->currentText(), replaceCombo->currentText(),
matchCaseCheck->isChecked(), regExpCheck->isChecked());
}
else
{
bool backward = (sender() == replacePreviousButton) ? true : false;
emit replace(findCombo->currentText(), replaceCombo->currentText(),
backward, matchCaseCheck->isChecked(),
regExpCheck->isChecked());
}
}
//更新查找/替换历史
void SearchDialog::update(QComboBox *combo)
{
int index = combo->findText(combo->currentText());
if (index == -1)
combo->insertItem(0, combo->currentText());
else
combo->setCurrentIndex(index);
}
| true |
44946c2c168e1ad2a0e371043b6abf62aeaf2f8c | C++ | balramsingh54/CompCod | /c++/pattern/india.cpp | UTF-8 | 221 | 2.625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
string str="INDIA";
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < i; j++)
{
cout<<str[j];
}
cout<<endl;
}
return 0;
} | true |
575bf28ce02faff3bf766b27ce3af333a32ed0b7 | C++ | Rennelovessleeping/LeetCode_Adventure | /BackTracing/291-WordPatternII.cpp | UTF-8 | 1,637 | 3.125 | 3 | [] | no_license | /**************************************************************************
* File Name : 291-WordPatternII.cpp
*
* Purpose :
*
* Creation Date : 26-04-2017
*
* Last Modified : Wed Apr 26 23:14:38 2017
*
* Created By : Renne Bai
**************************************************************************/
class Solution {
public:
unordered_map<char, string> pDict; // mapping : char -> word
unordered_map<string, char> sDict; // mapping : substr -> char
bool wordPatternMatch(string pattern, string str) {
return dfs(pattern,0,str,0);
}
bool dfs(const string& pattern, int i, const string& str, int pos) {
int pattern_len = pattern.size();
int str_len = str.length();
bool ins = false;
if(i == pattern_len || pos == str_len){
if(i == pattern_len && pos == str_len) return true;
else return false;
}
for(int j=pos; j<str_len; j++) {
string tmp = str.substr(pos, j-pos+1);
if(pDict.find(pattern[i]) != pDict.end()){
if (pDict[pattern[i]] != tmp) continue;
}
else if(sDict.find(tmp) != sDict.end()){
if (sDict[tmp] != pattern[i]) continue;
}
else {
pDict[pattern[i]] = tmp;
sDict[tmp] = pattern[i];
ins = true;
}
if(dfs(pattern, i+1, str, j+1)) return true;
if(ins) {
pDict.erase(pattern[i]);
sDict.erase(tmp);
}
}
return false;
}
};
| true |
b4b9ea4ba7daafaca7f0232af9fd78ab7fcb3c2d | C++ | rohannarde/configurationpuzzles | /JamPuzzle.cpp | UTF-8 | 7,668 | 2.84375 | 3 | [] | no_license | // File: $Id: JamPuzzle.cpp,v 1.2 2011/05/06 00:08:23 rsn5770 Exp $
// Author: Anand Rathod
// Description: Contains the main method to initiate the Traffic
//Jam puzzle and take input values from user.
// Revisions:
// $Log: JamPuzzle.cpp,v $
// Revision 1.2 2011/05/06 00:08:23 rsn5770
// Function removed .
// Indentations checked.
// Destructor added.
//
// Revision 1.1 2011/05/06 00:03:46 p334-70c
// Initial revision
//
// Revision 1.1 2011/04/03 18:25:05 agr5046
// Initial revision
//
//
#include "JamPuzzle.h"
using namespace std;
// Constructor for input of initial time, destination time and number
// of hours on the dial.
JamPuzzle::JamPuzzle(const int & dimension1, const int & dimension2,
const vector< vector<int> > carPositions,
const set<int> freeSpaceInLot,
const vector< vector <int> > move,
const vector< vector<int> > & path)
:_dimension1(dimension1), _dimension2(dimension2), cars(carPositions),
freeSpace(freeSpaceInLot),
pathForDestination(path)
{
for(int i=0; i<move.size(); i++)
{
pathForDestination.push_back(move[i]);
}
}
// condition to check whether the conditions are met or not.
bool JamPuzzle::IsPuzzleComplete() const
{
vector<int> temp = cars[cars.size()-1];
if( (temp[2]+1) % _dimension2 == 0)
return true;
else
return false;
}
// Returns the trace of path for solution.
vector<vector<int> > JamPuzzle::pathForSolution() const
{
return pathForDestination;
}
// Returns the possible moves for that point.
void JamPuzzle::getPossibleMoves(list<JamPuzzle> & possibleMoves)
{
for(unsigned int i=0; i< cars.size(); i++)
{
vector<int> carMove;
vector< vector<int> > movesMade;
//Vertical movements
if(cars[i][0] == 0)
{
set<int> freePos = freeSpace;
vector< vector<int> > carTemp = cars;
//check for top free spaces.
int top = cars[i][1] - _dimension1;
while (top >=0 && freePos.find(top)!=freePos.end())
{
vector<int> carDimensions = carTemp[i];
carMove.push_back(i);
carMove.push_back(carDimensions[1]);
carMove.push_back(carDimensions[2]);
carMove.push_back(carDimensions[1] -
_dimension1);
carMove.push_back(carDimensions[2] -
_dimension1);
movesMade.push_back(carMove);
freePos.erase(top);
freePos.insert(carDimensions[2]);
carDimensions[1] = carDimensions[1] - _dimension1;
carDimensions[2] = carDimensions[2] - _dimension1;
carTemp[i] = carDimensions;
JamPuzzle newCarMove(_dimension1, _dimension2,
carTemp, freePos, movesMade,
pathForDestination);
possibleMoves.push_back(newCarMove);
carMove.clear();
top = top - _dimension1;
}
carTemp.clear();
carTemp = cars;
freePos.clear();
freePos = freeSpace;
movesMade.clear();
//check for bottom free spaces.
int bottom = cars[i][2] + _dimension1;
while (bottom <= ((_dimension1 * _dimension2) - 1)
&& freePos.find(bottom)!=freePos.end())
{
vector<int> carDimensions = carTemp[i];
carMove.push_back(i);
carMove.push_back(carDimensions[1]);
carMove.push_back(carDimensions[2]);
carMove.push_back(carDimensions[1] + _dimension1);
carMove.push_back(carDimensions[2] + _dimension1);
movesMade.push_back(carMove);
freePos.erase(bottom);
freePos.insert(carDimensions[1]);
carDimensions[1] = carDimensions[1] + _dimension1;
carDimensions[2] = carDimensions[2] + _dimension1;
carTemp[i] = carDimensions;
JamPuzzle newCarMove(_dimension1, _dimension2,
carTemp, freePos, movesMade,
pathForDestination);
possibleMoves.push_back(newCarMove);
carMove.clear();
bottom = bottom + _dimension1;
}
movesMade.clear();
}
else // Horizontal movements
{
vector< vector<int> > carTemp = cars;
set<int> freePos = freeSpace;
//check for left free spaces.
int left = cars[i][1] - 1;
while ( ((left + 1) % _dimension2 !=0) &&
freePos.find(left)!= freePos.end())
{
vector<int> carDimensions = carTemp[i];
carMove.push_back(i);
carMove.push_back(carDimensions[1]);
carMove.push_back(carDimensions[2]);
carMove.push_back(carDimensions[1] - 1);
carMove.push_back(carDimensions[2] - 1);
movesMade.push_back(carMove);
freePos.erase(left);
freePos.insert(carDimensions[2]);
carDimensions[1] = carDimensions[1] - 1;
carDimensions[2] = carDimensions[2] - 1;
carTemp[i] = carDimensions;
JamPuzzle newCarMove(_dimension1, _dimension2,
carTemp, freePos, movesMade,
pathForDestination);
possibleMoves.push_back(newCarMove);
carMove.clear();
left--;
}
carTemp.clear();
carTemp = cars;
freePos.clear();
freePos = freeSpace;
movesMade.clear();
//check for right free spaces.
int right = cars[i][2] + 1;
while ((right % _dimension2 !=0) &&
freePos.find(right)!=freePos.end())
{
vector<int> carDimensions = carTemp[i];
carMove.push_back(i);
carMove.push_back(carDimensions[1]);
carMove.push_back(carDimensions[2]);
carMove.push_back(carDimensions[1] + 1);
carMove.push_back(carDimensions[2] + 1);
movesMade.push_back(carMove);
freePos.erase(right);
freePos.insert(carDimensions[1]);
carDimensions[1] = carDimensions[1] + 1;
carDimensions[2] = carDimensions[2] + 1;
carTemp[i] = carDimensions;
JamPuzzle newCarMove(_dimension1, _dimension2,
carTemp, freePos, movesMade,
pathForDestination);
possibleMoves.push_back(newCarMove);
carMove.clear();
right++;
}
movesMade.clear();
}
}
}
// Overloaded == operator for compairsion.
bool JamPuzzle::operator==(JamPuzzle & check) const
{
if(cars == check.cars)
return true;
else
return false;
}
// Overloaded < operator for comparision.
bool JamPuzzle::operator<(const JamPuzzle & check) const
{
return (cars < check.cars);
}
// Destructor.
JamPuzzle::~JamPuzzle()
{
}
| true |
122953020e570904a8d6173ecfb83de2ef82f031 | C++ | nimukelkar/Binary-Tree-Operations | /main.cpp | UTF-8 | 7,049 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include<stack>
using namespace std;
int cl=0;
int ci=0;
class node{
private:
int data;
node* left;
node* right;
public:
friend class tree;
//void create();
};
class tree{
public:
node* root;
tree()
{
root=NULL;
}
void create();
void inorder(node* );
void preorder(node* );
void postorder(node* );
int height(node* );
void mirror(node* );
void dpre(node*);
void iterativepreorder();
void iterativeinorder();
void iterativepostorder();
void dummyin()
{
inorder(root);
}
void dummypre()
{
preorder(root);
}
void dummypost()
{
postorder(root);
}
int dummyheight()
{
int h=height(root);
return h;
}
void dummymirror()
{
mirror(root);
cout<<"Inorder of the tree, after mirroring is"<<endl;
inorder(root);
}
void dpre()
{
preorder(root);
}
void treecopy(node* &cpy,node* &orig);
tree operator=(tree);
/*void preorder();
void postorder();
int height();
void mirror();*/
};
void tree:: create()
{
node* p=new node;
node* q=new node;
cout<<"Enter the data of the tree node"<<endl;
cin>>p->data;
p->left=NULL;
p->right=NULL;
if(root==NULL)
{
root=p;
cout<<"Root node has been successfully inserted"<<endl;
}
else{
int flag=0;
char ch;
q=root;
do {
cout<<"Do you wish to insert to the left or to the right enter l or r?"<<endl;
cin>>ch;
if(ch=='l')
{
if(q->left==NULL)
{
q->left=p;
cout<<p->data<<" Has been successfully inserted at left"<<endl;
flag=1;
}
else
{
q=q->left;
}
}
else{
if(q->right==NULL)
{
q->right=p;
cout<<p->data<<" Has been successfully inserted at right"<<endl;
flag=1;
}
else
{
q=q->right;
}
}
} while(flag==0);
}
}
void tree::inorder(node* root)
{
if(root!=NULL){
inorder(root->left);
cout<<root->data<<endl;
inorder(root->right);
}
}
void tree:: preorder(node* root)
{
if(root!=NULL)
{
cout<<root->data<<endl;
if((root->left==NULL) &&(root->right==NULL))
cl++;
else
ci++;
preorder(root->left);
preorder(root->right);
}
}
void tree::postorder( node* root)
{
if(root!=NULL)
{
postorder(root->left);
postorder(root->right);
cout<<root->data<<endl;
}
}
int tree:: height(node* root)
{
int h1,h2;
if(root==NULL)
return 0;
if((root->left==NULL) && (root->right==NULL))
return 0;
h1=height(root->left);
h2=height(root->right);
if(h1>h2)
return h1+1;
else
return h2+1;
}
void tree:: mirror(node* root)
{
if(root!=NULL)
{
mirror(root->left);
mirror(root->right);
node* temp=new node;
temp=root->left;
root->left=root->right;
root->right=temp;
//cout<<root->data<<endl;
}
}
void tree::iterativepreorder()
{
node* p=new node;
stack<node*>s1;
p=root;
while(1)
{
while(p!=NULL)
{
cout<<p->data<<" ";
s1.push(p);
p=p->left;
}
if(s1.empty())
break;
else{
p=s1.top();
s1.pop();
p=p->right;
}
}
}
void tree::iterativeinorder()
{
node* p=new node;
p=root;
stack<node* >s1;
while(1)
{
while(p!=NULL)
{
s1.push(p);
p=p->left;
}
if(s1.empty())
break;
else
{
p=s1.top();
s1.pop();
cout<<p->data<<" ";
p=p->right;
}
}
}
void tree::iterativepostorder()
{
node* p=new node;
p=root;
stack<node* >s1;
while(1)
{
while(p!=NULL)
{
s1.push(p);
p=p->left;
}
if(s1.empty())
break;
if(s1.top()->right==NULL)
{
p=s1.top();
s1.pop();
cout<<p->data<<" ";
}
while(s1.top()->right==p)
{
p=s1.top();
cout<<p->data<<" ";
s1.pop();
if(s1.empty())
break;
}
if(!s1.empty())
{
p=s1.top()->right;
}
else
p=NULL;
}
}
tree tree::operator=(tree origtree)
{
treecopy(root,origtree.root);
return *this;
}
void tree::treecopy(node* &cpy,node* &orig)
{
cpy=orig;
if(orig->left)
{
treecopy(cpy->left,orig->left);
}
if(orig->right)
{
treecopy(cpy->right,orig->right);
}
}
int main()
{
int h;
//node* root=NULL;
node* left=NULL;
node* right=NULL;
tree t;
//int h;
char ch='y';
while(ch=='y')
{
int choice;
cout<<"Enter 1 to create a binary tree.\n2.To print inorder r\n3.To print inorder non recursively\n4.To print preorder r\n5.To print preorder non recursively\n6.To print postorder r\n7.To find iterative postorder.\n8.To find the height of tree.\n9.To find no. of leaf and intermediate nodes\n10.To find the mirror image of tree.\n11.To copy the tree."<<endl;
cin>>choice;
switch(choice)
{
case 1:
t.create();
break;
case 2:
t.dummyin();
break;
case 3:
t.iterativeinorder();
cout<<endl;
break;
case 4:
t.dummypre();
break;
case 5:
t.iterativepreorder();
cout<<endl;
break;
case 6:
t.dummypost();
break;
case 7:
t.iterativepostorder();
break;
case 8:
h=t.dummyheight();
cout<<"The height of the tree is"<<h<<endl;
break;
case 9:
t.dpre();
cout<<"The number of leaf nodes are "<<cl<<endl;
cout<<"The number of intermediate nodes are "<<ci<<endl;
break;
case 10:
t.dummymirror();
break;
case 11:
tree t2;
//t1.create();
t2=t;
cout<<"Both of the trees are"<<endl;
//t1.iterativeinorder();
t.iterativeinorder();
t2.iterativeinorder();
}
cout<<"Do you wish to continue y or n?"<<endl;
cin>>ch;
}
return 0;
}
| true |
57fdefad374dbc111edcb257a463c77a490a846f | C++ | yyzYLMF/hihocoder | /1138_islands_travel.cc | UTF-8 | 2,016 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <climits>
using namespace std;
struct Node {
int x;
int y;
};
//TLE Bellman-Ford
int main() {
int N;
int *dp;
Node* store;
int i,j,k,temp;
bool flag;
cin>>N;
if(N<=1) {
cout<<"0"<<endl;
return 0;
}
dp = new int[N];
store = new Node [N];
for(i=0;i<N;++i)
cin>>store[i].x>>store[i].y;
dp[0]=0;
for(i=1;i<N;++i)
dp[i]=min(abs(store[i].x - store[0].x),abs(store[i].y-store[0].y));
for(k=0;k<N;++k) {
flag = false;
for(i=1;i<N;++i) {
for(j=1;j<N;++j) {
if(j==i || dp[j] >= dp[i])
continue;
temp = min(abs(store[j].x-store[i].x),abs(store[j].y-store[i].y)) + dp[j];
if(temp < dp[i]) {
dp[i] = temp;
flag =true;
}
}
}
if(flag == false)
break;
}
cout<<dp[N-1]<<endl;
return 0;
}
//TLE dijkstra
int main() {
int N;
int *dp;
Node* store;
int i,j,k,temp,next;
bool *sign;
cin>>N;
if(N<=1) {
cout<<"0"<<endl;
return 0;
}
dp = new int[N];
store = new Node [N];
sign = new bool [N];
for(i=0;i<N;++i)
cin>>store[i].x>>store[i].y;
dp[0]=0;
for(i=1;i<N;++i)
dp[i]=min(abs(store[i].x - store[0].x),abs(store[i].y-store[0].y));
sign[0]=true;
for(i=1;i<N;++i)
sign[i]=false;
for(i=0;i<N;++i) {
temp = INT_MAX;
for(j=1;j<N;++j) {
if(!sign[j] && dp[j] < temp) {
temp=dp[j];
next = j;
}
}
if(next == N-1)
break;
sign[next]=true;
for(j=1;j<N;++j) {
temp = min(abs(store[next].x-store[j].x),abs(store[next].y-store[j].y))+dp[next];
if(temp < dp[j])
dp[j]=temp;
}
}
cout<<dp[N-1]<<endl;
return 0;
}
| true |
d59760f1100781b4e57d264a4b9014124f42ae35 | C++ | IAmBullsaw/acpp | /exams/code20170112/assignment7.cpp | UTF-8 | 1,647 | 3.28125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
#include <iomanip>
#include <iterator>
#include <vector>
#include <algorithm>
#include <sstream>
using namespace std;
class Student {
public:
Student() = default;
Student(string const& name, string const& surname,
string const& pnr, int const& points,
char const& grade)
:name{name},surname{surname},pnr{pnr},points{points},grade{grade},grade_p{}
{
if (grade != 'U') {
grade_p = grade - '0';
}
}
bool operator<(Student const& stud) const {
if (grade_p < stud.grade_p) return false;
else if (grade_p > stud.grade_p) return true;
else return name+surname < (stud.name+stud.surname);
}
string to_string() const {
ostringstream os;
os << setw(30) << left << surname + ", " + name
<< pnr << '\t'
<< grade << ' '
<< '(' << setw(2) << right << points << ')';
return os.str();
}
private:
string name{};
string surname{};
string pnr{};
int points{};
char grade{};
int grade_p{};
};
ostream& operator<<(ostream & os, Student const& stud) {
os << stud.to_string();
return os;
}
istream& operator>>(istream & is, Student & stud) {
string name, sur, pnr;
int points;
char grade;
getline(is,name,':');
getline(is,sur,':');
getline(is,pnr,':');
is >> points;
is.ignore();
is.get(grade);
is.ignore();
stud = Student{name,sur,pnr,points,grade};
return is;
}
int main() {
vector<Student> pupils{istream_iterator<Student>{cin},
istream_iterator<Student>{}};
sort(begin(pupils),end(pupils));
copy(begin(pupils),end(pupils),ostream_iterator<Student>{cout,"\n"});
return 0;
}
| true |
35e8c9eadf74111da1996657fd4931a9b241438a | C++ | WaitGodot/lua | /ClassToLua.cpp | UTF-8 | 544 | 2.953125 | 3 | [] | no_license | #include "ClassToLua.h"
#include <iostream>
#include "LuaStack.h"
ClassToLua::ClassToLua()
{
m_member = 0;
m_scriptHandler = -1;
}
ClassToLua::~ClassToLua()
{
}
void ClassToLua::print(){
if( m_scriptHandler != -1){
LuaStack::getInstance()->execute(m_scriptHandler);
}else{
std::cout<< "Class: member->" << m_member<< "\n";
}
}
void ClassToLua::registerScriptHandler( int handler )
{
m_scriptHandler = handler;
}
void ClassToLua::setMember( int member)
{
m_member = member;
}
int ClassToLua::getMember()
{
return m_member;
}
| true |
370024e69ab68cd4e7f7d4167c1ad6ad70cbc775 | C++ | Spetsnaz-Dev/CPP | /LeetCode/test_.cpp | UTF-8 | 1,135 | 3.03125 | 3 | [] | no_license | class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(),nums.end());
set <vector<int> > myset;
int i,left,right;
int n = nums.size();
for(i=0;i<n-2;++i)
{
left = i+1;
right = n-1;
while(left < right)
{
long long sum = nums[i]+nums[left]+nums[right];
if(sum < 0)
++left;
else if(sum > 0)
--right;
else{
myset.insert({nums[i], nums[left], nums[right]});
++left;
--right;
while(left < right and nums[left] == nums[left-1])
left++;
while(left < right and nums[right] == nums[right+1])
right--;
}
}
}
vector<vector<int> > result;
for(auto itr = myset.begin();itr!=myset.end();++itr)
{
result.push_back(*itr);
}
return result;
}
}; | true |
b34b16b0787b48211e5b672557483c27044f1496 | C++ | chegestar/airscratch | /AirScratch/riaafilter.cpp | UTF-8 | 2,962 | 2.640625 | 3 | [] | no_license | #include "riaafilter.h"
#include <stdio.h>
#include <string.h>
#include <math.h>
RIAAFilter::RIAAFilter()
{
}
// The Recording side of RIAA Equalization
static float recA[3] = { 1.0000000000, -0.7218922000, -0.1860520545 };
static float recB[3] = { 1.0000000000, -1.7007240000, 0.7029381524 };
static float playA[3] = { 1.0000000000, -1.7007240000, 0.7029381524 };
static float playB[3] = { 1.0000000000, -0.7218922000, -0.1860520545 };
static float rectmp[10000];
static float playtmp[10000];
#include <QDebug>
void RIAAFilter::RecordingFilter(float* buf, DWORD bufSize)
{
float* a = &recA[0];
float* b = &recB[0];
memset(rectmp, 0.0, 10000);
memcpy(rectmp, buf, bufSize);
static float ly0 = 0.0;
static float ly1 = 0.0;
static float ly2 = 0.0;
static float lx0 = 0.0;
static float lx1 = 0.0;
static float lx2 = 0.0;
static float ry0 = 0.0;
static float ry1 = 0.0;
static float ry2 = 0.0;
static float rx0 = 0.0;
static float rx1 = 0.0;
static float rx2 = 0.0;
for (unsigned int i = 0; i < bufSize/4; i+=2)
{
if (i >= 4)
{
lx0 = rectmp[i];
lx1 = rectmp[i-2];
lx2 = rectmp[i-4];
rx0 = rectmp[i+1];
rx1 = rectmp[i-1];
rx2 = rectmp[i-3];
}
// b(z^-1)/a(z^-1)
// Filter the left channel
ly0 = b[0]*lx0 + b[1]*lx1 + b[2]*lx2 - a[1]*ly1 -a[2]*ly2;
ry0 = b[0]*rx0 + b[1]*rx1 + b[2]*rx2 - a[1]*ry1 -a[2]*ry2;
// Set the value to the output buffer
*buf++ = ly0;
*buf++ = ry0;
ly2 = ly1;
ly1 = ly0;
ry2 = ry1;
ry1 = ry0;
}
}
void RIAAFilter::PlaybackFilter(float* buf, DWORD bufSize, float volume)
{
float* a = &playA[0];
float* b = &playB[0];
memset(playtmp, 0.0, 10000);
memcpy(playtmp, buf, bufSize);
static float ly0 = 0.0;
static float ly1 = 0.0;
static float ly2 = 0.0;
static float lx0 = 0.0;
static float lx1 = 0.0;
static float lx2 = 0.0;
static float ry0 = 0.0;
static float ry1 = 0.0;
static float ry2 = 0.0;
static float rx0 = 0.0;
static float rx1 = 0.0;
static float rx2 = 0.0;
for (unsigned int i = 0; i < bufSize/4; i+=2)
{
if (i >= 4)
{
lx0 = playtmp[i];
lx1 = playtmp[i-2];
lx2 = playtmp[i-4];
rx0 = playtmp[i+1];
rx1 = playtmp[i-1];
rx2 = playtmp[i-3];
}
// b(z^-1)/a(z^-1)
// Filter the left channel
ly0 = b[0]*lx0 + b[1]*lx1 + b[2]*lx2 - a[1]*ly1 -a[2]*ly2;
ry0 = b[0]*rx0 + b[1]*rx1 + b[2]*rx2 - a[1]*ry1 -a[2]*ry2;
// Set the value to the output buffer
*buf++ = tanh(ly0)*volume;
*buf++ = tanh(ry0)*volume;
//*buf++ = ly0;
//*buf++ = ry0;
ly2 = ly1;
ly1 = ly0;
ry2 = ry1;
ry1 = ry0;
}
}
| true |
8fcce9e8067ad0a83897afcac5682b25bdc02275 | C++ | Bryan9815/AI-Assignment-2 | /DM2242 AI Framework/Base/Source/Waiter.cpp | UTF-8 | 3,922 | 2.78125 | 3 | [] | no_license | #include "Waiter.h"
#include "Customer.h"
#include "Chef.h"
#define DELAY_TIME 2.f
#define GIVE_ORDER_MSG "New Order!"
#define RECEIVE_FOOD_MSG "Food's ready!"
#define PASS_BILL_MSG "Here's the bill!"
Waiter::Waiter()
{
Name = "Waiter";
EntityManager::GetInstance()->AddEntity(this);
}
Waiter::~Waiter()
{
}
void Waiter::Init()
{
state = Idle;
state_delay_timer = 0;
scale = 3.f;
StartPos.Set(90, 45, 0);
Position = StartPos;
TablePos.Set(107.777, 60, 0);
}
void Waiter::Update(double dt)
{
ChefPos = EntityManager::GetInstance()->Find("Chef")->GetPosition();
distFromChef = (Position - ChefPos).Length();
CashierPos = EntityManager::GetInstance()->Find("Cashier")->GetPosition();
distFromCashier = (Position - CashierPos).Length();
distFromTable = (Position - TablePos).Length();
switch (state)
{
case Waiter::Idle:
if (((Position - StartPos).Length()) >= 0.5f)
{
Position += (StartPos - Position).Normalize() * 10 * dt;
}
break;
case Waiter::Take_Order:
if (distFromTable >= (scale + 5.f + 0.5f))
Position += (TablePos - Position).Normalize() * 10 * dt;
break;
case Waiter::Give_Order_To_Cashier:
if (distFromCashier >= (scale + scale + 0.5f))
Position += (CashierPos - Position).Normalize() * 10 * dt;
break;
case Waiter::Receive_Food_From_Chef:
if (distFromChef >= (scale + scale + 0.5f))
Position += (ChefPos - Position).Normalize() * 10 * dt;
break;
case Waiter::Bring_Food_To_Table:
if (distFromTable >= (scale + 5.f + 0.5f))
Position += (TablePos - Position).Normalize() * 10 * dt;
break;
case Waiter::Pass_Bill_To_Cashier:
if (distFromCashier >= (scale + scale + 0.5f))
Position += (CashierPos - Position).Normalize() * 10 * dt;
break;
}
if (state_delay_timer < DELAY_TIME)
state_delay_timer += dt;
StateUpdate(dt);
}
void Waiter::StateUpdate(double dt)
{
if (state_delay_timer < DELAY_TIME)
return;
state_delay_timer = 0.f;
switch (state)
{
case Waiter::Idle:
if (InputMsg == RECEIVE_FOOD_MSG)
{
state = Receive_Food_From_Chef;
}
if (((Position - StartPos).Length()) <= 0.5f && Customer::GetInstance()->GetIdle())
{
Customer::GetInstance()->Init();
}
break;
case Waiter::Take_Order:
if (distFromTable <= (scale + 5.f + 0.5f))
{
Customer::GetInstance()->WaitForFood();
state = Give_Order_To_Cashier;
}
break;
case Waiter::Give_Order_To_Cashier:
{
if (distFromCashier <= (scale + scale + 0.5f))
{
EntityManager::GetInstance()->Talk_to(this, "Cashier", GIVE_ORDER_MSG);
state = Idle;
}
break;
}
case Waiter::Receive_Food_From_Chef:
{
if (distFromChef <= (scale + scale + 0.5f))
{
state = Bring_Food_To_Table;
Chef::GetInstance()->GoIdle();
}
break;
}
case Waiter::Bring_Food_To_Table:
{
if (distFromTable <= (scale + 5.f + 0.5f))
{
Customer::GetInstance()->GetPayment();
state = Receive_Payment;
}
break;
}
case Waiter::Pass_Bill_To_Cashier:
if (distFromCashier <= (scale + scale + 0.5f))
{
EntityManager::GetInstance()->Talk_to(this, "Cashier", PASS_BILL_MSG);
state = Idle;
}
break;
default:
break;
}
state_delay_timer = 0.f;
InputMsg = "";
}
std::string Waiter::getState()
{
switch (state)
{
case Waiter::Idle:
return "Idle";
break;
case Waiter::Take_Order:
return "Take_Order";
break;
case Waiter::Give_Order_To_Cashier:
return "Give_Order_To_Cashier";
break;
case Waiter::Receive_Food_From_Chef:
return "Receive_Food_From_Chef";
break;
case Waiter::Bring_Food_To_Table:
return "Bring_Food_To_Table";
break;
case Waiter::Receive_Payment:
return "Receive_Payment";
case Waiter::Pass_Bill_To_Cashier:
return "Pass_Bill_To_Cashier";
break;
default:
break;
}
return "";
}
void Waiter::TakeOrder()
{
state = Take_Order;
}
void Waiter::PassBill()
{
state = Pass_Bill_To_Cashier;
} | true |
6b5d614adf18cadb6abb6492ec9401d6f358a8e2 | C++ | AllanNozomu/CompetitiveProgramming | /Leetcode/res/Rotate Image/2.cpp | UTF-8 | 726 | 2.9375 | 3 | [
"MIT"
] | permissive | \*
Author: allannozomu
Runtime: 8 ms
Memory: 9 MB*\
class Solution {
public:
void reverse_lines(vector<vector<int>>& matrix){
for (vector<int> &line : matrix){
reverse(line.begin(), line.end());
}
}
void swap_positions(vector<vector<int>>& matrix){
int N = matrix.size();
for (int i = 0; i < N- 1; ++i){
for (int j = 0; j < N - i - 1; ++j){
int aux = matrix[i,j];
matrix[i,j] = matrix[N - j - 1,N - i - 1];
matrix[N - j - 1,N - i - 1] = aux;
}
}
}
void rotate(vector<vector<int>>& matrix) {
reverse_lines(matrix);
swap_positions(matrix);
}
}; | true |
3cc1648f657eb24accea8299b1ead1020c5b482f | C++ | sekcheong/Amulet | /src/utils/registry.cc | UTF-8 | 5,627 | 2.921875 | 3 | [] | no_license | // registry.cc
// written by Alan Ferrency
// August 1995
// registry of names for debugging Amulet wrappers and method wrappers.
// only compile this in if we're debugging.
#ifdef DEBUG
#include <am_inc.h>
#include REGISTRY__H // for registry stuff.
#include TYPES__H // for wrappers
#include UNIV_MAP__H // for hash table routines.
/* Implementation details of the registry:
We have a one-way hash table which hashes items (registry entries can be
wrappers, methods, or constraints) according to their registry key (the name
and type_ID of the item combined). For registry entries, wee really want
to key on two pieces of information, the string name of the item, and its
type ID. We need both pieces of information to determine that two keys
are equal.
*/
Am_Registry_Key::Am_Registry_Key () {
name = NULL;
}
Am_Registry_Key::Am_Registry_Key (const char *the_name) {
//name = new char[strlen(the_name) + 1];
//strcpy (name, the_name);
name = the_name;
}
bool Am_Registry_Key::operator== (const Am_Registry_Key& test_key) {
if (test_key.name && name)
return !strcmp(name, test_key.name);
else return false; // no null names are equal to anything
}
bool Am_Registry_Key::operator!= (const Am_Registry_Key& test_key) {
return !(*this == test_key);
}
bool Am_Registry_Key::Valid() {
return !!(name); // if it's !=0
}
Am_Registry_Key::operator const char* () {
return name;
}
int HashValue (Am_Registry_Key key, int size)
{
// af1x
// This is based on the string hash function from univ_map.cc
// That one simply summed up the first two and last two characters,
// and normalized.
// With most object names, etc, we're going to have the most useful
// information in the end of the string (often "..._123_127_...") and not
// in the beginning of the string (usually "Am...") so I'll just use the
// last four characters instead of anything from the beginning.
unsigned base;
const char *name = key.Name();
unsigned len = name ? strlen(name) : 0;
switch (len) {
case 0: return 0;
case 1: base = name[0]*4; break;
case 2: base = name[0]*2 + name[1]*2; break;
case 3: base = name[0] + name[1] + name[2]*2; break;
default: base = name[len - 1] + name[len - 2] +
name[len - 3] + name[len - 4];
}
return base * unsigned (0x10000L / 4 / 0x100) % size;
}
int HashValue (const Am_Registered_Type* entry, int size)
{
// just use the pointer
// *OLD* return (long)entry % size ;
//new: from Yann LE BIANNIC <lebiannic@dassault-avion.fr> 26 Jun 1996
// the division by sizeof(entry) is intended to prevent "holes" in
// the hash table
return ((unsigned long)entry / sizeof(entry)) % size;
}
int KeyComp (Am_Registry_Key key1, Am_Registry_Key key2)
{
// uses Am_Registry_Key::operator!=
// returns strcmp-like compare results: 0 if equal, !=0 if unequal.
return key1 != key2;
}
int KeyComp (const Am_Registered_Type* key1, const Am_Registered_Type* key2)
{
// uses Am_Registry_Entry::operator!=
// returns strcmp-like compare results: 0 if equal, !=0 if unequal.
return key1 != key2; // Am_Registered_Type* has no op== so
// it should just compare pointers.
}
Am_Registry_Key Am_No_Registry_Key;
const Am_Registered_Type* Am_No_Registry_Entry = NULL;
// declare and implement custom hash table type
// the forward mapping (key to entry)
Am_DECL_MAP (Registry, Am_Registry_Key, const Am_Registered_Type*)
Am_IMPL_MAP (Registry, Am_Registry_Key, Am_No_Registry_Key,
const Am_Registered_Type*, Am_No_Registry_Entry);
// the reverse mapping (entry back to key)
Am_DECL_MAP (Registry_Reverse, const Am_Registered_Type*, Am_Registry_Key)
Am_IMPL_MAP (Registry_Reverse, const Am_Registered_Type*, Am_No_Registry_Entry,
Am_Registry_Key, Am_No_Registry_Key);
// the bidirectional table
Am_DECL_TABLE (Registry, Registry_Reverse, Am_Registry_Key,
const Am_Registered_Type*);
Am_Table_Registry* Am_Name_Registry = NULL;
// Utility to make sure registry is initialized
inline void verify_name_registry() {
// make the table pretty big, to hold lots of names.
// around 1000 names registered in testwidgets (9-6-95)
if (Am_Name_Registry == NULL)
Am_Name_Registry = new Am_Table_Registry (2000);
}
////////
// The registry routines
// register an item/ name pair
void Am_Register_Name (const Am_Registered_Type* item, const char *name) {
verify_name_registry();
Am_Registry_Key key (name);
if (key.Valid()) // only register valid keys
Am_Name_Registry->SetAt(key, item);
}
// we unregister the names when they're deleted
void Am_Unregister_Name (const Am_Registered_Type* item) {
verify_name_registry();
if (item) // only unregister valid items.
Am_Name_Registry->DeleteKey(item);
}
const char* Am_Get_Name_Of_Item (const Am_Registered_Type* item) {
verify_name_registry();
if (item)
return (Am_Name_Registry->GetAt(item));
else return NULL;
}
const Am_Registered_Type* Am_Get_Named_Item (const char* name) {
verify_name_registry();
Am_Registry_Key key (name);
if (key.Valid())
return Am_Name_Registry->GetAt(key);
else return Am_No_Registry_Entry;
}
Am_Map_Int2Str* Am_Type_Registry = NULL;
inline void verify_type_registry () {
if (Am_Type_Registry == NULL) Am_Type_Registry = new Am_Map_Int2Str;
}
void Am_Register_Type_Name (Am_ID_Tag id, const char* type_name)
{
verify_type_registry ();
Am_Type_Registry->SetAt (id, (char*)type_name);
}
void Am_Unregister_Type_Name (Am_ID_Tag id)
{
verify_type_registry ();
Am_Type_Registry->DeleteKey(id);
}
const char* Am_Get_Type_Name (Am_ID_Tag id)
{
verify_type_registry ();
return Am_Type_Registry->GetAt (id);
}
#endif
| true |
54edd25bd710855a183bbc81fe60c78ce5b06908 | C++ | thiagovas/Macaco-Louco | /testinator.cpp | UTF-8 | 2,708 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <deque>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <stack>
#include <queue>
#include <cmath>
#include <fstream>
#include <functional>
#include <iomanip>
#include <sstream>
using namespace std;
string convert (int a){
stringstream ss;
ss << a;
return ss.str();
}
string int_to_bitstring (int label, int size){
int x = 1 << size-1;
string binary;
while (x){
if (label&x) binary += '1';
else binary += '0';
x = x >> 1;
}
return binary;
}
string invert (string s){
string result;
for (int i=s.size()-1; i>=0; i--){
result += s[i];
}
return result;
}
void write_data (ofstream &data){
int a = rand()%65536;
// cout << a << endl;
data << invert (int_to_bitstring (a, 16)) << endl;
}
void r_type (ofstream &inst){
inst << "M" << convert (rand()%32) << ' ' << "M" << convert(rand()%32) << ' ' << "M" << convert(rand()%32) << endl;
}
void lwi_type (ofstream &inst){
inst << "M" << convert (rand()%32) << ' ' << rand()%1024 << endl;
}
void bne_type (ofstream &inst){
inst << "M" << convert (rand()%32) << ' ' << "M" << convert (rand()%32) << ' ' << rand()%32 << endl;
}
void j_type (ofstream &inst){
int a = rand()%32;
inst << 18*a << endl;
}
void jr_type (ofstream &inst){
inst << "M" << convert (rand()%32) << endl;
}
void convert_to_funct (ofstream &inst, string instruction, map<string, int> table){
if (table[instruction] == 1){
r_type (inst);
}
else if (table[instruction] == 2){
lwi_type (inst);
}
else if (table[instruction] == 3){
bne_type (inst);
}
else if (table[instruction] == 4){
j_type (inst);
}
else {
jr_type (inst);
}
}
int main (int argc, char *argv[]){
ios::sync_with_stdio(false);
// Primeiro parametro: Quantidade de instruções [0..32]
// Segundo parametro: Quantidade de elementos na memória de dados;
int quant_inst = atoi (argv[1]);
int quant_dados = atoi (argv[2]);
int random_number;
srand(time(NULL));
string instruction;
map<string, int> table;
table["ADD"] = 1;
table["SUB"] = 1;
table["AND"] = 1;
table["OR"] = 1;
table["LWI"] = 2;
table["BNE"] = 3;
table["J"] = 4;
table["JR"] = 5;
map<int, string> type_inst;
type_inst[0] = "ADD";
type_inst[1] = "SUB";
type_inst[2] = "AND";
type_inst[3] = "OR";
type_inst[4] = "LWI";
type_inst[5] = "BNE";
type_inst[6] = "J";
type_inst[7] = "JR";
ofstream inst ("inst");
ofstream data ("data");
for (int i=0; i<quant_inst; i++){
instruction = type_inst[rand()%8];
inst << instruction << ' ';
convert_to_funct (inst, instruction, table);
}
for (int i=0; i<quant_dados; i++){
write_data (data);
}
return 0;
}
| true |
141206d7ea731d88223dcd043900176c150547cf | C++ | verloka/CPPFromZero | /src/011.TextFileIO/011.TextFileIO.cpp | UTF-8 | 1,183 | 3.125 | 3 | [
"Apache-2.0"
] | permissive | #include "stdafx.h"
using namespace std;
int main()
{
system("color 70");
setlocale(0, "");
SetConsoleTitle("011.Text File I/O");
//write
string filePath;
string fileContent;
string fileName;
cout << "Enter path for new text file: ";
cin >> filePath;
cout << "Waht are you want to write to file? File content: ";
cin >> fileContent;
cout << "Enter file name: ";
cin >> fileName;
ofstream fileWrite;
fileWrite.open(filePath + "\\" + fileName + ".txt");
if (fileWrite.is_open())
{
fileWrite << fileContent;
cout << "File " + fileName + ".txt was saved in " + filePath << endl << endl;
}
else
{
cout << "File " << filePath + "\\" + fileName + ".txt" << " cannot open!" << endl;
}
fileWrite.close();
//read
string openFilePath;
cout << "Open file for read. Enter path to file: ";
cin >> openFilePath;
ifstream fileRead;
fileRead.open(openFilePath);
if (fileRead.is_open())
{
cout << "Contetn of " << openFilePath << endl;
string buffer;
while (!fileRead.eof())
{
getline(fileRead, buffer);
cout << buffer << endl;
}
}
else
{
cout << "File " << openFilePath << " cannot open!" << endl;
}
system("pause");
return 0;
}
| true |
e2e26faf21151652064da301739947ad27bc51c2 | C++ | mingdyuo/TCP-socket-chatting-server | /ChattingServer_v1.1/ChattingClient/LobbyDisplay.h | UHC | 2,587 | 2.9375 | 3 | [] | no_license | #pragma once
#ifndef LOBBY_DISPLAY_H
#define LOBBY_DISPLAY_H
#include "Display.h"
#include <map>
#include <string>
class LobbyDisplay : public Display
{
public:
LobbyDisplay() = delete;
LobbyDisplay(uint32_t id) :
myId_(id), cursorIndex_(4), lowerLimit_(4)
{}
void UpdatePlayer(uint32_t id, std::string name)
{
users_[id] = name;
}
void RemovePlayer(uint32_t pid)
{
auto player = users_.find(pid);
if (player != users_.end())
users_.erase(pid);
}
void draw()
{
this->Clear();
this->DrawWelcome();
this->DrawList();
this->DrawCursor();
}
void SetRoomList(
const std::vector<uint16_t>& chatroomId,
const std::vector<std::string>& chatroomName)
{
chatRoomIds_ = chatroomId;
chatRooms_ = chatroomName;
}
void CursorDown()
{
this->EraseCursor();
int upperLimit = lowerLimit_ + chatRooms_.size();
cursorIndex_++;
cursorIndex_ = min(cursorIndex_, upperLimit);
this->DrawCursor();
}
void CursorUp()
{
this->EraseCursor();
cursorIndex_--;
cursorIndex_= max(cursorIndex_, lowerLimit_);
this->DrawCursor();
}
int GetSelection() const
{ return cursorIndex_ == chatRooms_.size() + lowerLimit_ ? 0 : chatRoomIds_[cursorIndex_ - lowerLimit_]; }
private:
void DrawWelcome()
{
gotoxy(0,0); printf(" / __ ___ // // ___ ___ __ // ___ / \n");
gotoxy(0,1); printf(" // ) ) //___) ) // // // ) ) // / / / / // ) ) // ) ) // // ) / \n");
gotoxy(0,2); printf(" // / / // // // // / / // / / / / // / / // // // / / \n");
gotoxy(0,3); printf("// / / ((____ // // ((___/ / ((__( (__/ / ((___/ / // // ((___/ / \n");
}
void DrawList()
{
this->SetColor(CLR_WHITE);
gotoxy(0, lowerLimit_);
for (int i = 0;i < chatRooms_.size();i++)
{
printf("[ ] %s\n", chatRooms_[i].c_str());
}
printf("[ ] äù ϱ\n");
}
void DrawCursor()
{
COORD pos = { 2 , cursorIndex_ };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
printf("");
}
void EraseCursor()
{
COORD pos = { 2 , cursorIndex_ };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
printf(" ");
}
private:
inline int MIN(int a, int b)
{
return a > b ? b : a;
}
inline int MAX(int a, int b)
{
return a > b ? a : b;
}
private:
short cursorIndex_;
std::vector<std::string> chatRooms_;
std::vector<uint16_t> chatRoomIds_;
std::map<uint32_t, std::string> users_;
uint32_t myId_;
const int lowerLimit_;
};
#endif // !LOBBY_DISPLAY_H
| true |
e8d24700112f29fdf47fee22d2c24ec341c13245 | C++ | PenteractStudios/Tesseract | /Project/Libs/MathGeoLib/Math/TransformOps.cpp | ISO-8859-1 | 8,629 | 2.84375 | 3 | [
"MIT"
] | permissive | /* Copyright Jukka Jylnki
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
/** @file TransformOps.cpp
@author Jukka Jylnki
@brief */
#include "TransformOps.h"
#include "MathFunc.h"
#include "float2.h"
#include "float4.h"
#include "float3x3.h"
#include "float3x4.h"
#include "float4x4.h"
MATH_BEGIN_NAMESPACE
TranslateOp::TranslateOp(float tx, float ty, float tz)
:offset(DIR_VEC(tx, ty, tz))
{
}
TranslateOp::TranslateOp(const float3 &trans)
:offset(DIR_VEC(trans))
{
}
TranslateOp::operator float3x4() const
{
return ToFloat3x4();
}
TranslateOp::operator float4x4() const
{
return ToFloat4x4();
}
float3x4 TranslateOp::ToFloat3x4() const
{
float3x4 m;
m.SetRow(0, 1, 0, 0, offset.x);
m.SetRow(1, 0, 1, 0, offset.y);
m.SetRow(2, 0, 0, 1, offset.z);
return m;
}
float4x4 TranslateOp::ToFloat4x4() const
{
float4x4 m;
m.SetRow(0, 1, 0, 0, offset.x);
m.SetRow(1, 0, 1, 0, offset.y);
m.SetRow(2, 0, 0, 1, offset.z);
m.SetRow(3, 0, 0, 0, 1.f);
return m;
}
vec TranslateOp::Offset() const
{
return offset;
}
#if defined(MATH_ENABLE_STL_SUPPORT) || defined(MATH_CONTAINERLIB_SUPPORT)
StringT TranslateOp::ToString() const
{
char str[256];
sprintf(str, "(%.3f, %.3f, %.3f)", offset.x, offset.y, offset.z);
return str;
}
#endif
float3x4 operator *(const TranslateOp &lhs, const float3x4 &rhs)
{
float3x4 r = rhs;
r.SetTranslatePart(r.TranslatePart() + DIR_TO_FLOAT3(lhs.Offset()));
// Our optimized form of multiplication must be the same as this.
mathassert(r.Equals((float3x4)lhs * rhs));
return r;
}
float3x4 operator *(const float3x4 &lhs, const TranslateOp &rhs)
{
float3x4 r = lhs;
r.SetTranslatePart(lhs.TransformPos(DIR_TO_FLOAT3(rhs.Offset())));
// Our optimized form of multiplication must be the same as this.
assume4(r.Equals(lhs * (float3x4)rhs), lhs, rhs, r, lhs * (float3x4)rhs);
return r;
}
float4x4 operator *(const TranslateOp &lhs, const float4x4 &rhs)
{
// This function is based on the optimized assumption that the last row of rhs is [0,0,0,1].
// If this does not hold and you are hitting the check below, explicitly cast TranslateOp lhs to float4x4 before multiplication!
assume(rhs.Row(3).Equals(0.f, 0.f, 0.f, 1.f));
float4x4 r = rhs;
r.SetTranslatePart(r.TranslatePart() + DIR_TO_FLOAT3(lhs.Offset()));
return r;
}
float4x4 operator *(const float4x4 &lhs, const TranslateOp &rhs)
{
float4x4 r = lhs;
r.SetTranslatePart(lhs.TransformPos(DIR_TO_FLOAT3(rhs.Offset())));
return r;
}
ScaleOp::ScaleOp(const float2 &scaleXY, float scaleZ)
:scale(DIR_VEC(scaleXY.x, scaleXY.y, scaleZ))
{
}
ScaleOp::ScaleOp(float sx, float sy, float sz)
:scale(DIR_VEC(sx, sy, sz))
{
}
ScaleOp::ScaleOp(const float3 &scale)
:scale(DIR_VEC(scale))
{
}
ScaleOp::ScaleOp(const float4 &scale)
:scale(FLOAT4_TO_DIR(scale))
{
}
ScaleOp::operator float3x3() const
{
return ToFloat3x3();
}
ScaleOp::operator float3x4() const
{
return ToFloat3x4();
}
ScaleOp::operator float4x4() const
{
return ToFloat4x4();
}
float3x3 ScaleOp::ToFloat3x3() const
{
float3x3 m;
m.SetRow(0, scale.x, 0, 0);
m.SetRow(1, 0, scale.y, 0);
m.SetRow(2, 0, 0, scale.z);
return m;
}
float3x4 ScaleOp::ToFloat3x4() const
{
float3x4 m;
m.SetRow(0, scale.x, 0, 0, 0);
m.SetRow(1, 0, scale.y, 0, 0);
m.SetRow(2, 0, 0, scale.z, 0);
return m;
}
float4x4 ScaleOp::ToFloat4x4() const
{
float4x4 m;
m.SetRow(0, scale.x, 0, 0, 0);
m.SetRow(1, 0, scale.y, 0, 0);
m.SetRow(2, 0, 0, scale.z, 0);
m.SetRow(3, 0, 0, 0, 1.f);
return m;
}
float3x3 operator *(const ScaleOp &lhs, const float3x3 &rhs)
{
float3x3 ret = rhs;
ret.ScaleRow(0, lhs.scale.x);
ret.ScaleRow(1, lhs.scale.y);
ret.ScaleRow(2, lhs.scale.z);
// Our optimized form of multiplication must be the same as this.
mathassert(ret.Equals((float3x3)lhs * rhs));
return ret;
}
float3x3 operator *(const float3x3 &lhs, const ScaleOp &rhs)
{
float3x3 ret = lhs;
ret.ScaleCol(0, rhs.scale.x);
ret.ScaleCol(1, rhs.scale.y);
ret.ScaleCol(2, rhs.scale.z);
// Our optimized form of multiplication must be the same as this.
mathassert(ret.Equals(lhs * (float3x3)rhs));
return ret;
}
float3x4 operator *(const ScaleOp &lhs, const float3x4 &rhs)
{
float3x4 ret;
ret[0][0] = rhs[0][0] * lhs.scale.x; ret[0][1] = rhs[0][1] * lhs.scale.x; ret[0][2] = rhs[0][2] * lhs.scale.x; ret[0][3] = rhs[0][3] * lhs.scale.x;
ret[1][0] = rhs[1][0] * lhs.scale.y; ret[1][1] = rhs[1][1] * lhs.scale.y; ret[1][2] = rhs[1][2] * lhs.scale.y; ret[1][3] = rhs[1][3] * lhs.scale.y;
ret[2][0] = rhs[2][0] * lhs.scale.z; ret[2][1] = rhs[2][1] * lhs.scale.z; ret[2][2] = rhs[2][2] * lhs.scale.z; ret[2][3] = rhs[2][3] * lhs.scale.z;
mathassert(ret.Equals(lhs.ToFloat3x4() * rhs));
return ret;
}
float3x4 operator *(const float3x4 &lhs, const ScaleOp &rhs)
{
float3x4 ret;
ret[0][0] = lhs[0][0] * rhs.scale.x; ret[0][1] = lhs[0][1] * rhs.scale.y; ret[0][2] = lhs[0][2] * rhs.scale.z; ret[0][3] = lhs[0][3];
ret[1][0] = lhs[1][0] * rhs.scale.x; ret[1][1] = lhs[1][1] * rhs.scale.y; ret[1][2] = lhs[1][2] * rhs.scale.z; ret[1][3] = lhs[1][3];
ret[2][0] = lhs[2][0] * rhs.scale.x; ret[2][1] = lhs[2][1] * rhs.scale.y; ret[2][2] = lhs[2][2] * rhs.scale.z; ret[2][3] = lhs[2][3];
mathassert(ret.Equals(lhs * rhs.ToFloat3x4()));
return ret;
}
float4x4 operator *(const ScaleOp &lhs, const float4x4 &rhs)
{
float4x4 ret;
#if defined(MATH_AUTOMATIC_SSE) && defined(MATH_SIMD)
simd4f x = xxxx_ps(lhs.scale.v);
simd4f y = yyyy_ps(lhs.scale.v);
simd4f z = zzzz_ps(lhs.scale.v);
ret.row[0] = mul_ps(rhs.row[0], x);
ret.row[1] = mul_ps(rhs.row[1], y);
ret.row[2] = mul_ps(rhs.row[2], z);
ret.row[3] = rhs.row[3];
#else
ret[0][0] = rhs[0][0] * lhs.scale.x; ret[0][1] = rhs[0][1] * lhs.scale.x; ret[0][2] = rhs[0][2] * lhs.scale.x; ret[0][3] = rhs[0][3] * lhs.scale.x;
ret[1][0] = rhs[1][0] * lhs.scale.y; ret[1][1] = rhs[1][1] * lhs.scale.y; ret[1][2] = rhs[1][2] * lhs.scale.y; ret[1][3] = rhs[1][3] * lhs.scale.y;
ret[2][0] = rhs[2][0] * lhs.scale.z; ret[2][1] = rhs[2][1] * lhs.scale.z; ret[2][2] = rhs[2][2] * lhs.scale.z; ret[2][3] = rhs[2][3] * lhs.scale.z;
ret[3][0] = rhs[3][0]; ret[3][1] = rhs[3][1]; ret[3][2] = rhs[3][2]; ret[3][3] = rhs[3][3];
#endif
mathassert(ret.Equals(lhs.ToFloat4x4() * rhs));
return ret;
}
float4x4 operator *(const float4x4 &lhs, const ScaleOp &rhs)
{
float4x4 ret;
ret[0][0] = lhs[0][0] * rhs.scale.x; ret[0][1] = lhs[0][1] * rhs.scale.y; ret[0][2] = lhs[0][2] * rhs.scale.z; ret[0][3] = lhs[0][3];
ret[1][0] = lhs[1][0] * rhs.scale.x; ret[1][1] = lhs[1][1] * rhs.scale.y; ret[1][2] = lhs[1][2] * rhs.scale.z; ret[1][3] = lhs[1][3];
ret[2][0] = lhs[2][0] * rhs.scale.x; ret[2][1] = lhs[2][1] * rhs.scale.y; ret[2][2] = lhs[2][2] * rhs.scale.z; ret[2][3] = lhs[2][3];
ret[3][0] = lhs[3][0] * rhs.scale.x; ret[3][1] = lhs[3][1] * rhs.scale.y; ret[3][2] = lhs[3][2] * rhs.scale.z; ret[3][3] = lhs[3][3];
mathassert4(ret.Equals(lhs * rhs.ToFloat4x4()), lhs, rhs.ToFloat4x4(), ret, lhs * rhs.ToFloat4x4());
return ret;
}
float3x4 operator *(const ScaleOp &lhs, const TranslateOp &rhs)
{
float3x4 ret;
ret[0][0] = lhs.scale.x; ret[0][1] = 0; ret[0][2] = 0; ret[0][3] = lhs.scale.x * rhs.offset.x;
ret[1][0] = 0; ret[1][1] = lhs.scale.y; ret[1][2] = 0; ret[1][3] = lhs.scale.y * rhs.offset.y;
ret[2][0] = 0; ret[2][1] = 0; ret[2][2] = lhs.scale.z; ret[2][3] = lhs.scale.z * rhs.offset.z;
mathassert(ret.Equals(lhs.ToFloat3x4() * rhs));
return ret;
}
float3x4 operator *(const TranslateOp &lhs, const ScaleOp &rhs)
{
float3x4 ret;
ret[0][0] = rhs.scale.x; ret[0][1] = 0; ret[0][2] = 0; ret[0][3] = lhs.offset.x;
ret[1][0] = 0; ret[1][1] = rhs.scale.y; ret[1][2] = 0; ret[1][3] = lhs.offset.y;
ret[2][0] = 0; ret[2][1] = 0; ret[2][2] = rhs.scale.z; ret[2][3] = lhs.offset.z;
mathassert(ret.Equals(lhs.ToFloat3x4() * rhs));
return ret;
}
vec ScaleOp::Offset() const
{
return scale;
}
#if defined(MATH_ENABLE_STL_SUPPORT) || defined(MATH_CONTAINERLIB_SUPPORT)
StringT ScaleOp::ToString() const
{
char str[256];
sprintf(str, "(%.3f, %.3f, %.3f)", scale.x, scale.y, scale.z);
return str;
}
#endif
MATH_END_NAMESPACE
| true |
009d4f244a27bcabb01152c4d31d79c04b6b1124 | C++ | DeercoderCourse/Course-Project | /C++/code/chap9_8/chap9_8/chap9_8.cpp | GB18030 | 4,664 | 3.421875 | 3 | [] | no_license | #include <iostream>
using namespace std;
const int MAX = 23;
class SET{
int *elem; //żԪصĶ̬ڴ
int count,total; //ĿǰԪظԪظ
public:
SET(int total);
SET(const SET&);
int find(int val) const;
int full() const;
int empty() const;
virtual SET operator +(const SET&);
virtual SET operator -(const SET &)const; //ϵIJ
virtual SET operator *(const SET &)const; //ϵĽ
virtual SET &operator <<(int value); //һԪ
virtual SET &operator >>(int value); //ɾһԪ
virtual SET &operator +=(const SET &); //ϵIJ
virtual SET &operator -=(const SET &); //ϵIJ
virtual SET &operator *=(const SET &); //ϵĽ
virtual SET &operator <<=(int value); //һԪ
virtual SET &operator >>=(int value); //ɾһԪ
virtual SET &operator =(const SET &);
virtual ~SET();
void print();
};
SET::SET(int total){
this->total = total;
elem = new int[total];
count = 0;
}
SET::SET(const SET& b){
this->total = b.total;//ʼ
count = b.count;
elem = new int[total]; //ڴռ
for(int i = 0; i < count; i++){
elem[i] = b.elem[i]; //ֵ
}
}
SET::~SET(){
if(elem){
delete elem;//ͷڴ
}
}
int SET::find(int val) const{
for(int i=0; i < count; i++){
if(val == elem[i])
return 1; //ҵ
}
return 0; //δҵ
}
int SET::full() const{
return (int)(count == total);
}
int SET::empty() const{
return (int)(count==0);
}
SET SET::operator +(const SET& b){
for(int i =0; i <b.count; i++){
if(find(b.elem[i])==0){ //ҵԪأɾ
elem[count++] = b.elem[i]; //Ӻ濪ʼֵ
}
}
return *this;
}
SET SET::operator -(const SET &b)const{ //ϵIJ
for(int i =0; i <b.count; i++){
if(find(b.elem[i])){//ҵԪأɾ
int j;
for ( j= 0; elem[j]!= b.elem[i]; j++){}
for(int k = j ; j < this->count-1; j++){
elem[k] = elem[k++]; //ɾǰһλ
}
}
}
return *this;
}
SET SET::operator *(const SET & b)const{ //ϵĽ
int a[MAX],count =0;
for(int i = 0; i < this->count; i++)
{
for (int j = 0; j < b.count; j++)
{
if(elem[i]==b.elem[j])
a[count++]=elem[i]; //漯ͬԪԱ
}
}
SET *newSet = new SET(MAX);
for (int i = 0; i <count; i++)
{
newSet->elem[i] = a[i];
}
return *this;
}
SET &SET::operator <<(int value){ //һԪ
if(find(value) == 0)
this->elem[count++] = value;
return *this;
}
SET &SET::operator >>(int value){ //ɾһԪ
int ptest = -1; //־λɾvalueλ
for(int i = 0; i < this->count; i++)
{
if(elem[i]==value){
ptest = i; break;
}
}
for (int i = ptest; i < count; i++)
{
this->elem[i] = elem[i++]; //ƶԪ
}
count--;
return *this;
}
SET &SET::operator +=(const SET &b){ //ϵIJ
for(int i = 0; i<b.count; i++){
if(find(b.elem[i])==0){ //ڱУֱ
elem[count++] = b.elem[i];
}
}
return *this;
}
SET &SET::operator -=(const SET &b){ //ϵIJ
*this = *this - b; //ѾдõIJ
return *this;
}
SET &SET::operator *=(const SET &b){ //ϵĽ
*this = *this * b;
return *this; //ͬ
}
SET &SET::operator <<=(int value){ //һԪ
*this = *this << value;
return *this;
}
SET &SET::operator >>=(int value){ //ɾһԪ
*this = *this >> value;
return *this;
}
SET &SET::operator =(const SET &b){
for(int i = 0; i < count; i++){
elem[i] = 0;
}
for(int j = 0; j < b.count; j++){
elem[j] = b.elem[j];
}
return *this;
}
void SET::print(){
for (int i = 0; i < count; i++)
{
cout << elem[i] << " ";
}
cout << endl;
}
int main() //Դ
{
SET a(10); //һSET
for(int i = 0; i < 5; i++)
a << i; //һԪ
a.print();
a>>4; //ɾֵΪ4Ľڵ
a.print();
if(a.find(2)) //֤find
cout << "found!" << endl;
if(a.full()) //֤full
cout << "full!" << endl;
if(a.empty()) //֤empty
cout << "empty!" << endl;
SET b(10);
for(int i = 0; i < 6; i++)
b << i; //Ԫأʵdzʼ,ΪԪ
const SET c(b); //ÿ캯
b = a + c;
b.print();
b = a - c;
b.print();
b = a * c;
b.print();
b += c;
b.print();
b -= c;
b.print();
b *= c;
b.print();
return 0;
}
| true |
9ad53ed90e1efc006471cc25a461acd998503ca0 | C++ | guille31794/AAED | /Práctica 1/Ej 8/cuadrado.cpp | UTF-8 | 462 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include "cronometro.h"
using namespace std;
inline double cuadrado (double cuadrado) {return cuadrado * cuadrado;}
int main(int argc, char const *argv[]) {
int contador = 0; cronometro cronometro;
double numeroAElevar;
cout << "Introduzca el numero: ";
cin >> numeroAElevar;
cronometro.activar();
while (cronometro.tiempo() < 1) {
cuadrado(numeroAElevar);
++contador;
}
cout << "Se repite: " << contador << endl;
}
| true |
12443ffd11a7e908005b0fdde1e628e05b1ce674 | C++ | Eradan94/Mastercraft-CB | /glimac/src/Chunk.cpp | UTF-8 | 11,775 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <utility>
#include "glimac/common.hpp"
#include "glimac/Chunk.hpp"
#include <glimac/glm.hpp>
namespace glimac {
void Chunk::build(unsigned char** worldHeightArray, Color** worldTerrainArray, const int& x, const int& y, const int& z) {
int terrain;
int terrainHeight;
blocks = new int**[SIZE_CHUNK_X];
for(int i = 0; i < SIZE_CHUNK_X; i++) {
blocks[i] = new int*[SIZE_CHUNK_Y];
for(int j = 0; j < SIZE_CHUNK_Y; j++) {
blocks[i][j] = new int[SIZE_CHUNK_Z];
terrainHeight = (int)worldHeightArray[x + i][y + j];
terrain = BlockTypes::getType(worldTerrainArray[x + i][y + j]); // -1 if air block or decor
if(terrain == -1) { // Maybe be there is a decor here, in this case we get the terrain (the color of the decor is : terrainColor + (r, 0, 0))
terrain = BlockTypes::getGroundTypeFromColor(worldTerrainArray[x + i][y + j]);
}
for(int k = 0; k < SIZE_CHUNK_Z; k++) { // fill the rest with air block -1
blocks[i][j][k] = -1;
}
if(z < terrainHeight) {
if(terrainHeight - z >= 16) { // the chunk is not a surface chunk
for(int k = 0; k < SIZE_CHUNK_Z; k++) {
blocks[i][j][k] = terrain;
}
}
else {
for(int k = 0; k < terrainHeight - z; k++) { // surface chunk
blocks[i][j][k] = terrain;
}
}
}
}
}
}
Chunk::~Chunk() {
for(int i = 0; i < SIZE_CHUNK_X; i++) {
for(int j = 0; j < SIZE_CHUNK_Z; j++) {
delete[] blocks[i][j];
}
delete[] blocks[i];
}
delete[] blocks;
glDeleteBuffers(1, &vbo);
glDeleteVertexArrays(1, &vao);
}
/* Get the type of the block (0 = air block)
*/
int Chunk::getBlock(int x, int y, int z) {
return blocks[x][y][z];
}
/* Set the type of block
*/
void Chunk::setBlock(int x, int y, int z, int type) {
blocks[x][y][z] = type;
changed = true;
}
void Chunk::updateChunk() {
changed = false;
ShapeVertex* vertices = (ShapeVertex*)malloc(sizeof(ShapeVertex) * SIZE_CHUNK_X * SIZE_CHUNK_Y * SIZE_CHUNK_Z * 36);
int i = 0;
int type;
std::vector<std::pair<float, float>> texturesCoord;
for(int x = 0; x < SIZE_CHUNK_X; x++) {
for(int y = 0; y < SIZE_CHUNK_Y; y++) {
for(int z = 0; z < SIZE_CHUNK_Z; z++) {
type = blocks[x][y][z];
//std::cout << z << std::endl;
//std::cout << type << std::endl;
if(type == -1) { // air block
continue;
}
//get the textures Coordinates on Texture atlas
texturesCoord = TexturesAtlas::getTexturesCoord(type);
//std::cout << texturesCoord[0].first << std::endl;
// Inverser y et z, renverse le cube
// top -> front OK
if(y < SIZE_CHUNK_Y - 1 && blocks[x][y + 1][z] == - 1) {
vertices[i++] = ShapeVertex(glm::vec3(x, z, y + 1), glm::vec3(0., 0., 1.), glm::vec2(texturesCoord[1].first, texturesCoord[1].second + OFFSET));
vertices[i++] = ShapeVertex(glm::vec3(x, z + 1, y + 1), glm::vec3(0., 0., 1.), glm::vec2(texturesCoord[1].first, texturesCoord[1].second));
vertices[i++] = ShapeVertex(glm::vec3(x + 1, z + 1, y + 1), glm::vec3(0., 0., 1.), glm::vec2(texturesCoord[1].first + OFFSET, texturesCoord[1].second));
vertices[i++] = ShapeVertex(glm::vec3(x + 1, z + 1, y + 1), glm::vec3(0., 0., 1.), glm::vec2(texturesCoord[1].first + OFFSET, texturesCoord[1].second));
vertices[i++] = ShapeVertex(glm::vec3(x + 1, z, y + 1), glm::vec3(0., 0., 1.), glm::vec2(texturesCoord[1].first + OFFSET, texturesCoord[1].second + OFFSET));
vertices[i++] = ShapeVertex(glm::vec3(x, z, y + 1), glm::vec3(0., 0., 1.), glm::vec2(texturesCoord[1].first, texturesCoord[1].second + OFFSET));
}
//front -> bottom
if(z > 0 && blocks[x][y][z - 1] == - 1) {
vertices[i++] = ShapeVertex(glm::vec3(x, z, y), glm::vec3(0., 1., 0.), glm::vec2(texturesCoord[5].first, texturesCoord[5].second + OFFSET));
vertices[i++] = ShapeVertex(glm::vec3(x, z, y + 1), glm::vec3(0., 1., 0.), glm::vec2(texturesCoord[5].first, texturesCoord[5].second));
vertices[i++] = ShapeVertex(glm::vec3(x + 1, z, y), glm::vec3(0., 1., 0.), glm::vec2(texturesCoord[5].first + OFFSET, texturesCoord[5].second + OFFSET));
vertices[i++] = ShapeVertex(glm::vec3(x + 1, z, y), glm::vec3(0., 1., 0.), glm::vec2(texturesCoord[5].first + OFFSET, texturesCoord[5].second + OFFSET));
vertices[i++] = ShapeVertex(glm::vec3(x, z, y + 1), glm::vec3(0., 1., 0.), glm::vec2(texturesCoord[5].first, texturesCoord[5].second));
vertices[i++] = ShapeVertex(glm::vec3(x + 1, z, y + 1), glm::vec3(0., 1., 0.), glm::vec2(texturesCoord[5].first + OFFSET, texturesCoord[5].second));
}
// right -> right
if(x < SIZE_CHUNK_X - 1 && blocks[x + 1][y][z] == - 1) {
vertices[i++] = ShapeVertex(glm::vec3(x + 1, z, y), glm::vec3(1., 0., 0.), glm::vec2(texturesCoord[2].first, texturesCoord[2].second + OFFSET));
vertices[i++] = ShapeVertex(glm::vec3(x + 1, z, y + 1), glm::vec3(1., 0., 0.), glm::vec2(texturesCoord[2].first + OFFSET, texturesCoord[2].second + OFFSET));
vertices[i++] = ShapeVertex(glm::vec3(x + 1, z + 1, y), glm::vec3(1., 0., 0.), glm::vec2(texturesCoord[2].first, texturesCoord[2].second));
vertices[i++] = ShapeVertex(glm::vec3(x + 1, z, y + 1), glm::vec3(1., 0., 0.), glm::vec2(texturesCoord[2].first + OFFSET, texturesCoord[2].second + OFFSET));
vertices[i++] = ShapeVertex(glm::vec3(x + 1, z + 1, y + 1), glm::vec3(1., 0., 0.), glm::vec2(texturesCoord[2].first + OFFSET, texturesCoord[2].second));
vertices[i++] = ShapeVertex(glm::vec3(x + 1, z + 1, y), glm::vec3(1., 0., 0.), glm::vec2(texturesCoord[2].first, texturesCoord[2].second));
}
// left -> left
if(x > 0 && blocks[x - 1][y][z] == - 1) {
vertices[i++] = ShapeVertex(glm::vec3(x, z, y), glm::vec3(1., 0., 0.), glm::vec2(texturesCoord[3].first + OFFSET, texturesCoord[3].second + OFFSET));
vertices[i++] = ShapeVertex(glm::vec3(x, z + 1, y), glm::vec3(1., 0., 0.), glm::vec2(texturesCoord[3].first + OFFSET, texturesCoord[3].second));
vertices[i++] = ShapeVertex(glm::vec3(x, z, y + 1), glm::vec3(1., 0., 0.), glm::vec2(texturesCoord[3].first, texturesCoord[3].second + OFFSET));
vertices[i++] = ShapeVertex(glm::vec3(x, z, y + 1), glm::vec3(1, 0., 0.), glm::vec2(texturesCoord[3].first, texturesCoord[3].second + OFFSET));
vertices[i++] = ShapeVertex(glm::vec3(x, z + 1, y), glm::vec3(1., 0., 0.), glm::vec2(texturesCoord[3].first + OFFSET, texturesCoord[3].second));
vertices[i++] = ShapeVertex(glm::vec3(x, z + 1, y + 1), glm::vec3(1., 0., 0.), glm::vec2(texturesCoord[3].first, texturesCoord[3].second));
}
// back -> top
if(z < SIZE_CHUNK_Z - 1 && blocks[x][y][z + 1] == - 1) {
vertices[i++] = ShapeVertex(glm::vec3(x, z + 1, y), glm::vec3(0., 1., 0.), glm::vec2(texturesCoord[0].first + OFFSET, texturesCoord[0].second + OFFSET));
vertices[i++] = ShapeVertex(glm::vec3(x, z + 1, y + 1), glm::vec3(0., 1., 0.), glm::vec2(texturesCoord[0].first + OFFSET, texturesCoord[0].second));
vertices[i++] = ShapeVertex(glm::vec3(x + 1, z + 1, y + 1), glm::vec3(0., 1., 0.), glm::vec2(texturesCoord[0].first, texturesCoord[0].second));
vertices[i++] = ShapeVertex(glm::vec3(x + 1, z + 1, y + 1), glm::vec3(0., 1., 0.), glm::vec2(texturesCoord[0].first, texturesCoord[0].second));
vertices[i++] = ShapeVertex(glm::vec3(x + 1, z + 1, y), glm::vec3(0., 1., 0.), glm::vec2(texturesCoord[0].first, texturesCoord[0].second + OFFSET));
vertices[i++] = ShapeVertex(glm::vec3(x, z + 1, y), glm::vec3(0., 1., 0.), glm::vec2(texturesCoord[0].first + OFFSET, texturesCoord[0].second + OFFSET));
}
// bottom -> back
if(y > 0 && blocks[x][y - 1][z] == - 1) {
vertices[i++] = ShapeVertex(glm::vec3(x, z, y), glm::vec3(0., 0., 1.), glm::vec2(texturesCoord[4].first + OFFSET, texturesCoord[4].second + OFFSET));
vertices[i++] = ShapeVertex(glm::vec3(x, z + 1, y), glm::vec3(0., 0., 1.), glm::vec2(texturesCoord[4].first + OFFSET, texturesCoord[4].second));
vertices[i++] = ShapeVertex(glm::vec3(x + 1, z + 1, y), glm::vec3(0., 0., 1.), glm::vec2(texturesCoord[4].first, texturesCoord[4].second));
vertices[i++] = ShapeVertex(glm::vec3(x + 1, z + 1, y), glm::vec3(0., 0., 1.), glm::vec2(texturesCoord[4].first, texturesCoord[4].second));
vertices[i++] = ShapeVertex(glm::vec3(x + 1, z, y), glm::vec3(0., 0., 1.), glm::vec2(texturesCoord[4].first, texturesCoord[4].second + OFFSET));
vertices[i++] = ShapeVertex(glm::vec3(x, z, y), glm::vec3(0., 0., 1.), glm::vec2(texturesCoord[4].first + OFFSET, texturesCoord[4].second + OFFSET));
}
}
}
}
size = i;
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, size * sizeof(ShapeVertex), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
free(vertices);
}
void Chunk::renderChunk() {
//std::cout << "draw0 : " << changed << std::endl;
if(changed) {
updateChunk();
}
if(!size) {
return;
}
//glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBindVertexArray(vao);
glEnableVertexAttribArray(VERTEX_ATTR_POSITION);
glEnableVertexAttribArray(VERTEX_ATTR_NORMAL);
glEnableVertexAttribArray(VERTEX_ATTR_TEXTURE);
glVertexAttribPointer(VERTEX_ATTR_POSITION, 3, GL_FLOAT, GL_FALSE, sizeof(ShapeVertex), 0);
glVertexAttribPointer(VERTEX_ATTR_NORMAL, 3, GL_FLOAT, GL_FALSE, sizeof(ShapeVertex),
(const GLvoid*)(offsetof(ShapeVertex, normal)));
glVertexAttribPointer(VERTEX_ATTR_TEXTURE, 2, GL_FLOAT, GL_FALSE, sizeof(ShapeVertex),
(const GLvoid*)(offsetof(ShapeVertex, texCoords)));
glDrawArrays(GL_TRIANGLES, 0, size);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void Chunk::destroyBlock(int x, int y, int z) {
std::cout << " chunk destroy block coord : " << x << " " << y << " " << z << std::endl;
blocks[x][y][z] = -1;
changed = true;
}
/* Return true if the block is not a air block (-1)
*/
bool Chunk::checkBlock(glm::vec3 position) {
return (blocks[(int)position.x][(int)position.z][(int)position.y] != -1);
}
std::ostream& operator<<(std::ostream& os, const Chunk& c) {
for(int i = 0; i < SIZE_CHUNK_X; i++) {
for(int j = 0; j < SIZE_CHUNK_Y; j++) {
for(int k = 0; k < SIZE_CHUNK_Z; k++) {
//os << (int)c.blocks[i][j][k].type << " ";
os << c.blocks[i][j][k];
}
}
os << std::endl;
}
os << std::endl;
return os;
}
}
| true |
1f9b2e3132121666957aa6cc691112f270287b90 | C++ | norshtein/train | /poj3440/main.cpp | UTF-8 | 1,905 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include<algorithm>
#include<vector>
#include<set>
#include<string>
#include<cmath>
#include<cstdio>
using namespace std;
const char* prefix[] = {"","Probability of covering 1 tile = ","Probability of covering 2 tiles = ","Probability of covering 3 tiles = ","Probability of covering 4 tiles = "};
const double PI = acos(-1.0);
int main()
{
int T;
int m,n;
double t,c;
scanf("%d",&T);
for(int caseNum = 1;caseNum <= T;caseNum++)
{
double area[5] = {0};
scanf("%d%d%lf%lf",&m,&n,&t,&c);
printf("Case %d:\n",caseNum);
double totalArea = m * n * t * t;
if(m < n)
swap(m,n);
if(m == 1 && n == 1)
{
printf("%s%.4f%%\n",prefix[1],100.0);
for(int i = 2;i <= 4;i++)
printf("%s%.4f%%\n",prefix[i],0.0);
putchar('\n');
continue;
}
else if(n == 1)
{
area[1] = (m - 2) * (t - c) * t + 2 * (t - c / 2) * t;
area[2] = (m - 2) * c * t + 2 * c * t / 2;
}
else
{
int inner = (m - 2) * (n - 2);
int border = (2 * m + 2 * n - 8);
int corner = 4;
area[1] += inner * (t - c) * (t - c);
area[1] += border * (t - c) * (t - c / 2);
area[1] += corner * (t - c / 2) * (t - c / 2);
area[2] += inner * 2 * c * (t - c);
area[2] += border * (3 * c * t / 2 - c * c);
area[2] += corner * (c * t - c * c / 2);
area[4] += inner * PI * c * c / 4;
area[4] += border * PI * c * c / 8;
area[4] += corner * PI * c * c / 16;
area[3] = totalArea - area[1] - area[2] - area[4];
}
for(int i = 1;i <= 4;i++)
printf("%s%.4f%%\n",prefix[i],area[i] / totalArea * 100);
putchar('\n');
}
return 0;
}
| true |
e6ef6d3390c0ba606c3c4f5822790400834f0be6 | C++ | smhaaker/atari-arduino | /AtariController/AtariController/AtariController.ino | UTF-8 | 1,281 | 2.96875 | 3 | [] | no_license | #include "Keyboard.h" //include the library used for keyboard commands
void setup() {
Serial.begin(9600);
delay(5000);
pinMode(3, INPUT_PULLUP); //define all pins uses as inputs
pinMode(4, INPUT_PULLUP);
pinMode(5, INPUT_PULLUP);
pinMode(6, INPUT_PULLUP);
pinMode(7, INPUT_PULLUP);
pinMode(8, OUTPUT);
Keyboard.begin();
}
void loop() {
int Fire = digitalRead(3); //define Fire as read pin 3
int Up = digitalRead(7); //define Up as read pin 4
int Down = digitalRead(6); //define Down as read pin 5
int Right = digitalRead(5); //define Right as read pin 6
int Left = digitalRead(4); //define Left as read pin 7
if (Fire == LOW)
{
Keyboard.press(32); // If fire key (which is pin 3) goes low to press key 32 (spacebar)
}
if (Fire == HIGH)
{
Keyboard.release(32); // If fire key (which is pin 3) goes high to release key 32 (spacebar)
}
if (Up == LOW){
Keyboard.press(119);
}
if (Up == HIGH){
Keyboard.release(119);
}
if (Down == LOW){
Keyboard.press(115);
}
if (Down == HIGH) {
Keyboard.release(115);
}
if (Left == LOW){
Keyboard.press(97);
}
if (Left == HIGH){
Keyboard.release(97);
}
if (Right == LOW)
{
Keyboard.press(100);
}
if (Right == HIGH)
{
Keyboard.release(100);
}
}
| true |
b9e78317e338eb2913e18aa3c4d767d151adeee0 | C++ | rhayatin/C-- | /Turn an image by 90 degree.cpp | UTF-8 | 393 | 2.734375 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
using namespace std;
int main()
{
int r,c;
char arr1[4][8]={"***^***","***|***","***|***","***|***"};
char arr[100][100];
while(1)
{
r=4;c=7;
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
arr[j][r-i-1]=arr1[i][j];
for(int i=0;i<c;i++)
{
for(int j=0;j<r;j++)
cout<<arr[i][j]<<" ";
cout<<"\n";
}
getchar();
}
}
| true |
13c67a1fbe7b233bec72c127466ecae421c78c1a | C++ | reFreshD2/AoN | /main.cpp | UTF-8 | 11,227 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include <string.h>
using namespace std;
struct Element {
char *str;
Element *Prev, *Next;
};
class StringDL {
Element *H, *T;
unsigned int LengthElem;
void Add(const char *elem) {
Element *temp = new Element;
temp->Next = nullptr;
temp->str = new char[LengthElem];
strncpy(temp->str, elem, LengthElem + 1);
if (H != nullptr) {
temp->Prev = T;
T->Next = temp;
T = temp;
} else {
temp->Prev = nullptr;
H = T = temp;
}
}
void ToNull(unsigned int pos, unsigned int n) {
Element *temp = H;
int num = pos / LengthElem;
while (num != 0) {
temp = temp->Next;
num--;
pos -= LengthElem;
}
int i = pos;
while (n != 0) {
if (i < LengthElem) {
temp->str[i] = '*';
} else {
temp = temp->Next;
i = 0;
temp->str[i] = '*';
}
i++;
n--;
}
}
public:
StringDL(const char *str = "", unsigned int length = 5) {
LengthElem = length;
H = T = nullptr;
char *temp = new char[LengthElem + 1];
unsigned int i = 0;
if ((strlen(str) % LengthElem) == 0) {
while (i <= strlen(str)) {
if (((i % LengthElem) == 0) && (i != 0)) {
temp[LengthElem] = '\0';
Add(temp);
}
temp[i % LengthElem] = str[i];
i++;
}
}
if ((strlen(str) % LengthElem) != 0) {
unsigned int LengthCopy = (strlen(str) / LengthElem) * LengthElem;
while (i <= LengthCopy) {
if (((i % LengthElem) == 0) && (i != 0)) {
temp[LengthElem] = '\0';
Add(temp);
}
temp[i % LengthElem] = str[i];
i++;
}
while (i < strlen(str)) {
temp[i % LengthElem] = str[i];
i++;
}
while ((i % LengthElem) != 0) {
temp[i % LengthElem] = '*';
i++;
}
temp[LengthElem] = '\0';
Add(temp);
}
}
StringDL(const StringDL ©) {
H = nullptr;
T = nullptr;
LengthElem = copy.LengthElem;
Element *copyDL = copy.H;
while (copyDL != nullptr) {
Element *temp = new Element;
temp->Next = nullptr;
temp->str = new char[LengthElem + 1];
strcpy(temp->str, copyDL->str);
if (H != nullptr) {
temp->Prev = T;
T->Next = temp;
T = temp;
} else {
temp->Prev = nullptr;
H = T = temp;
}
copyDL = copyDL->Next;
}
}
StringDL &operator=(const StringDL &right) {
if (this == &right) {
return *this;
}
while (H) {
T = H->Next;
delete H;
H = T;
}
LengthElem = right.LengthElem;
Element *rightDL = right.H;
while (rightDL != nullptr) {
Element *temp = new Element;
temp->Next = nullptr;
temp->str = new char[LengthElem + 1];
strcpy(temp->str, rightDL->str);
if (H != nullptr) {
temp->Prev = T;
T->Next = temp;
T = temp;
} else {
temp->Prev = nullptr;
H = T = temp;
}
rightDL = rightDL->Next;
}
return *this;
}
StringDL operator+(const StringDL &right) {
StringDL str(*this);
Element *temp = str.T;
if (temp == nullptr) {
return right;
}
int len = LengthDL();
str.Paste(len, right);
while (temp->str[0] == '*') {
temp = temp->Prev;
temp->Next = nullptr;
}
return str;
}
~StringDL() {
while (H != nullptr) {
T = H->Next;
delete H;
H = T;
}
}
void Print() {
Element *temp = H;
if (T == nullptr){
}
else {
while (temp->Next != nullptr) {
cout << temp->str;
temp = temp->Next;
}
unsigned int i = 0;
while (temp->str[i] != '*' && i < LengthElem) {
cout << temp->str[i];
i++;
}
}
//delete[] temp;
}
unsigned int LengthDL() const {
unsigned int length = 0;
if (H == nullptr) {
return length;
}
Element *temp = H;
while (temp->Next != nullptr) {
length++;
temp = temp->Next;
}
length = length * LengthElem;
unsigned int i = 0;
while (temp->str[i] != '*' && i < LengthElem) {
length++;
i++;
}
//delete[] temp;
return length;
}
int PosSub(const StringDL &sub) {
Element *temp = H;
Element *temp1 = sub.H;
int count = 0, j = 0, countOfEq = 0;
int pos;
while (temp != nullptr) {
int i = 0;
for (i; i < LengthElem; i++) {
if (temp->str[i] == temp1->str[j]) {
countOfEq++;
pos = i;
j++;
if (countOfEq == sub.LengthDL()) {
return (count * LengthElem) + pos - sub.LengthDL() + 1;
}
if (j == sub.LengthElem) {
temp1 = temp1->Next;
j = 0;
}
} else {
temp1 = sub.H;
j = 0;
countOfEq = 0;
}
}
temp = temp->Next;
count++;
}
return -1;
}
StringDL SubStr(unsigned int k, unsigned int n) {
if (k + n > this->LengthDL() || n == 0) {
StringDL res("");
return res;
}
char *res = new char[n + 1];
Element *temp = H;
int num = k / LengthElem;
while (num != 0) {
temp = temp->Next;
num--;
k -= LengthElem;
}
int i = k, j = 0;
while (n != 0) {
if (i < LengthElem) {
res[j] = temp->str[i];
} else {
temp = temp->Next;
i = 0;
res[j] = temp->str[i];
}
j++;
i++;
n--;
}
res[j] = '\0';
StringDL str(res);
return str;
}
int DelSub(const StringDL &sub) {
int pos = this->PosSub(sub);
if (pos == -1) {
return -1;
}
int len = sub.LengthDL(), len1 = LengthDL();
StringDL paste;
paste = this->SubStr(pos + len, LengthDL() - (pos + len));
Paste(pos, paste);
ToNull(len1 - len, len);
Element *temp = H;
if (temp->str[0] == '*') {
temp = temp->Next;
while (temp != nullptr) {
T = temp->Next;
delete temp;
temp = T;
}
temp = H;
temp->Next = nullptr;
} else {
temp = T;
while (temp->str[0] == '*' && temp->Prev != nullptr) {
temp = temp->Prev;
temp->Next = nullptr;
}
}
return 0;
}
void Paste(unsigned int pos, StringDL const &paste) {
Element *temp = H;
Element *temp1 = paste.H;
int num = pos / LengthElem;
while (num != 0 && temp->Next != nullptr) {
temp = temp->Next;
num--;
pos -= LengthElem;
}
int i = pos, j = 0, len = paste.LengthDL();
while (len != 0) {
if (i < LengthElem) {
temp->str[i] = temp1->str[j];
} else {
if (temp->Next != nullptr) {
temp = temp->Next;
} else {
char *str = new char[LengthElem + 1];
for (int k = 0; k < LengthElem; k++) {
str[k] = '*';
}
str[LengthElem] = '\0';
Add(str);
temp = temp->Next;
}
i = 0;
temp->str[i] = temp1->str[j];
}
j++;
if (j == paste.LengthElem) {
temp1 = temp1->Next;
j = 0;
}
i++;
len--;
}
}
};
void Replace(StringDL &str, StringDL &sub, StringDL const &paste) {
if (str.PosSub(sub) != -1) {
StringDL res;
StringDL buf(str);
int p = buf.PosSub(sub);
while (p != -1) {
res = res + buf.SubStr(0, p ) + paste;
buf = buf.SubStr(p + sub.LengthDL(), str.LengthDL() - sub.LengthDL());
p = buf.PosSub(sub);
}
str = res + buf;
/* int pos = str.PosSub(sub);
StringDL temp;
temp = str.SubStr(pos, str.LengthDL() - sub.LengthDL());
str.DelSub(temp);
str = str + paste;
temp.DelSub(sub);
while (temp.PosSub(sub) != -1) {
pos = temp.PosSub(sub);
StringDL str1;
str1 = temp.SubStr(0, temp.LengthDL() - pos);
temp.DelSub(str1);
temp.DelSub(sub);
str = str + str1 + paste;
}*/
}
}
int main() {
setlocale(LC_ALL, "Russian");
StringDL str1(" ", 10);
StringDL str2("The ", 1);
StringDL s = str1 + str2;
s.Print();
cout << endl;
str2.Print();
cout << endl;
Replace(s, str1, str2);
cout << "String 1 after replacing: ";
s.Print();
cout << endl;
/*cout << "String 1: ";
str1.Print();
cout << endl;
cout << "Dlina stroki: " << str1.LengthDL() << endl;
StringDL sub("Tree", 3);
if (str1.PosSub(sub) != -1) {
cout << "Poziciya podstroki \'";
sub.Print();
cout << "\' " << str1.PosSub(sub) << endl;
} else {
cout << "Stroka - ";
sub.Print();
cout << " ne naydena" << endl;
}
sub = str1.SubStr(4, 6);
cout << "Videlena podstroka: ";
sub.Print();
cout << endl;
StringDL str2(str1);
str1.DelSub(sub);
cout << "String 1: ";
str1.Print();
cout << endl;
cout << "String 2: ";
str2.Print();
cout << endl;
str1 = str2;
cout << "str1 = str2: ";
str1.Print();
cout << endl;
StringDL str3(" End.");
str1 + str3;
cout << "str1 + str3: ";
str1.Print();
cout << endl;
StringDL s1("."), s2("...");
Replace(str1, s1, s2);
cout << "String 1 after replacing: ";
str1.Print();
cout << endl;*/
return 0;
} | true |
0b2cb2ba36b19cbc5b18cad3db33d5db1b9dbbf5 | C++ | rafa95359/programacionCOmpetitiva | /HackerRank/palindrome-index.cpp | UTF-8 | 1,088 | 2.953125 | 3 | [] | no_license | #include <bits/stdc++.h>
typedef long long Long;
using namespace std;
pair <bool,int> palindromo(string c){
pair <bool,int>resp;
for(Long i=0;i<c.size()/2 ;i++){
if(c[i] != c[c.size()-i-1]) {
resp.first=false;
resp.second=i;
return resp;
}
}
resp.first=true;
resp.second=-1;
return resp;
}
int main(){
Long n;
cin>>n;
for (Long i=0; i<n; i++){
string palabra;
cin>>palabra;
int index=-1;
int num=palindromo(palabra).second;
if(palindromo(palabra).first)cout<<index<<endl;
else{
string aux;
aux.append(palabra);
aux.erase(num,1);
if(palindromo(aux).first)index=num;
else{
aux.clear();
aux.append(palabra);
aux.erase(palabra.size()-num-1,1);
if(palindromo(aux).first)index=palabra.size()-num-1;
}
cout<<index<<endl;
}
}
return 0;
}
| true |
6ba06f8b7155d8a910923f83100e9449bc02aad4 | C++ | mkmpvtltd1/Webinaria | /src/common/Folders.h | UTF-8 | 1,260 | 2.65625 | 3 | [
"MIT"
] | permissive | #pragma once
class Folders
{
private:
Folders();
static bool BuildPathFromBase(TCHAR *path, const TCHAR *base, const TCHAR *subPath);
public:
static const TCHAR* My(); // Returns path to module which is currently executing.
static const TCHAR* Home(); // Returns path to Webinaria files in My Documents.
static const TCHAR* RecorderUI(); // Returns path to Recorder UI.
static const TCHAR* EditorUI(); // Returns path to Editor UI.
static const TCHAR* FromMine(TCHAR *path, const TCHAR *subPath); // Builds a path using My() as a base.
static const TCHAR* FromHome(TCHAR *path, const TCHAR *subPath); // Builds a path using Home() as a base.
static const TCHAR* FromRecorderUI(TCHAR *path, const TCHAR *subPath); // Builds a path using RecorderUI() as a base.
static const TCHAR* FromEditorUI(TCHAR *path, const TCHAR *subPath); // Builds a path using EditorUI() as a base.
static bool EnsurePathExists(const TCHAR *path);
static bool EnsureHomeFolderExists(); // Creates Webinaria's folder under My Documents and brands it with application icon.
};
| true |
5d9ffbc071b3e586aed89dfd09bf6e980b467cbb | C++ | Peter-Roger/linear_algebra | /tests.cpp | UTF-8 | 11,036 | 3.125 | 3 | [] | no_license | #include <string>
#include <iostream>
#include <sstream>
#include <random>
#include <stdexcept>
#include "linear_algebra.hpp"
using namespace linear_algebra;
class TestMatrix {
public:
void run() {
std::cout << "Running tests:" << std::endl;
// matrix
test_dft_ctor();
test_std_ctor();
test_cpy_ctor();
test_list_init_ctor_sq();
test_list_init_ctor_rec();
test_cpy_asnmt_op();
test_call_out_of_bounds();
test_set();
test_dft_ctor();
// add
test_add_op_NxN();
test_add_invalid_dimensions();
// mult
test_mult_NxN();
test_mult_NxN();
test_mult_NxM();
test_mult_3_terms();
// trans
test_trans_mult_3_terms();
test_trans_matrix_mult();
test_transpose_NxN();
test_transpose_NxM();
test_nested_transpose_NxM();
if (all_cases_passed) {
std::cout << std::endl << "All test cases passed." << std::endl;
} else {
std::cout << std::endl << oss.str();
}
}
//-------------------- TEST MATRIX CLASS --------------------
void test_dft_ctor() {
std::string prompt = __func__;
Matrix<int> m1;
bool condition;
try {
m1.set(0,0,5);
condition = false;
} catch (const std::out_of_range&) {
condition = m1.rows() == 0 && m1.cols() == 0 && m1.size() == 0;
}
test(condition, prompt);
}
void test_std_ctor() {
std::string prompt = __func__;
int n = 5, m = 5;
Matrix<int> m1(n,m);
bool condition = m1.rows() == n && m1.cols() == m && m1.size() == n*m;
test(condition, prompt);
}
void test_cpy_ctor() {
std::string prompt = __func__;
Matrix<int> m1(6,7);
random_int_fill(m1);
Matrix<int> m2(m1);
bool condition = matrix_equal(m1, m2);
test(condition, prompt);
}
void test_list_init_ctor_sq() {
std::string prompt = __func__;
Matrix<double> m1({{1.1, 2.2}, {3.3, 4.4}});
bool condition = m1(0,0) == 1.1 && m1(0,1) == 2.2 && m1(1,0) == 3.3 && m1(1,1) == 4.4;
test(condition, prompt);
}
void test_list_init_ctor_rec() {
std::string prompt = __func__;
Matrix<double> m1({{1.1}, {2.2}});
bool condition = m1(0,0) == 1.1 && m1(1,0) == 2.2;
test(condition, prompt);
}
void test_cpy_asnmt_op() {
std::string prompt = __func__;
Matrix<int> m1(100, 100);
random_int_fill(m1);
Matrix<int> m2 = m1;
bool condition = matrix_equal(m1, m2);
test(condition, prompt);
}
void test_call_out_of_bounds() {
std::string prompt = __func__;
Matrix<int> m1(5,5);
random_int_fill(m1);
bool condition = false;
try {
m1(5,5);
} catch (const std::out_of_range& e) {
condition = true;
}
test(condition, prompt);
}
void test_set() {
std::string prompt = __func__;
Matrix<int> m1(5,5);
m1.set(3,2,10);
bool condition = m1(3,2) == 10;
test(condition, prompt);
}
//-------------------- TEST MATRIX ADDITION --------------------------
void test_add_op_NxN() {
std::string prompt = __func__;
Matrix<int> expected({{1,2,3},
{9,15,8},
{9,9,15}});
Matrix<int> m1({{0,1,2},
{5,10,6},
{7,8,9}});
Matrix<int> m2({{1,1,1},
{4,5,2},
{2,1,6}});
Matrix<int> res = m1 + m2;
bool condition = matrix_equal(res, expected);
test(condition, prompt);
}
void test_add_invalid_dimensions() {
std::string prompt = __func__;
Matrix<int> m1({{1,2},{3,4}});
Matrix<int> m2({{0,1,2},
{5,10,6},
{7,8,9}});
bool condition;
try {
Matrix<int> res = m1 + m2;
condition = false;
} catch (const std::logic_error &e) {
condition = true;
}
test(condition, prompt);
}
//-------------------- TEST MATRIX MULTIPLICATION --------------------
void test_mult_op_NxN() {
std::string prompt = __func__;
Matrix<int> expected({{348,372,334,197},
{495,462,407,201},
{376,435,357,245},
{132,122,116,55}});
Matrix<int> m1({{10,6,5,9},
{3,2,21,15},
{8,7,8,4},
{2,1,4,5}});
Matrix<int> m2({{7,8,3,0},
{24,33,31,27},
{16,17,11,7},
{6,1,7,0}});
Matrix<int> res = m1 * m2;
bool condition = matrix_equal(res, expected);
test(condition, prompt);
}
void test_mult_NxN() {
std::string prompt = __func__;
Matrix<int> expected({{348,372,334,197},
{495,462,407,201},
{376,435,357,245},
{132,122,116,55}});
Matrix<int> m1({{10,6,5,9},
{3,2,21,15},
{8,7,8,4},
{2,1,4,5}});
Matrix<int> m2({{7,8,3,0},
{24,33,31,27},
{16,17,11,7},
{6,1,7,0}});
Matrix<int> res = mult(m1, m2);
bool condition = matrix_equal(res, expected);
test(condition, prompt);
}
void test_mult_NxM() {
std::string prompt = __func__;
Matrix<int> expected({{348,372,334},
{495,462,407},
{376,435,357}});
Matrix<int> m1({{10,6,5,9},
{3,2,21,15},
{8,7,8,4}});
Matrix<int> m2({{7,8,3},
{24,33,31},
{16,17,11},
{6,1,7}});
Matrix<int> res = m1 * m2;
bool condition = matrix_equal(res, expected);
test(condition, prompt);
}
void test_mult_3_terms() {
std::string prompt = __func__;
Matrix<int> expected({{8018,10342,5646,3072},
{10186,12947,7491, 3894},
{8852,11332,6254, 3329}});
Matrix<int> m1({{10,6,5,9},
{3,2,21,15},
{8,7,8,4}});
Matrix<int> m2({{7,8,3},
{24,33,31},
{16,17,11},
{6,1,7}});
Matrix<int> m3({{5,4,8,2},
{7,7,5,1},
{11,19,3,6}});
Matrix<int> res = m1 * m2 * m3;
bool condition = matrix_equal(res, expected);
test(condition, prompt);
}
void test_trans_mult_3_terms() {
std::string prompt = __func__;
Matrix<int> expected({{8018, 10186, 8852},
{10342, 12947, 11332},
{5646, 7491, 6254},
{3072, 3894, 3329}});
Matrix<int> m1({{10,6,5,9},
{3,2,21,15},
{8,7,8,4}});
Matrix<int> m2({{7,8,3},
{24,33,31},
{16,17,11},
{6,1,7}});
Matrix<int> m3({{5,4,8,2},
{7,7,5,1},
{11,19,3,6}});
Matrix<int> res = trans(m1 * m2 * m3);
bool condition = matrix_equal(res, expected);
test(condition, prompt);
}
void test_trans_matrix_mult() {
std::string prompt = __func__;
Matrix<int> expected({{64, 50, 14},
{32, 25, 7},
{12, 11, 3},
{34, 16, 5}});
Matrix<int> m1({{6,3,1,4},
{8,4,2,1}});
Matrix<int> m2({{8,3,1},
{2,4,1}});
Matrix<int> res = trans(m1) * m2;
bool condition = matrix_equal(res, expected);
test(condition, prompt);
}
//-------------------- TEST MATRIX TRANSPOSE --------------------
void test_transpose_NxN() {
std::string prompt = __func__;
int n = 10;
Matrix<int> m1(n,n);
random_int_fill(m1);
Matrix<int> t = trans(m1);
bool condition = true;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
condition = t(i, j) == m1(j, i);
if (!(condition)) {
break;
}
}
}
test(condition, prompt);
}
void test_transpose_NxM() {
std::string prompt = __func__;
int n = 10, m = 15;
Matrix<int> m1(n, m);
random_int_fill(m1);
Matrix<int> t = trans(m1);
bool condition = true;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
condition = t(i, j) == m1(j, i);
if (!(condition)) {
break;
}
}
}
test(condition, prompt);
}
void test_nested_transpose_NxM() {
std::string prompt = __func__;
int n = 2, m = 5;
Matrix<int> m1(n, m);
random_int_fill(m1);
Matrix<int> t = trans(m1);
Matrix<int> tt = trans(trans(m1));
bool condition = matrix_equal(tt, m1);
test(condition, prompt);
}
protected:
void test(bool condition, const std::string& prompt) {
if (condition) {
std::cout << "✓";
} else {
all_cases_passed = false;
std::cout << "F";
oss << "TEST FAILED: " << prompt << std::endl;
}
}
template<typename T>
bool matrix_equal(Matrix<T> m1, Matrix<T> m2) {
if (m1.rows() != m2.rows() || m1.cols() != m2.cols()) {
return false;
} else {
for (int i = 0; i < m1.rows(); ++i) {
for (int j = 0; j < m1.cols(); ++j) {
if (m1(i, j) != m2(i, j)) {
return false;
}
}
}
}
return true;
}
void random_int_fill(Matrix<int> &matrix) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> uni_dist(-9, 9);
for (int i = 0; i < matrix.rows(); i++) {
for (int j = 0; j < matrix.cols(); j++) {
matrix.set(i, j, uni_dist(gen));
}
}
}
private:
std::ostringstream oss;
bool all_cases_passed = true;
};
int main() {
TestMatrix suite;
suite.run();
}; | true |
78072367c11f2f580534f941fe0f64c6bc5c1952 | C++ | ValentinUsedREKTItsSuperEffective/REKTgine | /src/Screen.cpp | UTF-8 | 225 | 2.59375 | 3 | [] | no_license | #include "Screen.hpp"
unsigned int Screen::width = 0;
unsigned int Screen::height = 0;
Screen::Screen(unsigned int width, unsigned int height){
Screen::width = width;
Screen::height = height;
}
Screen::~Screen(){}
| true |
bd7615728fb70a5c0a91a885ed61766d87b48f62 | C++ | jlewis2112/CPTS-440 | /HW9 Final/Agent.cc | UTF-8 | 37,297 | 2.734375 | 3 | [] | no_license | // Agent.cc
//
// This code works only for the testworld that comes with the simulator.
//Joseph
//Lewis
//HW 9
//I tried moving my global variables to the .h file. I had some errors doing that.
#include <iostream>
#include <list>
#include "Agent.h"
using namespace std;
int stench[11][11]; //array of stench locations
int breeze[11][11];//breeze locations
int frontier[11][11];//possible pit locations not close to stench
int wumpusX = 0; //wumpus locations
int wumpusY = 0;
int goldX = 0;//gold location
int goldY = 0;
int pits[11][11]; //array of pit locations
int visited[11][11]; //array of visited locations
int safe[11][11]; //array of safe locations
int noWumpus[11][11];//key areas by stenches that has no wumpus
int maxSize = 3; //assume size 3 and then adjust
int locx = 1; //agents location
int locy = 1;
int rightF = 1;//agent direction facing
int leftF = 0;
int upF = 0;
int downF = 0;
int hasGold = 0;//having gold
int foundMaxSize = 0;//bumped into the highest x or Y wall
int Danger = 0;//if breeze or stench Danger = 1
int nextx = 0;//The target safe location to go to
int nexty = 0;
int hailx = 0;//stench locations to shoot a hail marry shot
int haily = 0;
int firstMove = 0;//first move of a game
int firstTry = 1;//first try of multiple tries
int hasToShoot = 0;//does the user have to shoot
int hasArrow = 1; //does the user have the arrow
int inPit = 0; //determine if agent fell in the pit
int deadWumpus = 0;
int takeTheShot = 0;//take the shot this turn
int hailMarry = 0;//had to shoot to find wumpus
Action action;
//constructor
Agent::Agent ()
{
}
//deconstructor
Agent::~Agent ()
{
}
//initailizes the agent
void Agent::Initialize ()
{
if(firstTry == 1)//set up arrays if first try
{
for(int x = 0; x < 10; x++)
{
for(int y = 0; y < 10; y++)
{
stench[x][y] = 0;
pits[x][y] = 0;
visited[x][y] = 0;
safe[x][y] = 0;
breeze[x][y] = 0;
frontier[x][y] = 0;
noWumpus[x][y] = 0;
}
}
}
//if not first try, then have all safe locations marked
//defensive programing
if(firstTry == 0)
{
for(int x = 1; x < 10; x++)
{
for(int y = 0; y < 10; y++)
{
searchEngine.RemoveSafeLocation(locx,locy-1);
}
}
for(int x = 1; x < 10; x++)
{
for(int y = 0; y < 10; y++)
{
if(visited[x][y] == 1 || safe[x][y] == 1)
{
searchEngine.AddSafeLocation(x,y);
}
}
}
}
if(wumpusX != 0 && wumpusY != 0)
{
searchEngine.RemoveSafeLocation(wumpusX, wumpusY);
safe[wumpusX][wumpusY] = 0;
}
//set defualt values
searchEngine.AddSafeLocation(1,1);
firstMove = 1;
firstTry = 0;
visited[1][1] = 1;
actionList.clear();
hasGold = 0;
locx = 1;
locy = 1;
rightF = 1;//set facing
leftF = 0;
upF = 0;
downF = 0;
deadWumpus = 0;//wumpus is back alive
hasArrow = 1;//set arrow
inPit = 0;
}
Action Agent::Process (Percept& percept)
{
list<Action> actionList2;
Danger = 0;
cout << "wumpus \n";
cout << wumpusX;
cout << wumpusY;
cout << "\n";
if(wumpusX != 0 && wumpusY != 0 && deadWumpus == 0)
{
searchEngine.RemoveSafeLocation(wumpusX, wumpusY);
safe[wumpusX][wumpusY] = 0;
}
if(percept.Bump)//if far end bump we know the size of the world
{
if(rightF == 1)
{
foundMaxSize = 1;
maxSize = locx;
}
else if(upF == 1)
{
foundMaxSize = 1;
maxSize = locy;
}
}
else if(action == GOFORWARD && firstMove == 0)//update cordinates and facing
{
if(rightF == 1)
{
locx += 1;
}
else if(leftF == 1)
{
locx -= 1;
}
else if(upF == 1)
{
locy += 1;
}
else if(downF == 1)
{
locy -= 1;
}
}
else if(action == TURNRIGHT)
{
if(rightF == 1)
{
rightF = 0;
downF = 1;
}
else if(leftF == 1)
{
leftF = 0;
upF = 1;
}
else if(upF == 1)
{
upF = 0;
rightF = 1;
}
else if(downF == 1)
{
downF = 0;
leftF = 1;
}
}
else if(action == TURNLEFT)
{
if(rightF == 1)
{
rightF = 0;
upF = 1;
}
else if(leftF == 1)
{
leftF = 0;
downF = 1;
}
else if(upF == 1)
{
upF = 0;
leftF = 1;
}
else if(downF == 1)
{
downF = 0;
rightF = 1;
}
}
else if(action == SHOOT)
{
hasArrow = 0;
if(!percept.Scream)//did the agent miss
{
if(rightF == 1)
{
noWumpus[locx+1][locy] = 1;
}
else if(leftF == 1)
{
noWumpus[locx-1][locy] = 1;
}
else if(upF == 1)
{
noWumpus[locx][locy+1] = 1;
}
else if(downF == 1)
{
noWumpus[locx][locy-1] = 1;
}
}
}
cout << "cord\n";
cout << locx;
cout << ", ";
cout << locy;
cout << "\n";
firstMove = 0;
visited[locx][locy] = 1;
frontier[locx][locy] = 0;//not a pit
if(percept.Scream)//if scream mark wumpus safe for the round
{
cout<<"\n marked wumpus safe\n";
deadWumpus = 1;
hasToShoot = 1;
if(wumpusX == 0 && wumpusY == 0)
{
if(rightF == 1)
{
wumpusX = locx + 1;
wumpusY = locy;
}
else if(leftF == 1)
{
wumpusX = locx - 1;
wumpusY = locy;
}
else if(upF == 1)
{
wumpusX = locx;
wumpusY = locy + 1;
}
else if(downF == 1)
{
wumpusX = locx;
wumpusY = locy - 1;
}
}
searchEngine.AddSafeLocation(wumpusX,wumpusY);
safe[wumpusX][wumpusY] = 1;
}
if(percept.Stench && deadWumpus == 0)//stench mark the location and find wumpus
{
Danger = 1;
stench[locx][locy] = 1;
if(locx > 1)//check left if not by a wall
{
if(stench[locx-1][locy+1] == 1)//diagnal
{
if(safe[locx][locy+1] == 1)//safe check
{
wumpusX = locx - 1;
wumpusY = locy;
searchEngine.RemoveSafeLocation(locx-1,locy);
}
}
if(stench[locx-1][locy-1] == 1)
{
if(safe[locx][locy-1] == 1)
{
wumpusX = locx - 1;
wumpusY = locy;
searchEngine.RemoveSafeLocation(locx-1,locy);
}
}
}
if(locy > 1)//check down
{
if(stench[locx-1][locy-1] == 1)
{
if(safe[locx-1][locy] == 1)
{
wumpusX = locx;
wumpusY = locy - 1;
searchEngine.RemoveSafeLocation(locx,locy-1);
}
}
if(stench[locx+1][locy-1] == 1)
{
if(safe[locx+1][locy] == 1)
{
wumpusX = locx;
wumpusY = locy - 1;
searchEngine.RemoveSafeLocation(locx,locy-1);
}
}
}
if(locx < maxSize)//check right
{
if(stench[locx+1][locy-1] == 1)
{
if(safe[locx][locy-1] == 1)
{
wumpusX = locx + 1;
wumpusY = locy;
searchEngine.RemoveSafeLocation(locx+1,locy);
}
}
if(stench[locx+1][locy+1] == 1)
{
if(safe[locx][locy+1] == 1)
{
wumpusX = locx + 1;
wumpusY = locy;
searchEngine.RemoveSafeLocation(locx+1,locy);
}
}
}
if(locy < maxSize)//check up
{
if(stench[locx+1][locy+1] == 1)
{
if(safe[locx+1][locy] == 1)
{
wumpusX = locx;
wumpusY = locy + 1;
searchEngine.RemoveSafeLocation(locx,locy+1);
}
}
if(stench[locx-1][locy+1] == 1)
{
if(safe[locx-1][locy] == 1)
{
wumpusX = locx;
wumpusY = locy + 1;
searchEngine.RemoveSafeLocation(locx,locy+1);
}
}
}
}
if(wumpusX == 0 && wumpusY == 0)//find wumpus new rule
{
//rule 2 if 3 of the ajacent stench locations are safe, pits, or frontier,
//then we have found the wumpus
for(int x = 0; x < 10; x++)
{
for(int y = 0; y < 10; y++)
{
if(stench[x][y] == 1)//if found stench confirm wupus location
{
int conUp = 0;
int conDown = 0;
int conLeft = 0;
int conRight = 0;
if(x > 1)//check left
{
if(visited[x-1][y] == 1 || pits[x-1][y] == 1 || frontier[x-1][y] == 1)
{
noWumpus[x-1][y] = 1;
conLeft = 1;
}
}
else
{
conLeft = 1;
}
if(y > 1)//check down
{
if(visited[x][y-1] == 1 || pits[x][y-1] == 1 || frontier[x][y-1] == 1)
{
noWumpus[x][y-1] = 1;
conDown = 1;
}
}
else
{
conDown = 1;
}
if(foundMaxSize == 0)
{
if(x < 9)
{
if(visited[x+1][y] == 1 || pits[x+1][y] == 1 || frontier[x+1][y] == 1)
{
noWumpus[x+1][y] = 1;
conRight = 1;
}
}
else
{
conRight = 1;
}
if(y < 9)
{
if(visited[x][y+1] == 1 || pits[x][y+1] == 1 || frontier[x][y+1] == 1)
{
noWumpus[x][y+1] = 1;
conUp = 1;
}
}
else
{
conUp = 1;
}
}
else
{
if(x < maxSize)
{
if(visited[x+1][y] == 1 || pits[x+1][y] == 1 || frontier[x+1][y] == 1)
{
noWumpus[x+1][y] = 1;
conRight = 1;
}
}
else
{
conRight = 1;
}
if(y < maxSize)
{
if(visited[x][y+1] == 1 || pits[x][y+1] == 1 || frontier[x][y+1] == 1)
{
noWumpus[x][y+1] = 1;
conUp = 1;
}
}
else
{
conUp = 1;
}
}
//check to see if we found the wumpus
if(conUp == 1 && conDown == 1 && conLeft == 1 && conRight == 0)
{
//wumpus is found right
wumpusX = x+1;
wumpusY = y;
searchEngine.RemoveSafeLocation(wumpusX, wumpusY);
}
else if(conUp == 1 && conDown == 1 && conLeft == 0 && conRight == 1)
{
//wumpus is found Left
wumpusX = x-1;
wumpusY = y;
searchEngine.RemoveSafeLocation(wumpusX, wumpusY);
}
else if(conUp == 1 && conDown == 0 && conLeft == 1 && conRight == 1)
{
//wumpus is found Down
wumpusX = x;
wumpusY = y-1;
searchEngine.RemoveSafeLocation(wumpusX, wumpusY);
}
else if(conUp == 0 && conDown == 1 && conLeft == 1 && conRight == 1)
{
//wumpus is found Up
wumpusX = x;
wumpusY = y+1;
searchEngine.RemoveSafeLocation(wumpusX, wumpusY);
}
}
}
}
}
if(percept.Breeze && percept.Stench && wumpusX == 0 && wumpusY == 0)//no safe or frontier locations added
{
Danger = 1;
breeze[locx][locy] = 1;
}
else if(percept.Breeze)
{
cout << "\nmarking possible pits!!\n";
Danger = 1;
breeze[locx][locy] = 1;
//mark possible pits
if(visited[locx][locy+1] == 0 && pits[locx][locy+1] == 0 && !(wumpusX == locx && wumpusY == locy+1))
{
frontier[locx][locy+1] = 1;
}
if(visited[locx][locy-1] == 0 && pits[locx][locy-1] == 0 && !(wumpusX == locx && wumpusY == locy-1))
{
frontier[locx][locy-1] = 1;
}
if(visited[locx+1][locy] == 0 && pits[locx+1][locy] == 0 && !(wumpusX == locx+1 && wumpusY == locy))
{
frontier[locx+1][locy] = 1;
}
if(visited[locx-1][locy] == 0 && pits[locx-1][locy] == 0 && !(wumpusX == locx-1 && wumpusY == locy))
{
frontier[locx-1][locy] = 1;
}
}
//new rule to find pits if breeze spot has 3 ajacent safe spots, then
//the 4th spot has a pit and can't be in frontier
for(int x = 0; x < 10; x++)//
{
for(int y = 0; y < 10; y++)
{
if(breeze[x][y] == 1)//if found breeze confirm pit location
{
int conUp = 0;
int conDown = 0;
int conLeft = 0;
int conRight = 0;
if(x > 1)//check left
{
if(visited[x-1][y] == 1)
{
conLeft = 1;
}
}
else
{
conLeft = 1;
}
if(y > 1)//check down
{
if(visited[x][y-1] == 1)
{
conDown = 1;
}
}
else
{
conDown = 1;
}
if(foundMaxSize == 0)
{
if(x < 9)
{
if(visited[x+1][y] == 1)
{
conRight = 1;
}
}
else
{
conRight = 1;
}
if(y < 9)
{
if(visited[x][y+1] == 1)
{
conUp = 1;
}
}
else
{
conUp = 1;
}
}
else
{
if(x < maxSize)
{
if(visited[x+1][y] == 1)
{
conRight = 1;
}
}
else
{
conRight = 1;
}
if(y < maxSize)
{
if(visited[x][y+1] == 1)
{
conUp = 1;
}
}
else
{
conUp = 1;
}
}
//check to see if we found a pit
if(conUp == 1 && conDown == 1 && conLeft == 1 && conRight == 0)
{
//pit is found right
pits[x+1][y] = 1;
frontier[x+1][y] = 0;
searchEngine.RemoveSafeLocation(x+1, y);
}
else if(conUp == 1 && conDown == 1 && conLeft == 0 && conRight == 1)
{
//pit is found Left
pits[x-1][y] = 1;
frontier[x-1][y] = 0;
searchEngine.RemoveSafeLocation(x-1, y);
}
else if(conUp == 1 && conDown == 0 && conLeft == 1 && conRight == 1)
{
//pit is found Down
pits[x][y-1] = 1;
frontier[x][y-1] = 0;
searchEngine.RemoveSafeLocation(x, y-1);
}
else if(conUp == 0 && conDown == 1 && conLeft == 1 && conRight == 1)
{
//pit is found Up
pits[x][y+1] = 1;
frontier[x][y+1] = 0;
searchEngine.RemoveSafeLocation(x, y+1);
}
}
}
}
//pit rule end
//once wumpus found find safe spots next to stenches
if(wumpusX != 0 && wumpusY != 0)
{
if(wumpusX > 1)//check left if not by a wall
{
if(wumpusY > 1)//left bottom
{
if((visited[wumpusX][wumpusY-1] == 1 && breeze[wumpusX][wumpusY-1] == 0) || (visited[wumpusX-1][wumpusY] == 1 && breeze[wumpusX-1][wumpusY] == 0))
{
safe[wumpusX-1][wumpusY-1] = 1;
searchEngine.AddSafeLocation(wumpusX-1,wumpusY-1);
}
}
if(wumpusY < maxSize || (foundMaxSize == 0 && wumpusY < 9))//left top
{
if((visited[wumpusX][wumpusY+1] == 1 && breeze[wumpusX][wumpusY+1] == 0) || (visited[wumpusX-1][wumpusY] == 1 && breeze[wumpusX-1][wumpusY] == 0))
{
safe[wumpusX-1][wumpusY+1] = 1;
searchEngine.AddSafeLocation(wumpusX-1,wumpusY+1);
}
}
}
if(wumpusX < maxSize || (foundMaxSize == 0 && wumpusX < 9))//check right
{
if(wumpusY > 1)//right down
{
if((visited[wumpusX][wumpusY-1] == 1 && breeze[wumpusX][wumpusY-1] == 0) || (visited[wumpusX+1][wumpusY] == 1 && breeze[wumpusX+1][wumpusY] == 0))
{
safe[wumpusX+1][wumpusY-1] = 1;
searchEngine.AddSafeLocation(wumpusX+1,wumpusY-1);
}
}
if(wumpusY < maxSize || (foundMaxSize == 0 && wumpusY < 9))//right up
{
if((visited[wumpusX][wumpusY+1] == 1 && breeze[wumpusX][wumpusY+1] == 0) || (visited[wumpusX+1][wumpusY] == 1 && breeze[wumpusX+1][wumpusY] == 0))
{
safe[wumpusX+1][wumpusY+1] = 1;
searchEngine.AddSafeLocation(wumpusX+1,wumpusY+1);
}
}
}
}
if(percept.Glitter)//pick up the gold and head home
{
goldX = locx;
goldY = locy;
hasGold = 1;
searchEngine.AddSafeLocation(locx,locy);
actionList.clear();
action = GRAB;
return GRAB;
}
if(takeTheShot == 1 && actionList.empty() && hasArrow == 1)
{
cout << "\nFIRE!!!!\n";
takeTheShot = 0;
action = SHOOT;
return SHOOT;
}
if(maxSize < locx)//update max world size
{
maxSize = locx;
}
if(maxSize < locy)
{
maxSize = locy;
}
if(Danger == 0)//no breeze or stench add safe locations
{
cout<<"\nsafe!!! \n";
if(locx < 9)
{
safe[locx+1][locy] = 1;
searchEngine.AddSafeLocation(locx+1,locy);
}
if(locy < 9)
{
safe[locx][locy+1] = 1;
searchEngine.AddSafeLocation(locx,locy+1);
}
if(locx > 1)
{
safe[locx-1][locy] = 1;
searchEngine.AddSafeLocation(locx-1,locy);
}
if(locy > 1)
{
safe[locx][locy-1] = 1;
searchEngine.AddSafeLocation(locx,locy-1);
}
}
if (actionList.empty()) {
cout<<"empty actions\n";
inPit = 0; //no pit attempt yet
if(hasGold == 1)//if picked up gold
{
cout << "let's go home\n";
if(rightF == 1)//find facing
{
actionList2 = searchEngine.FindPath(Location(locx,locy), RIGHT, Location(1,1), LEFT);
actionList.splice(actionList.end(), actionList2);
actionList.push_back(CLIMB);
}
else if(leftF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), LEFT, Location(1,1), DOWN);
actionList.splice(actionList.end(), actionList2);
actionList.push_back(CLIMB);
}
else if(upF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), UP, Location(1,1), DOWN);
actionList.splice(actionList.end(), actionList2);
actionList.push_back(CLIMB);
}
else if(downF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), DOWN, Location(1,1), LEFT);
actionList.splice(actionList.end(), actionList2);
actionList.push_back(CLIMB);
}
}
else if(hasToShoot == 1 && deadWumpus == 0 && firstTry == 0)//wumpus is alive and needs to die
{
if(visited[wumpusX][wumpusY-1] == 1) //shoot up?
{
if(rightF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), RIGHT, Location(wumpusX,wumpusY-1), UP);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(leftF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), LEFT, Location(wumpusX,wumpusY-1), UP);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(upF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), UP, Location(wumpusX,wumpusY-1), UP);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(downF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), DOWN, Location(wumpusX,wumpusY-1), UP);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
}
else if(visited[wumpusX][wumpusY+1] == 1)//shoot down?
{
if(rightF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), RIGHT, Location(wumpusX,wumpusY+1), DOWN);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(leftF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), LEFT, Location(wumpusX,wumpusY+1), DOWN);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(upF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), UP, Location(wumpusX,wumpusY+1), DOWN);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(downF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), DOWN, Location(wumpusX,wumpusY+1), DOWN);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
}
else if(visited[wumpusX-1][wumpusY] == 1)//shoot Right?
{
if(rightF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), RIGHT, Location(wumpusX-1,wumpusY), RIGHT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(leftF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), LEFT, Location(wumpusX-1,wumpusY), RIGHT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(upF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), UP, Location(wumpusX-1,wumpusY), RIGHT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(downF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), DOWN, Location(wumpusX-1,wumpusY), RIGHT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
}
else if(visited[wumpusX+1][wumpusY] == 1)//shoot Left?
{
if(rightF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), RIGHT, Location(wumpusX+1,wumpusY), LEFT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(leftF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), LEFT, Location(wumpusX+1,wumpusY), LEFT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(upF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), UP, Location(wumpusX+1,wumpusY), LEFT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(downF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), DOWN, Location(wumpusX+1,wumpusY), LEFT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
}
}
else if(goldX != 0 && goldY != 0)//if knows gold location go fetch
{
cout<<"gold already known\n";
if(rightF == 1)//find facing
{
actionList2 = searchEngine.FindPath(Location(1,1), RIGHT, Location(goldX,goldY), RIGHT);
actionList.splice(actionList.end(), actionList2);
}
else if(leftF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), LEFT, Location(goldX,goldY), RIGHT);
actionList.splice(actionList.end(), actionList2);
}
else if(upF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), UP, Location(goldX,goldY), DOWN);
actionList.splice(actionList.end(), actionList2);
}
else if(downF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), DOWN, Location(goldX,goldY), DOWN);
actionList.splice(actionList.end(), actionList2);
}
}
else//find a safe location
{
nextx = 0;
nexty = 0;
if(foundMaxSize == 0)
{
for(int x = 1; x<10 ; x++)
{
for(int y = 1; y<10 ; y++)
{
if(safe[x][y] == 1 && visited[x][y] == 0)
{
nextx = x;
nexty = y;
cout<<"found solution\n";
}
}
}
}
else if(foundMaxSize != 0)
{
for(int x = 1; x<=maxSize; x++)
{
for(int y = 1; y<=maxSize; y++)
{
if(safe[x][y] == 1 && visited[x][y] == 0)
{
nextx = x;
nexty = y;
cout<<"found solution\n";
}
}
}
}
if(nextx != 0 && nexty != 0)//next spot found
{
cout << "nextx = ";
cout << nextx;
cout << "\n";
cout << "nexty = ";
cout << nexty;
cout << "\n";
cout << "x = ";
cout << locx;
cout << "\n";
cout << "y = ";
cout << locy;
cout << "\n";
if(rightF == 1)//find facing
{
actionList2 = searchEngine.FindPath(Location(locx,locy), RIGHT, Location(nextx,nexty), RIGHT);
actionList.splice(actionList.end(), actionList2);
}
else if(leftF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), LEFT, Location(nextx,nexty), RIGHT);
actionList.splice(actionList.end(), actionList2);
}
else if(upF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), UP, Location(nextx,nexty), DOWN);
actionList.splice(actionList.end(), actionList2);
}
else if(downF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), DOWN, Location(nextx,nexty), DOWN);
actionList.splice(actionList.end(), actionList2);
}
}
else//no safe spots
{
if(wumpusX != 0 && wumpusY != 0 && deadWumpus == 0)//if wumpus needs to die
{
hasToShoot = 1;
if(visited[wumpusX][wumpusY-1] == 1) //shoot up?
{
if(rightF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), RIGHT, Location(wumpusX,wumpusY-1), UP);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(leftF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), LEFT, Location(wumpusX,wumpusY-1), UP);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(upF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), UP, Location(wumpusX,wumpusY-1), UP);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(downF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), DOWN, Location(wumpusX,wumpusY-1), UP);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
}
else if(visited[wumpusX][wumpusY+1] == 1)//shoot down?
{
if(rightF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), RIGHT, Location(wumpusX,wumpusY+1), DOWN);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(leftF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), LEFT, Location(wumpusX,wumpusY+1), DOWN);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(upF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), UP, Location(wumpusX,wumpusY+1), DOWN);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(downF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), DOWN, Location(wumpusX,wumpusY+1), DOWN);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
}
else if(visited[wumpusX-1][wumpusY] == 1)//shoot Right?
{
if(rightF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), RIGHT, Location(wumpusX-1,wumpusY), RIGHT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(leftF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), LEFT, Location(wumpusX-1,wumpusY), RIGHT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(upF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), UP, Location(wumpusX-1,wumpusY), RIGHT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(downF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), DOWN, Location(wumpusX-1,wumpusY), RIGHT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
}
else if(visited[wumpusX+1][wumpusY] == 1)//shoot Left?
{
if(rightF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), RIGHT, Location(wumpusX+1,wumpusY), LEFT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(leftF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), LEFT, Location(wumpusX+1,wumpusY), LEFT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(upF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), UP, Location(wumpusX+1,wumpusY), LEFT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(downF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), DOWN, Location(wumpusX+1,wumpusY), LEFT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
}
}
else//go to a possible pit.
{
nextx = 0;
nexty = 0;
if(foundMaxSize == 0)
{
for(int x = 1; x<10 ; x++)
{
for(int y = 1; y<10 ; y++)
{
if(frontier[x][y] == 1)
{
nextx = x;
nexty = y;
cout<<"found risky solution\n";
}
if(stench[x][y] == 1)
{
hailx = x;
haily = y;
}
}
}
}
else if(foundMaxSize != 0)
{
for(int x = 1; x<=maxSize; x++)
{
for(int y = 1; y<=maxSize; y++)
{
if(frontier[x][y] == 1)
{
nextx = x;
nexty = y;
cout<<"found risky solution\n";
}
if(stench[x][y] == 1)
{
hailx = x;
haily = y;
}
}
}
}
if(nextx != 0 && nexty != 0)//next spot found
{
searchEngine.AddSafeLocation(nextx,nexty);
safe[locx][locy] = 1;
inPit = 1;//found pit if died
cout << "nextx = ";
cout << nextx;
cout << "\n";
cout << "nexty = ";
cout << nexty;
cout << "\n";
cout << "x = ";
cout << locx;
cout << "\n";
cout << "y = ";
cout << locy;
cout << "\n";
if(rightF == 1)//find facing
{
actionList2 = searchEngine.FindPath(Location(locx,locy), RIGHT, Location(nextx,nexty), RIGHT);
actionList.splice(actionList.end(), actionList2);
}
else if(leftF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), LEFT, Location(nextx,nexty), RIGHT);
actionList.splice(actionList.end(), actionList2);
}
else if(upF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), UP, Location(nextx,nexty), DOWN);
actionList.splice(actionList.end(), actionList2);
}
else if(downF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), DOWN, Location(nextx,nexty), DOWN);
actionList.splice(actionList.end(), actionList2);
}
}
else if(hailx != 0 && haily != 0 && hasArrow == 1 && wumpusX == 0 && wumpusY == 0)//we can hail marry shoot
{
cout << "\nHail Marry!!!\n";
hailMarry = 1;
//determine direction to shoot
int shootUp = 1;
int shootDown = 1;
int shootLeft = 1;
int shootRight = 1;//default direction
if(foundMaxSize == 0 && hailx+1 > 9)//check boundaries
{
shootRight = 0;
}
else if(hailx + 1 > maxSize)
{
shootRight = 0;
}
if(foundMaxSize == 0 && haily+1 > 9)
{
shootUp = 0;
}
else if(haily + 1 > maxSize)
{
shootUp = 0;
}
if(hailx-1 < 1)
{
shootLeft = 0;
}
if(haily-1 < 1)
{
shootDown = 0;
}
if(noWumpus[hailx+1][haily] == 1)//determine possible shots
{
shootRight = 0;
}
if(noWumpus[hailx-1][haily] == 1)
{
shootLeft = 0;
}
if(noWumpus[hailx][haily+1] == 1)
{
shootUp = 0;
}
if(noWumpus[hailx][haily-1] == 1)
{
shootDown = 0;
}
if(shootRight == 1)
{
if(locx == hailx && locy == haily)
{
if(rightF == 1)
{
action = SHOOT;
return SHOOT;
}
else if(leftF == 1)
{
action = TURNLEFT;
return TURNLEFT;
}
else if(downF == 1)
{
action = TURNRIGHT;
return TURNLEFT;
}
else
{
action = TURNRIGHT;
return TURNRIGHT;
}
}
if(rightF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), RIGHT, Location(hailx,haily), RIGHT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(leftF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), LEFT, Location(hailx,haily), RIGHT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(upF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), UP, Location(hailx,haily), RIGHT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(downF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), DOWN, Location(hailx,haily), RIGHT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
}
else if(shootUp == 1)
{
if(locx == hailx && locy == haily)
{
if(rightF == 1)
{
action = TURNLEFT;
return TURNLEFT;
}
else if(leftF == 1)
{
action = TURNRIGHT;
return TURNRIGHT;
}
else if(downF == 1)
{
action = TURNLEFT;
return TURNLEFT;
}
else
{
action = SHOOT;
return SHOOT;
}
}
if(rightF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), RIGHT, Location(hailx,haily), UP);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(leftF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), LEFT, Location(hailx,haily), UP);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(upF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), UP, Location(hailx,haily), UP);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(downF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), DOWN, Location(hailx,haily), UP);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
}
else if(shootDown == 1)
{
if(locx == hailx && locy == haily)
{
if(rightF == 1)
{
action = TURNRIGHT;
return TURNRIGHT;
}
else if(leftF == 1)
{
action = TURNLEFT;
return TURNLEFT;
}
else if(downF == 1)
{
action = SHOOT;
return SHOOT;
}
else
{
action = TURNRIGHT;
return TURNRIGHT;
}
}
if(rightF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), RIGHT, Location(hailx,haily), DOWN);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(leftF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), LEFT, Location(hailx,haily), DOWN);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(upF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), UP, Location(hailx,haily), DOWN);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(downF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), DOWN, Location(hailx,haily), DOWN);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
}
else//shoot left
{
if(locx == hailx && locy == haily)
{
if(rightF == 1)
{
action = TURNRIGHT;
return TURNRIGHT;
}
else if(leftF == 1)
{
action = SHOOT;
return SHOOT;
}
else if(downF == 1)
{
action = TURNRIGHT;
return TURNRIGHT;
}
else
{
action = TURNLEFT;
return TURNLEFT;
}
}
if(rightF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), RIGHT, Location(hailx,haily), LEFT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(leftF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), LEFT, Location(hailx,haily), LEFT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(upF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), UP, Location(hailx,haily), LEFT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
else if(downF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), DOWN, Location(hailx,haily), LEFT);
actionList.splice(actionList.end(), actionList2);
takeTheShot = 1;
}
}
}
else
{
//last resort if world is not safe at all
cout << "get out of here \n";
if(rightF == 1)//find facing
{
actionList2 = searchEngine.FindPath(Location(locx,locy), RIGHT, Location(1,1), LEFT);
actionList.splice(actionList.end(), actionList2);
actionList.push_back(CLIMB);
}
else if(leftF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), LEFT, Location(1,1), DOWN);
actionList.splice(actionList.end(), actionList2);
actionList.push_back(CLIMB);
}
else if(upF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), UP, Location(1,1), DOWN);
actionList.splice(actionList.end(), actionList2);
actionList.push_back(CLIMB);
}
else if(downF == 1)
{
actionList2 = searchEngine.FindPath(Location(locx,locy), DOWN, Location(1,1), LEFT);
actionList.splice(actionList.end(), actionList2);
actionList.push_back(CLIMB);
}
}
}
}
}
}
action = actionList.front();
actionList.pop_front();
return action;
}
void Agent::GameOver (int score)
{
hailMarry = 0;
cout << "\nend game!!!!!\n";
if(rightF == 1)
{
locx += 1;
}
else if(leftF == 1)
{
locx -= 1;
}
else if(upF == 1)
{
locy += 1;
}
else if(downF == 1)
{
locy -= 1;
}
if(inPit == 1)
{
cout << "\n oops you fell in a pit!!!!\n";
pits[locx][locy] = 1;//confirmed pit
frontier[locx][locy] = 0;//remove from possible pits
safe[locx][locy] = 0;
searchEngine.RemoveSafeLocation(locx, locy);
}
if(wumpusX != 0 && wumpusY != 0)//mark wumpus back to unsafe
{
searchEngine.RemoveSafeLocation(wumpusX, wumpusY);
safe[wumpusX][wumpusY] = 0;
}
}
| true |
c94ff49a3d821c45f7fde921e74f6b365bcd8e0b | C++ | anonymous007-coder/Jumping-Into-CPP-Exercises | /ch16-recursion/Recursive Linked List/main.cpp | UTF-8 | 2,331 | 4.03125 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
struct node
{
string keyVal;
node* next;
};
void traverse(node* restOfList)
{
if (restOfList != NULL)
{
cout << restOfList->keyVal << endl;
traverse(restOfList->next);
}
}
node* addElement(node* restOfList, string input)
{
if (restOfList == NULL)
{
node* newElement = new node;
newElement->keyVal = input;
newElement->next = NULL;
return newElement;
}
restOfList->next = addElement(restOfList->next, input);
return restOfList;
}
node* removeElement(node* restOfList, string input)
{
if (restOfList == NULL)
{
cout << "Sorry, your element wasn't found!" << endl;
return NULL;
}
else if (restOfList->keyVal == input)
{
if (restOfList->next == NULL)
{
delete restOfList;
return NULL;
}
else
{
node* placeholder = restOfList->next;
delete restOfList;
return placeholder;
}
}
else
{
restOfList->next = removeElement(restOfList->next, input);
return restOfList;
}
}
int main()
{
node* headOfList = NULL;
int numInputs;
cout << "Enter the number of strings you want to enter: ";
cin >> numInputs;
for (int i = 0; i < numInputs; i++)
{
string input;
cout << "Enter your string: ";
cin >> input;
while (!cin)
{
cin.clear();
cin.ignore();
cout << "Incompatible input, try again: ";
cin >> input;
}
headOfList = addElement(headOfList, input);
}
cout << endl << "Your list is: " << endl;
traverse(headOfList);
while (headOfList != NULL)
{
cout << "Enter an element to remove: ";
string input;
cin >> input;
while (!cin)
{
cin.clear();
cin.ignore();
cout << "Incompatible input, try again: ";
cin >> input;
}
headOfList = removeElement(headOfList, input);
cout << endl;
traverse(headOfList);
cout << endl;
}
}
| true |
276fb14fed9c71769968ac9c6f7442b227a7f473 | C++ | abhijithneilabraham/TESLA_Robotic-arm | /Sweep.ino | UTF-8 | 976 | 2.78125 | 3 | [] | no_license | #include <Servo.h>
Servo servo1, servo2, servo3, servo4, servo5 servo6;
int pos = 0;
const int pingPin = 7;
const int echoPin = 6;
void setup()
{
Serial.begin(9600);
pinMode(pingPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void ultrasonic()
{
long duration, distance;
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(10);
digitalWrite(pingPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration / 29 / 2;
Serial.print(distance);
}
void setup() {
servo1.attach(3);
servo2.attach(5);
servo3.attach(6);
servo4.attach(9);
servo5.attach(10);
servo6.attach(11);
}
void loop() {
for (pos = 0; pos <= 180; pos += 1) {
servo1.write(pos);
delay(15);
}
for (pos = 180; pos >= 0; pos -= 1) {
myservo.write(pos);
delay(15);
}
}
| true |
d95d5efce8ddb6e0fde9d776282fdaee6e4b7b1e | C++ | OSLL/vpulse | /calculator.h | UTF-8 | 4,352 | 3.21875 | 3 | [] | no_license | #ifndef CALCULATOR_H
#define CALCULATOR_H
#endif // CALCULATOR_H
#include <utility>
#include <conf.h>
#include <videoreader.h>
#include <processor.h>
#include <mat.h>
using harmonic_stat = pair<double,double>; //a data type for holding information about an harmonic oscillation, first is amplitude, second is period
using Point = pair<size_t,size_t>; //a data type for holding pixel coordinates on the image.
namespace Calculator
{
/*!
Function calculates amplitude and period of the oscillation represented by the array of values
\param values values vector
\return harmonic stats of the oscillation
*/
harmonic_stat calc_amplitude_and_period(vector<double> values);
/*!
From the array of periods, function find k with least difference and returns their average
\param periods vector of periods
\param k parameter
\return Average of k periods with least difference
*/
double calc_average_significant_period(vector<double> periods, size_t k);
/*!
Generates array of values of sin function to be oscillation with specified parameters
\param length length of output array
\param ampl amplitude of the oscillation
\param period period of the oscillation
\return vector of values of the oscillation
*/
vector<double> gen_sin_vector(size_t length, double ampl, double period);
/*!
Function generates a set of images so that its pixels are from oscillation with specified parameters
\param length length of vector of images
\param width width of images
\param height height of images
\param ampl amplitude of oscillation
\param period period of oscillation
\return a vector of unique pointers to the Mat images
*/
vector<unique_ptr<Mat>> gen_test_image(size_t length, size_t width, size_t height, double ampl, double period);
/*!
Function obtains an array of pixel values from the images vector
\param src a vector of unique pointers to the Mat images
\param row row
\param col column
\param channel channel
\return vector of specified pixel values
*/
vector<double> receive_pixel_values(vector<unique_ptr<Mat>>& src, size_t row, size_t col, size_t channel);
/*!
Function obtains an array of pixel values from the images vector in specified range [start;end)
\param src a vector of unique pointers to the Mat images
\param row row
\param col column
\param channel channel
\param start Starting position
\param end Ending position
\return vector of values in specified range [start;end)
*/
vector<double> receive_pixel_values(vector<unique_ptr<Mat>>& src, size_t row, size_t col, size_t channel, size_t start, size_t end);
/*!
Function obtains an array of averaged pixel values from the images vector in specified range [start;end)
\param src a vector of unique pointers to the Mat images
\param row row
\param col column
\param area_size radius of circle which area will be used to average pixel value
\param channel channel
\param start Starting position
\param end Ending position
\return vector of averaged pixel values in specified range [start; end)
*/
vector<double> receive_averaged_pixel_values(vector<unique_ptr<Mat>>& src, size_t row, size_t col, double area_size, size_t start, size_t end);
/*!
Function calculates pulse from video according to points, specified by the parameter
\param fr1 lower frequency threshold
\param fr2 upper frequency threshold
\param ampFactor amplifying factor
\param avg_parameter
\param area_radius radius of circle used to average pixel values. 1 for no averaging
\return A vector of real numbers, one for each period of time with length equal to upd_freq parameter
*/
vector<double> calculate_pulse(VideoReader& video, vector<Point>& points, double upd_freq, double fr1, double fr2, double ampFactor, size_t avg_parameter, double area_radius);
/*!
Function generates standart points for image with specified width and height.
\param width width
\param height height
\return a vector of Points
*/
vector<Point> standart_points(size_t width, size_t height);
/*!
Function finds points of interest in the video for potential pulse recognition
\param video VideoReader video
\return a vector of Points
*/
vector<Point> find_points_of_interest(VideoReader& video);
}
| true |
ffb39f16b379686db84f51d7702fdc4321671612 | C++ | gbrlas/AVSP | /CodeJamCrawler/dataset/09_24594_76.cpp | UTF-8 | 1,690 | 3.375 | 3 | [] | no_license | // string constructor
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
bool MatchPattern (std::string word, std::string pattern)
{
int wptr = 0;
bool flag = false;
for (unsigned int pptr = 0; pptr < pattern.length(); pptr ++)
{
if (pattern.at(pptr) == '(')
{
flag = true;
continue;
}
else if (pattern.at(pptr) == ')')
{
flag = false;
continue;
}
else if (pattern.at(pptr) == word.at (wptr))
{
wptr += 1;
if (wptr == word.length())
return true;
if (flag != false)
{
while (pattern.at(pptr) != ')')
pptr ++;
flag = false;
}
}
else if (flag == false)
return false;
}
return false;
}
int main (int argc, char *argv[])
{
int len = 0;
int wordsCnt = 0;
int patternCnt = 0;
fstream infile("A-large.in", ios::in);
fstream outfile("Ouput.txt", ios::out);
infile >> len >> wordsCnt >> patternCnt;
std::string line;
vector<std::string> words;
vector<std::string> patterns;
int *results = (int *)calloc (wordsCnt, sizeof(int));
getline (infile, line);
for (int i = 0; i < wordsCnt; i++)
{
getline (infile, line);
words.push_back(line);
}
for (int i = 0; i < patternCnt; i++)
{
getline (infile, line);
patterns.push_back(line);
}
for (int i = 0; i < wordsCnt; i ++)
{
for (int j = 0; j < patternCnt; j++)
{
if (MatchPattern (words.at(i), patterns.at(j)))
results[j] ++;
}
}
for (int j = 0; j < patternCnt; j++)
{
outfile << "Case #" << j+1 << ": "<< results[j] << endl;
}
outfile.close();
infile.close();
return 0;
} | true |
958b259ccf50bd256c8e0c72c875aab4f3376340 | C++ | sunsidi/Leetcode | /27.cpp | UTF-8 | 481 | 3.96875 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int removeElement(vector<int> &nums, int value) {
int pos = 0;
for(int num:nums) {
if(num !=value){
nums[pos] = num;
pos++;
}
}
return pos;
}
int main() {
vector<int> nums = {1,2,3,4,5,6,1,2,3,4,5,6,7,1,2,3,4,5};
int value = 4;
int pos = removeElement(nums, value);
cout << "The length of the array is " << pos << endl;
for(int i = 0; i < nums.size(); i++){
cout << i << " : "<< nums[i] << endl;
}
} | true |
894cdb2be85d300d4c9932beb00a6121c31e79f7 | C++ | CPKai/leetcode | /leetcode_17.cpp | UTF-8 | 1,600 | 3.734375 | 4 | [] | no_license | #include <vector>
#include <string>
using namespace std;
class Solution17 {
public:
vector<string> letterCombinations(string digits) {
vector<vector<char>> d(10);
d[0] = {' '};
d[1] = {};
d[2] = {'a','b','c'};
d[3] = {'d','e','f'};
d[4] = {'g','h','i'};
d[5] = {'j','k','l'};
d[6] = {'m','n','o'};
d[7] = {'p','q','r','s'};
d[8] = {'t','u','v'};
d[9] = {'w','x','y','z'};
vector<string> res = {""};
if (digits.empty())
{
return {};
}
// BFS algorithm,廣度優先,一層一層彺下
for (char digit : digits)
{
// 建立一個空vector<string>,準備裝「當前層」的運算結果
vector<string> temp;
// 第一圈res會有一個空字串成為s,此處res代表「前一層的字串」 ps:每一層為一個vector<string>
for (string s : res)
{
// '2' = 51 當減去'0'可成功match到d[2]的區段,或可找其他手段讓digit直接轉int
for (char c : d[digit - '0'])
{
// 當前層新增字串,自字串內容為s+c
temp.push_back(s+c);
}
}
// 當前層運算完後,與res交換
res.swap(temp);
}
// ""
// "a", "b", "c"
// "ad","ae","af","bd","be","bf","cd","ce","cf"
return res;
}
}; | true |
6cf92f2b00aa549fef55d0ebdb936bfab4818cc6 | C++ | riplaboratory/Kanaloa | /SurfaceVehicles/WAMV/Arduino/KillMega/a20190915_wamvKillArduino/io.ino | UTF-8 | 3,747 | 2.796875 | 3 | [] | no_license | void readRemoteKill() {
/*
Checks the receiver channel 4 and sets remoteKillStatus based on it.
*/
// Create local, non-volatile copy of pulse widths (QuickMedian does not like volatile arrays)
int ch4PulseFilt[nMedian] = {};
memcpy(ch4PulseFilt, ch4PulseArray, nMedian * 2);
// Take median of pulse width arrays
ch4PulseMedian = QuickMedian<int>::GetMedian(ch4PulseFilt, nMedian);
// // Print debug statements
// Serial.print("Ch4 (");
// Serial.print(ch4PulseMedian);
// Serial.println(");");
// Determine mode from handheld receiver channel 4
int switchUp = ch4PulseMax;
int switchMid = round((ch4PulseMax + ch4PulseMin) / 2);
int switchDown = ch4PulseMin;
if (ch4PulseMedian + pulseTolerance > switchUp && ch4PulseMedian - pulseTolerance < switchUp) {
// Channel 4 switch is in the up position (unkill)
remoteKillStatus = 0;
}
else if (ch4PulseMedian + pulseTolerance > switchDown && ch4PulseMedian - pulseTolerance < switchDown) {
// Channel 4 switch is in the down position (kill)
remoteKillStatus = 1;
}
else {
// Invalid input from channel 4
Serial.println("Remote kill switch (channel 4) reporting invalid input. Check transmitter connection...");
remoteKillStatus = 1;
}
}
void readPhysicalKill() {
/*
Checks the physical kill pins and sets physicalKillStatus based on it.
*/
// Read state of physical kill switches
if (digitalRead(physicalKillPin) == HIGH) {
// Physical kill switch is unpressed (unkill)
physicalKillStatus = 0;
}
else {
// Physical kill switch is pressed (kill)
physicalKillStatus = 1;
}
}
void checkInterruptTimeout() {
/*
Checks the interrupt timer, if it has not published for more than timeout, then kill system.
*/
// Function varaibles
float timeOut = 0.25; // how long system should tolerate no updates from receiver before killing [s]
float timeOutMicros = timeOut * 1E6;
// Take current time
float timeNow = micros();
// Take time since last update on each channel
float timeSinceCh4 = timeNow - ch4Timer; // time since last ch1 rise [us]
if (timeSinceCh4 > timeOutMicros) {
// Set remote kill to true
remoteKillStatus = 1;
// Print debug statement
Serial.print("Time since last receiver update has exceeded ");
Serial.print(timeOut);
Serial.println(" s; check receiver connection! Killing...");
}
}
void setKillStatus() {
/*
Sets kill status, kills or unkills thrusters, and sends status to main arduino.
*/
if (remoteKillStatus == 0 && physicalKillStatus == 0) {
// Set kill status to 0
killStatus = 0;
// Unkill thrusters
digitalWrite(q1KillPin, LOW); // pull LOW to unkill
digitalWrite(q2KillPin, LOW); // pull LOW to unkill
digitalWrite(q3KillPin, LOW); // pull LOW to unkill
digitalWrite(q4KillPin, LOW); // pull LOW to unkill
// Send unkill signal to main arduino
digitalWrite(killCommPin, LOW); // pull LOW to communicate unkill (as receiving pin on main arduino is set to INPUT_PULLUP)
// // Print debug statement
// Serial.println("System is UNKILLED");
}
else {
// Set kill status to 1
killStatus = 1;
// Kill thrusters
digitalWrite(q1KillPin, HIGH); // set HIGH to kill
digitalWrite(q2KillPin, HIGH); // set HIGH to kill
digitalWrite(q3KillPin, HIGH); // set HIGH to kill
digitalWrite(q4KillPin, HIGH); // set HIGH to kill
// Send unkill signal to main arduino
digitalWrite(killCommPin, HIGH); // set HIGH to communicate kill (as receiving pin on main arduino is set to INPUT_PULLUP)
// // Print debug statement
// Serial.println("System is KILLED");
}
}
| true |
fd1dc5aac2a55c86a0cdc72b54f90c03e96f16a1 | C++ | samuelbrown3199/AI-Assignment | /Code/AssignmentAI/AStar.cpp | UTF-8 | 4,735 | 3.703125 | 4 | [] | no_license | #include "AStar.h"
AStar::AStar(Maze* _maze)
{
currentMaze = _maze; //keeps a pointer of the current maze
nodeAmount = currentMaze->tileData.size(); //works out the amount of nodes in the maze
SetupNodeList(); //sets up the node data
Algorithm(); //starts the algorithm
}
AStar::~AStar()
{
}
void AStar::SetupNodeList()
{
for (int i = 0; i < nodeAmount; i++) //loops through the amount of nodes
{
Node* temp = new Node(currentMaze->tileData[i].x, currentMaze->tileData[i].y, currentMaze->tileData[i].type, i, this); //pushes a node with the relevant data into the list
nodeList.push_back(temp);
if (temp->type == 2)
{
startNode = temp; //keeps a pointer of the start node
}
else if (temp->type == 3)
{
endNode = temp; //keeps a pointer of the end node
}
}
}
Node* AStar::FindNode(int _x, int _y) //finds a node with an x and y value
{
for (int i = 0; i < nodeAmount; i++) //loops through the node list
{
if (nodeList[i]->x == _x && nodeList[i]->y == _y) //if the values are correct we have found the node
{
return nodeList[i];
}
}
return nullptr; //if we get through the full list the node doesnt exist
}
void AStar::Algorithm() //the a* algorithm
{
auto t1 = std::chrono::high_resolution_clock::now();
std::vector<Node*> openList; //creates the open list
std::vector<Node*> closedList; //creates the closed list
for (int i = 0; i < nodeAmount; i++) //pushes back some nullptrs into the closed and open lists
{
openList.push_back(nullptr);
closedList.push_back(nullptr);
}
Node* currentNode; //used to store the current node
openList[startNode->posInList] = startNode; //puts the start node into the openlist
while (!pathFound) //while the path is found continue
{
currentNode = nullptr; //sets the current node to nullptr
for (int i = 0; i < nodeAmount; i++) //loop through the node lists
{
if (openList[i] != nullptr) //if the current open list element is nullptr
{
if (currentNode == nullptr) //if the current node is null just set the value to the first non-null openlist element
{
currentNode = openList[i];
}
else if (currentNode->f < openList[i]->f) //if the f cost is lower than the current node, this is better and we will explore this first
{
currentNode = openList[i];
}
}
}
openList[currentNode->posInList] = nullptr; //remove the current node from the list
closedList[currentNode->posInList] = currentNode; //add the current node to the closed list
if (currentNode->type == 3) //if the currentnode is the endnode the path is found and the loop is broken
{
std::cout << "Found the end of the path, breaking loop." << std::endl;
pathFound = true;
auto t2 = std::chrono::high_resolution_clock::now();
std::cout << "Finding the path took: " << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() << " milliseconds." << std::endl;
break;
}
else //path is not found, we will explore the neighbours
{
currentNode->SetupNeighbours(); //sets up the node neighbours
for (int i = 0; i < 8; i++) //loop through the neighbours
{
if (currentNode->neighbours[i] != nullptr) //if the neighbour isnt null continue
{
if (openList[currentNode->neighbours[i]->posInList] != nullptr) //ifs its in the open list ignore it
{
continue;
}
else
{
if (closedList[currentNode->neighbours[i]->posInList] != nullptr) //if its in the closed list we ignore it
{
continue;
}
else
{
if (currentNode->neighbours[i]->type != 1) //if the node is a wall/obstacle we ignore it
{
if (currentNode->neighbours[i]->parent == nullptr)
{
currentNode->neighbours[i]->ChangeParent(currentNode); //we set the nodes parent to the current node
currentNode->neighbours[i]->CalculateCost(); //we calculate the cost of the node
openList[currentNode->neighbours[i]->posInList] = currentNode->neighbours[i]; //we put the neighbour into the openList
}
}
}
}
}
}
}
}
}
void AStar::RenderPath(SDL_Renderer* _renderer) //used to render the finished path to the screen
{
Node* currentNode; //used to store current node
currentNode = endNode; //start at the end node
SDL_SetRenderDrawColor(_renderer, 0, 100, 100, 255); //render the start node
SDL_RenderFillRect(_renderer, &startNode->nodeRect);
while (currentNode->parent != nullptr) //while the current nodes parent does exist we render this node
{
SDL_SetRenderDrawColor(_renderer, 0, 100, 100, 255);
SDL_RenderFillRect(_renderer, ¤tNode->nodeRect);
currentNode = currentNode->parent; //make the current node equal to the parent of the currentnode
}
} | true |
38e400c99459c2fe7b01e948943e482ffabbc783 | C++ | shanPic/CodeOfAcm | /2017训练比赛/9.16西安网络赛/e.cpp | UTF-8 | 830 | 2.53125 | 3 | [] | no_license | /*
* @FileName: D:\代码与算法\2017训练比赛\9.16西安网络赛\e.cpp
* @Author: Pic
* @Created Time: 2017/9/16 13:37:07
*/
#include <iostream>
#include <cstdio>
using namespace std;
typedef long long ll;
const ll mod=999999999;
ll sum(ll x)
{
ll res=0;
while(x){
res+=(x%10);
x=x/10;
}
return res;
}
ll cal(ll i)
{
ll res=0;
res+=sum(i*9-1);
res+=sum(mod-i+1);
return res+16*9;
}
int main()
{
//freopen("data.in","r",stdin);
//freopen("data.out","w",stdout);
int t;
scanf("%d",&t);
while(t--){
ll n;
scanf("%I64d",&n);
ll ans=0;
for(ll i=1;i<=99999;i++){
if((cal(i*n))%233==0){
// cout<<11111<<endl;
ans=i;
break;
}
}
// cout<<ans<<endl;
printf("%I64d",ans*(ll)9-(ll)1);
for(int i=0;i<16;i++) printf("9");
printf("%I64d",mod-ans+1);
printf("\n");
}
return 0;
}
| true |
ee2f3a794644cec1803e7810d2d1b6e6edb8a258 | C++ | xshaheen/cpp-data-structure | /BinaryTree/TreeType.h | UTF-8 | 9,210 | 3.75 | 4 | [] | no_license | // Created by Mahmoud Shaheen on 5/8/2019.
// Implementation of binary tree.
// TODO: test code well
#ifndef TREETYPE_H
#define TREETYPE_H
#include <iostream>
#include "QueueType.h"
template <class ItemType>
struct TreeNode{
ItemType info;
TreeNode<ItemType> *left;
TreeNode<ItemType> *right;
};
enum OrderType {PRE_ORDER, IN_ORDER, POST_ORDER};
template <class ItemType>
class TreeType
{
public:
TreeType();
~TreeType();
TreeType(const TreeType<ItemType>& originalTree); // copy constructor
void MakeEmpty(); // Returns the list to the empty state.
bool IsEmpty() const;
bool IsFull() const;
int NumberOfNodes() const; // Determines the number of elements in tree.
void RetrieveItem(ItemType&, bool& found);
void InsertItem(ItemType newItem);
void DeleteItem(ItemType item); // delete item whose key matches item's key
void ResetTree(OrderType order);
// for an iteration through the tree and the user is allowed to specify the tree traversal order
void GetNextItem(ItemType& item, OrderType order, bool& finished); // Gets the next element in list.
void PrintTree(OrderType order) const;
private:
TreeNode<ItemType> *root;
// needs for ResetTree function
QueueType<ItemType> preQue;
QueueType<ItemType> inQue;
QueueType<ItemType> postQue;
};
template <class ItemType>
TreeType<ItemType>::TreeType()
{
root = NULL;
}
template <class ItemType>
TreeType<ItemType>::TreeType(const TreeType<ItemType>& originalTree)
// function: make the new list a copy from tree.
{
CopyTree(root, originalTree);
}
template <class ItemType>
void CopyTree(TreeNode<ItemType> *copy, TreeNode<ItemType> *originalTree)
{
if(originalTree == NULL) // base case
copy = NULL;
else {
copy = new TreeNode<ItemType>;
// pre-order
copy->info = originalTree->info;
CopyTree(copy->left, originalTree->left);
CopyTree(copy->right, originalTree->right);
}
}
template <class ItemType>
TreeType<ItemType>::~TreeType()
// Post: tree is Empty and All element has been de-allocated.
{
Destroy(root);
}
template <class ItemType>
void TreeType<ItemType>::MakeEmpty()
// Post: list is Empty and All element has been de-allocated.
{
Destroy(root);
}
template <class ItemType>
void Destroy(TreeNode<ItemType>*& tree)
{ // Delete the tree in a "bottom-up" fashion postOrder traversal is appropriate for that.
if(tree != NULL) {
Destroy(tree->left);
Destroy(tree->right);
delete tree;
}
}
template <class ItemType>
bool TreeType<ItemType>::IsEmpty() const
{
return (root == NULL);
}
template <class ItemType>
bool TreeType<ItemType>::IsFull() const
// return true if there is no room for another ItemType
// on the free store, false otherwise.
{
TreeNode<ItemType> *tempNode;
try {
tempNode = new TreeNode<ItemType>;
delete tempNode;
return false;
}
catch (std::bad_alloc exception) {
return true;
}
}
template <class ItemType>
int TreeType<ItemType>::NumberOfNodes() const
{
return (CountNodes(root));
}
template <class ItemType>
int CountNodes(TreeNode<ItemType> *tree)
{
if (tree == NULL)
return 0;
else
return CountNodes(tree->left) + CountNodes(tree->right) + 1;
}
template <class ItemType>
void TreeType<ItemType>::InsertItem(ItemType newItem)
// Pre: list is not full
// item is not in tree
// Pre: newItem is not exist in the tree.
{
insert(root, newItem);
}
template <class ItemType>
void insert(TreeNode<ItemType>* &tree, ItemType newItem)
// insert item to tree using recursion
{
if (tree == NULL){ // base case
tree = new TreeNode<ItemType>;
tree->info = newItem;
tree->left = NULL;
tree->right = NULL;
}
else if (tree->info > newItem) // insert at left subtree.
insert(tree->left, newItem);
else
insert(tree->right, newItem); // insert at right subtree.
}
template <class ItemType>
void TreeType<ItemType>::DeleteItem(ItemType item)
// Pre: tree is not empty
// item's key has been initialized.
// An element in the list has a key that matches item's.
// Post: No element in the list has a key that matches item's.
{
Delete(root, item);
}
template <class ItemType>
void Delete(TreeNode<ItemType>* &tree, ItemType item)
// function: determine the node of the node to be deleted and delete it using deleteNode function
{
if (item < tree->info) // if the item less than node delete in left subtree.
Delete(tree->left, item);
else if (item > tree->info) // if the item greater than node delete in right subtree.
Delete(tree->right, item);
else // base case: node founded
deleteNode(tree);
}
template <class ItemType>
void deleteNode(TreeNode<ItemType>* &tree)
{
ItemType data;
TreeNode<ItemType>* tempPtr = tree;
// Case1: Deleting a node with only one child or Deleting leaf
if(tree->left == NULL) { // 1.1. have right child or not
tree = tree->right;
delete tempPtr;
}
else if(tree->right == NULL) { // 1.2. have left child or not
tree = tree->left;
delete tempPtr;
}
// Case2: Deleting a node with two children
else { // replace the greatest element in left subtree (Predecessor) with it and delete predecessor node
// find the predecessor (it is the rightmost node in the left subtree)
GetPredecessor(tree->left, data);
// Replace the data of the node to be deleted with predecessor's data
tree->info = data;
Delete(tree->left, data); // delete the node with the same way
}
}
template<class ItemType>
void GetPredecessor(TreeNode<ItemType>* tree, ItemType& data)
{
while(tree->right != NULL)
tree = tree->right;
data = tree->info;
}
template <class ItemType>
void TreeType<ItemType>::RetrieveItem(ItemType& item, bool& found)
{
retrieve(root, item, found);
}
template <class ItemType>
void retrieve(TreeNode<ItemType> *tree, ItemType& item, bool& found)
// Post: If found, item's key matches an element's key in the
// tree and a copy of that element has been stored in item;
// otherwise, item is unchanged.
{
if (tree == NULL) // base case 1
found = false;
else if (tree->info > item)
retrieve(tree->left, item, found); // search in the left subtree
else if (tree->info < item)
retrieve(tree->right, item, found); // search in the right subtree
else { // base case 2
found = true;
item = tree->info;
}
}
template <class ItemType>
void TreeType<ItemType>::PrintTree(OrderType order) const
{
switch (order) {
case IN_ORDER:
PrintInOrder(root);
break;
case PRE_ORDER:
PrintPreOrder(root);
break;
case POST_ORDER:
PrintPostOrder(root);
break;
default:
std::cout << "You Entered incorrect value.";
}
}
template <class ItemType>
void PrintInOrder(TreeNode<ItemType> *tree)
{
if (tree != NULL){
PrintInOrder(tree->left);
std::cout << tree->info << "\t";
PrintInOrder(tree->right);
}
}
template <class ItemType>
void PrintPostOrder(TreeNode<ItemType> *tree)
{
if (tree != NULL){
PrintPostOrder(tree->left);
PrintPostOrder(tree->right);
std::cout << tree->info << "\t";
}
}
template <class ItemType>
void PrintPreOrder(TreeNode<ItemType> *tree)
{
if (tree != NULL){
std::cout << tree->info << "\t";
PrintPreOrder(tree->left);
PrintPreOrder(tree->right);
}
}
template <class ItemType>
void TreeType<ItemType>::ResetTree(OrderType order)
// For efficiency, ResetTree stores in a queue the results of the specified tree traversal
// Then, GetNextItem, dequeues the node values from the queue
{
switch(order) {
case PRE_ORDER: PreOrder(root, preQue);
break;
case IN_ORDER: InOrder(root, inQue);
break;
case POST_ORDER: PostOrder(root, postQue);
break;
default:
std::cout << "You entered incorrect value!";
}
}
template <class ItemType>
void InOrder(TreeNode<ItemType> *tree, QueueType<ItemType> &inQue)
{
if(tree != NULL) {
InOrder(tree->left, inQue);
inQue.Enqueue(tree->info);
InOrder(tree->right, inQue);
}
}
template<class ItemType>
void PostOrder(TreeNode<ItemType> *tree, QueueType<ItemType> &postQue)
{
if(tree != NULL) {
PostOrder(tree->left, postQue);
PostOrder(tree->right, postQue);
postQue.Enqueue(tree->info);
}
}
template<class ItemType>
void PreOrder(TreeNode<ItemType> *tree, QueueType<ItemType> &preQue)
{
if (tree != NULL) {
preQue.Enqueue(tree->info);
PreOrder(tree->left, preQue);
PreOrder(tree->right, preQue);
}
}
template <class ItemType>
void TreeType<ItemType>::GetNextItem(ItemType &item, OrderType order, bool& finished)
// Pre: ResetList was called with the same order.
// Queue has been initialized and not empty
// Post: A copy of the next item in the list is returned.
// When the end of the list is reached, finished be true.
{
finished = false;
switch (order) {
case PRE_ORDER:
preQue.Dequeue(item);
if (preQue.IsEmpty())
finished = true;
break;
case IN_ORDER:
inQue.Dequeue(item);
if (inQue.IsEmpty())
finished = true;
break;
case POST_ORDER:
postQue.Dequeue(item);
if (postQue.IsEmpty())
finished = true;
break;
}
}
#endif //TREETYPE_H
| true |
6f29df15ead7f5bb279b3d9e72971dd3c1c2fc5c | C++ | joonas-yoon/PS | /BOJ/16431.cpp | UTF-8 | 1,194 | 2.5625 | 3 | [] | no_license | #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <string>
#include <algorithm>
using namespace std;
typedef int lld;
typedef pair<int, int> ii;
int jy, jx;
char visit[1001][1001];
static int ddy[] = {-1,0,0,1,-1,-1,1,1};
static int ddx[] = {0,-1,1,0,-1,1,-1,1};
int dist(int y, int x, int around) {
memset(visit, 0, sizeof(visit));
queue<ii> q;
q.push(make_pair(y, x));
visit[y][x] = true;
int ans = 0;
while (!q.empty()) {
int qs = q.size();
while (qs--) {
int cy = q.front().first;
int cx = q.front().second;
q.pop();
if (cy == jy && cx == jx) return ans;
for (int i = 0; i < around; ++i) {
int ny = cy + ddy[i];
int nx = cx + ddx[i];
if (ny < 0 || ny >= 1000 || nx < 0 || nx >= 1000) continue;
if (visit[ny][nx]) continue;
q.push(make_pair(ny, nx));
visit[ny][nx] = true;
}
}
ans++;
}
return -1;
}
int main() {
int by, bx, dy, dx;
scanf("%d %d %d %d %d %d", &by, &bx, &dy, &dx, &jy, &jx);
int b = dist(by, bx, 8);
int d = dist(dy, dx, 4);
if (b == d) puts("tie");
else puts(b < d ? "bessie" : "daisy");
return 0;
} | true |
8ff897b92b911ddb0ab48806df2448c386e226b4 | C++ | heykenwu/Geographic-Information-System | /NameIndex.cpp | UTF-8 | 3,620 | 2.796875 | 3 | [] | no_license | #include "NameIndex.h"
unsigned int NameIndex::elfhash(string key){
unsigned int h = 0;
unsigned int s;
for (int i =0; i < key.length(); i++) {
h = (h << 4) + key[i];
s = h & 0xf0000000L;
if(s) {
h ^= s >> 24;
}
h &= ~s;
}
return h;
}
void NameIndex::expandAndRehash(){
c*=2;
size = 0;
avg_name_len = 0;
vector<pair<string,vector<int>>> tmp_buckets(c);
vector<BucketStatus> tmp_status(c);
for (int g = 0; g < buckets.size(); g++)
{
tmp_buckets[g] = buckets[g];
tmp_status[g] = status[g];
}
pair<string,vector<int>> re_;
buckets.assign(c,re_);
status.assign(c,EMPTY);
for (int i = 0; i < tmp_buckets.size(); i++)
{
if (tmp_status[i] == OCCUPIED)
for(int k = 0; k < tmp_buckets[i].second.size(); k ++) {
insert(tmp_buckets[i].first,tmp_buckets[i].second[k]);
}
}
}
bool NameIndex::insert(string name_state, int offset)
{
if (static_cast<double>(size) / c >= 0.7)
{
expandAndRehash();
}
int numCollisions = 0;
unsigned int h = elfhash(name_state) % c;
unsigned int i = 0;
unsigned int hi = h;
unsigned int probe;
while (status[hi] == OCCUPIED)
{
if (buckets[hi].first == name_state){
if(!(std::find(buckets[hi].second.begin(), buckets[hi].second.end(), offset) != buckets[hi].second.end())) {
buckets[hi].second.push_back(offset);
}
return true;
}
++i;
probe = (i*i + i) / 2;
numCollisions++;
hi = (hi + probe) % c;
}
avg_name_len+=name_state.length()-2;
status[hi] = OCCUPIED;
buckets[hi].first = name_state;
buckets[hi].second.push_back(offset);
size++;
if(numCollisions > max_numCollisions) {
max_numCollisions = numCollisions;
}
return true; // Key inserted successfully
}
pair<string,vector<int>> NameIndex::search(string name_state)
{
unsigned int h = elfhash(name_state) % c;
unsigned int i = 0;
unsigned int hi = h;
unsigned int probe;
while (status[hi] == OCCUPIED)
{
if (buckets[hi].first == name_state)
{
return buckets[hi];
}
++i;
probe = (i*i + i) / 2;
hi = (hi + probe) % c;
}
pair<string,vector<int>> not_found;
not_found.first = "null";
// Key not found. Hit an empty bucket.
return not_found;
}
string NameIndex::str(){
string result = "";
result += "Format of display is\n";
result +="Slot number: data record\n";
result +="Current table size is " + to_string(c) +"\n";
result +="Number of elements in table is " + to_string(size) + "\n\n";
for(int i = 0; i < buckets.size(); i++){
if(status[i] == OCCUPIED) {
result+= " "+to_string(i);
result+=": [";
result+=buckets[i].first.substr(0,buckets[i].first.length() - 2) +":";
result+=buckets[i].first.substr(buckets[i].first.length() - 2,2) + ", [";
result+= to_string(buckets[i].second[0]);
for(int j = 1; j<buckets[i].second.size();j++) {
result+= ","+to_string(buckets[i].second[j]);
}
result+= "]]\n";
}
}
return result;
}
int NameIndex::name_length(){
return (avg_name_len/size);
}
int NameIndex::longest_probe() {
return max_numCollisions;
}
int NameIndex::size_by_name() {
return size;
} | true |
292082a700ae894964021076040508a5434dfb16 | C++ | eecs280staff/unit_test_framework | /unit_test_framework.hpp | UTF-8 | 22,044 | 2.6875 | 3 | [
"MIT"
] | permissive | #ifndef UNIT_TEST_FRAMEWORK_HPP
#define UNIT_TEST_FRAMEWORK_HPP
#include <map>
#include <utility>
#include <string>
#include <iostream>
#include <sstream>
#include <cmath>
#include <memory>
#include <vector>
#include <typeinfo>
#include <type_traits>
#include <cstdlib>
#include <iterator>
#include <algorithm>
#include <exception>
#include <stdexcept>
#if UNIT_TEST_ENABLE_REGEXP
# include <regex>
#endif
// For compatibility with Visual Studio
#include <ciso646>
// Place the following line of code in your test file to generate a
// main() function:
// TEST_MAIN()
using Test_func_t = void (*)();
#define TEST(name) \
static void name(); \
static TestRegisterer register_##name((#name), name); \
static void name()
#define TEST_MAIN() \
int main(int argc, char** argv) { \
return TestSuite::get().run_tests(argc, argv); \
} \
TEST_SUITE_INSTANCE();
struct TestCase {
TestCase(const std::string& name_, Test_func_t test_func_)
: name(name_), test_func(test_func_) {}
void run(bool quiet_mode);
void print(bool quiet_mode);
std::string name;
Test_func_t test_func;
std::string failure_msg{};
std::string exception_msg{};
};
class TestSuite {
public:
static TestSuite& get() {
if (not instance) {
instance = new TestSuite;
}
return *instance;
}
void add_test(const std::string& test_name, Test_func_t test) {
tests_.insert({test_name, TestCase{test_name, test}});
}
int run_tests(int argc, char** argv);
void print_results();
void enable_quiet_mode() {
quiet_mode = true;
}
std::ostream& print_test_names(std::ostream& os) {
for (const auto& test_pair : tests_) {
os << test_pair.first << '\n';
}
return os;
}
friend class TestSuiteDestroyer;
private:
TestSuite() {
auto func = []() {
if (TestSuite::incomplete) {
std::cout << "ERROR: premature call to exit()" << std::endl;
std::abort();
}
};
std::atexit(func);
#ifdef _GLIBCXX_HAVE_AT_QUICK_EXIT
std::at_quick_exit(func);
#endif
}
TestSuite(const TestSuite&) = delete;
bool operator=(const TestSuite&) = delete;
~TestSuite() {}
std::vector<std::string> get_test_names_to_run(int argc, char** argv);
static TestSuite* instance;
std::map<std::string, TestCase> tests_;
bool quiet_mode = false;
static bool incomplete;
};
class TestSuiteDestroyer {
public:
~TestSuiteDestroyer() {
delete TestSuite::instance;
}
};
class TestRegisterer {
public:
TestRegisterer(const std::string& test_name, Test_func_t test) {
TestSuite::get().add_test(test_name, test);
}
};
class TestFailure {
public:
TestFailure(std::string reason, int line_number, const char* assertion_text)
: reason_m(std::move(reason)), line_number_m(line_number),
assertion_text_m(assertion_text) {}
std::ostream& print(std::ostream& os) const {
os << "In " << assertion_text_m << ", line " << line_number_m << ":\n"
<< reason_m << '\n';
return os;
}
std::string to_string() const {
std::ostringstream oss;
print(oss);
return oss.str();
}
private:
std::string reason_m;
int line_number_m;
const char* assertion_text_m;
};
std::ostream& operator<<(std::ostream& os, const TestFailure& test_failure);
// ----------------------------------------------------------------------------
// demangle, print_helper, and print contributed by Amir Kamil <akamil@umich.edu>
// Demangles a string produced by std::type_info::name.
std::string demangle(const char* typeinfo_name);
// forward declaration of print
template <class T>
std::ostream& print(std::ostream& os, const T& t);
// This version of print_helper will be called when T has an available
// stream insertion operator overload.
template <class T>
auto print_helper(std::ostream& os, const T& t, int, int)
-> decltype(os << t)& {
return os << t;
}
// This version of print_helper will be called when T is a pair.
template <class First, class Second>
auto print_helper(std::ostream& os, const std::pair<First, Second>& t, int,
int) -> decltype(print(os, t.first), print(os, t.second))& {
os << '(';
print(os, t.first);
os << ',';
print(os, t.second);
return os << ')';
}
// Helper function to print a sequence.
template <class Sequence>
auto print_sequence_helper(std::ostream &os, const Sequence& seq)
-> decltype(print(os, (*std::begin(seq), *std::end(seq))))& {
if (std::begin(seq) == std::end(seq)) {
return os << "{}";
}
auto it = std::begin(seq);
os << "{ ";
print(os, *it);
for (++it; it != std::end(seq); ++it) {
os << ", ";
print(os, *it);
}
return os << " }";
}
// This version of print_helper will be called when T is a sequence.
template <class Sequence>
auto print_helper(std::ostream& os, const Sequence& seq, int, ...)
-> decltype(print(os, *seq.begin()), print(os, *seq.end()))& {
return print_sequence_helper(os, seq);
}
// This version of print_helper will be called when T is a non-char array.
// This is separate from the sequence overload so that printing an
// array as a sequence is preferred over printing it as a pointer
// (using the first overload).
template <class Elem, std::size_t N>
std::ostream& print_helper(std::ostream& os, const Elem (&arr)[N], int, int) {
return print_sequence_helper(os, arr);
}
// This version of print_helper will be called when T is a char array.
// If the array contains a null terminator, it is printed as a string.
// Otherwise, it is printed as a sequence.
template <std::size_t N>
std::ostream& print_helper(std::ostream& os, const char (&arr)[N], int, int) {
for (std::size_t i = 0; i < N; ++i) {
if (!arr[i]) {
return os << arr;
}
}
return print_sequence_helper(os, arr);
}
// This version of print_helper will be called when T does not have an
// available stream insertion operator overload.
template <class T>
std::ostream& print_helper(std::ostream& os, const T&, ...) {
return os << "<" << demangle(typeid(T).name()) << " object>";
}
// Attempts to print the given object to the given stream.
// If T has an available stream insertion operator overload, that
// operator is used. Otherwise, a generic representation of the object
// is printed to os.
template <class T>
std::ostream& print(std::ostream& os, const T& t) {
// The extra parameters are needed so that the first overload of
// print_helper is preferred, followed by the third one.
return print_helper(os, t, 0, 0);
}
// ----------------------------------------------------------------------------
#define ASSERT_EQUAL(first, second) \
assert_equal((first), (second), __LINE__, \
"ASSERT_EQUAL(" #first ", " #second ")");
#define ASSERT_NOT_EQUAL(first, second) \
assert_not_equal((first), (second), __LINE__, \
"ASSERT_NOT_EQUAL(" #first ", " #second ")");
#define ASSERT_SEQUENCE_EQUAL(first, second) \
assert_sequence_equal((first), (second), __LINE__, \
"ASSERT_SEQUENCE_EQUAL(" #first ", " #second ")");
#define ASSERT_TRUE(value) \
assert_true((value), __LINE__, "ASSERT_TRUE(" #value ")");
#define ASSERT_FALSE(value) \
assert_false((value), __LINE__, "ASSERT_FALSE(" #value ")");
#define ASSERT_ALMOST_EQUAL(first, second, precision) \
assert_almost_equal((first), (second), (precision), __LINE__, \
"ASSERT_ALMOST_EQUAL(" #first ", " #second ", " \
#precision ")");
// Template logic to produce a static assertion failure when comparing
// incomparable types.
template <typename First, typename Second, typename = void>
struct is_equality_comparable : std::false_type {};
template <typename First, typename Second>
using enable_if_equality_comparable = typename std::enable_if<
std::is_same<bool, decltype(std::declval<First>() ==
std::declval<Second>())>::value and
std::is_same<bool, decltype(std::declval<First>() !=
std::declval<Second>())>::value and
(!std::is_array<typename std::remove_reference<First>::type>::value or
!std::is_array<typename std::remove_reference<Second>::type>::value),
void>::type;
template <typename First, typename Second>
struct is_equality_comparable<First, Second,
enable_if_equality_comparable<First, Second>>
: std::true_type {};
// Overloads for equality comparisons.
template <typename First, typename Second>
bool safe_equals_helper(const First& first, const Second& second) {
return first == second;
}
template <typename First, typename Second>
bool safe_not_equals_helper(const First& first, const Second& second) {
return first != second;
}
// Allow size_t to correctly be compared to int.
bool safe_equals_helper(std::size_t first, int second) {
return second >= 0 && static_cast<long long>(first) == second;
}
bool safe_equals_helper(int first, std::size_t second) {
return first >= 0 && first == static_cast<long long>(second);
}
bool safe_not_equals_helper(std::size_t first, int second) {
return second < 0 || static_cast<long long>(first) != second;
}
bool safe_not_equals_helper(int first, std::size_t second) {
return first < 0 || first != static_cast<long long>(second);
}
template <typename First, typename Second, typename = void>
struct safe_equals {
static_assert(is_equality_comparable<First, Second>::value,
"types cannot be compared with == and !=");
static bool equals(const First& first, const Second& second) {
return safe_equals_helper(first, second);
}
static bool not_equals(const First& first, const Second& second) {
return safe_not_equals_helper(first, second);
}
};
template <typename First, typename Second>
void assert_equal(First&& first, Second&& second, int line_number,
const char* assertion_text) {
if (safe_equals<First, Second>::equals(first, second)) {
return;
}
std::ostringstream reason;
print(reason, first);
reason << " != ";
print(reason, second);
throw TestFailure(reason.str(), line_number, assertion_text);
}
template <typename First, typename Second>
void assert_not_equal(First&& first, Second&& second, int line_number,
const char* assertion_text) {
if (safe_equals<First, Second>::not_equals(first, second)) {
return;
}
std::ostringstream reason;
reason << "Values unexpectedly equal: ";
print(reason, first);
reason << " == ";
print(reason, second);
throw TestFailure(reason.str(), line_number, assertion_text);
}
template <typename First, typename Second>
void assert_sequence_equal(First&& first, Second&& second, int line_number,
const char* assertion_text) {
using std::begin;
using std::end;
auto it1 = begin(first);
auto it2 = begin(second);
auto end1 = end(first);
auto end2 = end(second);
auto len1 = std::distance(it1, end1);
auto len2 = std::distance(it2, end2);
if (len1 != len2) { // different number of elements
std::ostringstream reason;
print(reason, first);
reason << " != ";
print(reason, second);
reason << " (sizes differ: " << len1 << " != " << len2 << ")";
throw TestFailure(reason.str(), line_number, assertion_text);
}
bool equal = true;
std::size_t position = 0;
for (; it1 != end1 and it2 != end2; ++it1, ++it2, ++position) {
if (not safe_equals<decltype(*it1), decltype(*it2)>::equals(
*it1, *it2)) {
equal = false;
break;
}
}
if (not equal) {
std::ostringstream reason;
print(reason, first);
reason << " != ";
print(reason, second);
reason << " (elements at position " << position << " differ: ";
print(reason, *it1);
reason << " != ";
print(reason, *it2);
reason << ")";
throw TestFailure(reason.str(), line_number, assertion_text);
}
}
//------------------------------------------------------------------------------
// THIS IS PART OF A WORKAROUND TO DEAL WITH STATIC
// INITIALIZATION SHENANIGANS.
// DO NOT CHANGE THIS UNLESS YOU REEEEALLY KNOW WHAT
// YOU'RE DOING. CONTACT akamil@umich.edu or jameslp@umich.edu IF
// YOU HAVE QUESTIONS ABOUT THIS.
#define TEST_SUITE_INSTANCE() \
static TestSuiteDestroyer destroyer; \
bool TestSuite::incomplete = false; \
TestSuite* TestSuite::instance = &TestSuite::get()
void TestCase::run(bool quiet_mode) {
try {
if (not quiet_mode) {
std::cout << "Running test: " << name << std::endl;
}
test_func();
if (not quiet_mode) {
std::cout << "PASS" << std::endl;
}
}
catch (TestFailure& failure) {
failure_msg = failure.to_string();
if (not quiet_mode) {
std::cout << "FAIL" << std::endl;
}
}
catch (std::exception& e) {
std::ostringstream oss;
oss << "Uncaught " << demangle(typeid(e).name()) << " in test \""
<< name << "\": \n";
oss << e.what() << '\n';
exception_msg = oss.str();
if (not quiet_mode) {
std::cout << "ERROR" << std::endl;
}
}
}
void TestCase::print(bool quiet_mode) {
if (quiet_mode) {
std::cout << name << ": ";
}
else {
std::cout << "** Test case \"" << name << "\": ";
}
if (not failure_msg.empty()) {
std::cout << "FAIL" << std::endl;
if (not quiet_mode) {
std::cout << failure_msg << std::endl;
}
}
else if (not exception_msg.empty()) {
std::cout << "ERROR" << std::endl;
if (not quiet_mode) {
std::cout << exception_msg << std::endl;
}
}
else {
std::cout << "PASS" << std::endl;
}
}
// ----------------------------------------------------------------------------
class ExitSuite : public std::exception {
public:
ExitSuite(int status_ = 0) : status(status_) {}
int status;
};
class SetComplete {
public:
SetComplete(bool& incomplete_) : incomplete(incomplete_) {
incomplete = true;
}
~SetComplete() {
incomplete = false;
}
private:
bool& incomplete;
};
int TestSuite::run_tests(int argc, char** argv) {
SetComplete completer(TestSuite::incomplete);
std::vector<std::string> test_names_to_run;
try {
test_names_to_run = get_test_names_to_run(argc, argv);
}
catch (ExitSuite& e) {
return e.status;
}
for (auto test_name : test_names_to_run) {
if (tests_.find(test_name) == end(tests_)) {
throw std::runtime_error("Test " + test_name + " not found");
}
}
for (auto test_name : test_names_to_run) {
tests_.at(test_name).run(quiet_mode);
}
std::cout << "\n*** Results ***" << std::endl;
for (auto test_name : test_names_to_run) {
tests_.at(test_name).print(quiet_mode);
}
auto num_failures =
std::count_if(tests_.begin(), tests_.end(),
[](std::pair<std::string, TestCase> test_pair) {
return not test_pair.second.failure_msg.empty();
});
auto num_errors =
std::count_if(tests_.begin(), tests_.end(),
[](std::pair<std::string, TestCase> test_pair) {
return not test_pair.second.exception_msg.empty();
});
if (not quiet_mode) {
std::cout << "*** Summary ***" << std::endl;
std::cout << "Out of " << test_names_to_run.size()
<< " tests run:" << std::endl;
std::cout << num_failures << " failure(s), " << num_errors
<< " error(s)" << std::endl;
}
if (num_failures == 0 and num_errors == 0) {
return 0;
}
return 1;
}
std::vector<std::string> TestSuite::get_test_names_to_run(int argc,
char** argv) {
std::vector<std::string> test_names_to_run;
#if UNIT_TEST_ENABLE_REGEXP
bool regexp_matching = false;
#endif
for (auto i = 1; i < argc; ++i) {
if (argv[i] == std::string("--show_test_names") or
argv[i] == std::string("-n")) {
TestSuite::get().print_test_names(std::cout);
std::cout << std::flush;
throw ExitSuite();
}
else if (argv[i] == std::string("--quiet") or
argv[i] == std::string("-q")) {
TestSuite::get().enable_quiet_mode();
}
#if UNIT_TEST_ENABLE_REGEXP
else if (argv[i] == std::string("--regexp") or
argv[i] == std::string("-e")) {
regexp_matching = true;
}
#endif
else if (argv[i] == std::string("--help") or
argv[i] == std::string("-h")) {
std::cout << "usage: " << argv[0]
#if UNIT_TEST_ENABLE_REGEXP
<< " [-h] [-e] [-n] [-q] [[TEST_NAME] ...]\n";
#else
<< " [-h] [-n] [-q] [[TEST_NAME] ...]\n";
#endif
std::cout
<< "optional arguments:\n"
<< " -h, --help\t\t show this help message and exit\n"
#if UNIT_TEST_ENABLE_REGEXP
<< " -e, --regexp\t\t treat TEST_NAME as a regular expression\n"
#endif
<< " -n, --show_test_names\t print the names of all "
"discovered test cases and exit\n"
<< " -q, --quiet\t\t print a reduced summary of test results\n"
<< " TEST_NAME ...\t\t run only the test cases whose names "
"are "
"listed here. Note: If no test names are specified, all "
"discovered tests are run by default."
<< std::endl;
throw ExitSuite();
}
else {
test_names_to_run.push_back(argv[i]);
}
}
if (test_names_to_run.empty()) {
std::transform(
std::begin(tests_), std::end(tests_),
std::back_inserter(test_names_to_run),
[](const std::pair<std::string, TestCase>& p) { return p.first; });
}
#if UNIT_TEST_ENABLE_REGEXP
else if (regexp_matching) {
std::ostringstream pattern;
for (auto iter = test_names_to_run.begin();
iter != test_names_to_run.end(); ++iter) {
if (iter != test_names_to_run.begin()) {
pattern << "|";
}
pattern << "(" << *iter << ")";
}
std::regex name_regex{pattern.str()};
test_names_to_run.clear();
for (const auto& test_pair : tests_) {
if (std::regex_match(test_pair.first, name_regex)) {
test_names_to_run.push_back(test_pair.first);
}
}
}
#endif
return test_names_to_run;
}
std::ostream& operator<<(std::ostream& os, const TestFailure& test_failure) {
return test_failure.print(os);
}
//------------------------------------------------------------------------------
#if defined(__clang__) || defined(__GLIBCXX__) || defined(__GLIBCPP__)
#include <cxxabi.h>
#include <cstdlib>
std::string demangle(const char* typeinfo_name) {
int status = 0;
char* demangled =
abi::__cxa_demangle(typeinfo_name, nullptr, nullptr, &status);
if (status == 0) {
std::string result = demangled;
std::free(demangled);
return result;
}
else {
return typeinfo_name;
}
}
#else
std::string demangle(const char* typeinfo_name) {
return typeinfo_name;
}
#endif // defined(__clang__) || defined(__GLIBCXX__) || defined(__GLIBCPP__)
//------------------------------------------------------------------------------
void assert_true(bool value, int line_number, const char* assertion_text) {
if (value) {
return;
}
std::ostringstream reason;
reason << "Expected true, but was false";
throw TestFailure(reason.str(), line_number, assertion_text);
}
void assert_false(bool value, int line_number, const char* assertion_text) {
if (not value) {
return;
}
std::ostringstream reason;
reason << "Expected false, but was true";
throw TestFailure(reason.str(), line_number, assertion_text);
}
void assert_almost_equal(double first, double second, double precision,
int line_number, const char* assertion_text) {
if (std::abs(first - second) <= precision) {
return;
}
std::ostringstream reason;
// For now, we'll just set the precision arbitrarily high.
// In the future, we may decide to add an option to configure
// the output precision.
reason.precision(20);
reason << "Values too far apart: " << first << " and " << second;
throw TestFailure(reason.str(), line_number, assertion_text);
}
#endif // UNIT_TEST_FRAMEWORK_HPP
| true |
365e2570c91e74dfd2b5bd52e32f68aec4672b5b | C++ | AlexaEgorova/KiTG | /fordBellman.cpp | UTF-8 | 1,700 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
long long inf = 1e7; //изначально расстояние до всех вершин будет равно бесконечности = 10000000
int n, m;
cin >> n >> m;
vector<int> H(n, -1), L(m), I(m), J(m), C(m);
for (int i = 0; i < m; i += 1){
cin >> I[i] >> J[i] >> C[i];
//--I[i], --J[i];//расскомментировать, если вершины в задаче нумеруются с единицы
}
for (int i = 0; i < m; i += 1){
L[i] = H[I[i]];
H[I[i]] = i;
}
vector<int> distance(n, inf);
distance[0] = 0;//Расстояние от вершины с которой считаем до неё же самой 0
for (int i = 0; i < n - 1; i+=1){
for (int j = 0; j < m; j+=1){
if (distance[I[j]] < inf){//Заходим, если эта вершина была хоть раз затронута;
/*В нашей задаче первый раз выполнится, когда
ребро будет исходить из вершины 0
*/
distance[J[j]] = min(distance[J[j]], distance[I[j]] + C[j]);
/*
Берём минимум из расстояния которое было посчитано до этой вершины
и расстояние которое может быть с новым ребром
*/
}
}
}
for (int i = 0; i < n; i += 1){
if (distance[i] == inf)
distance[i] = 30000;//для задачи http://acmp.ru/index.asp?main=task&id_task=138
cout << distance[i] << " \n"[i + 1==n];//Выводим расстояние до всех вершин от вершины 0
}
return 0;
} | true |
c8726ddbc0611ba50041a2407fac69cde0f84b6f | C++ | sikorski-as/script-interpreter | /structures/ast/VariableDefinition.h | UTF-8 | 822 | 3.03125 | 3 | [] | no_license | #ifndef TKOM_INTERPRETER_VARIABLEDEFINITION_H
#define TKOM_INTERPRETER_VARIABLEDEFINITION_H
#include <string>
#include "Statement.h"
#include "Assignable.h"
class VariableDefinition : public Statement{
public:
VariableDefinition(std::string typeName, std::string name, Assignable::ptr value)
: name(name), typeName(typeName), value(value)
{
}
Type getType() const override {
return Type::var_definition;
}
std::string representation() const override {
return "Definition of variable " + typeName + " " + name;
};
ChildrenList getChildren() override {
auto children = ChildrenList({value});
return children;
}
std::string name;
std::string typeName;
Assignable::ptr value;
};
#endif //TKOM_INTERPRETER_VARIABLEDEFINITION_H
| true |
bf73b8cb60bea4bf2fadbbd3a9f24fc98a7018ac | C++ | wangjianfei/Tony_high_C | /own_study_1020/class_exec.cpp | UTF-8 | 1,743 | 4.15625 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class Time
{
public:
void set_time(); //公共成员函数
void show_time(); //公共成员函数
private:
int hour;
int minute;
int sec;
};
void Time::set_time()
{
cout<<"please input hour"<<endl;
cin>>hour;
cout<<"please input minute"<<endl;
cin>>minute;
cout<<"please input sec"<<endl;
cin>>sec;
}
void Time::show_time()
{
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
int main(void)
{
Time t1;
t1.set_time();
t1.show_time();
Time t2;
t2.set_time();
t2.show_time();
return 0;
}
/*函数写法比较繁琐 */
/*
int main(void)
{
Time t1;
cout<<"please input hour:"<<endl;
cin>>t1.hour;
cout<<"please input minute:"<<endl;
cin>>t1.minute;
cout<<"please input sec:"<<endl;
cin>>t1.sec;
cout<<t1.hour<<":"<<t1.minute<<":"<<t1.sec<<endl;
Time t2;
cout<<"please input hour:"<<endl;
cin>>t2.hour;
cout<<"please input minute:"<<endl;
cin>>t2.minute;
cout<<"please input sec:"<<endl;
cin>>t2.sec;
cout<<t2.hour<<":"<<t2.minute<<":"<<t2.sec<<endl;
return 0;
}*/
/*下面是一个完整的关于类的练习的程序 类的函数在类内声明 在类外定义 还有一点
* 关于类内的内置函数*/
/*class Student
{
public:
inline void display();
Student()
{
num = 10123;
name = "wangjianfei";
sex = 'M';
}
private:
int num;
string name;
char sex;
};
inline void Student::display()
{
cout<<"num: "<<num<<endl;
cout<<"name: "<<name<<endl;
cout<<"sex: "<<sex<<endl;
}
int main(int argc, const char *argv[])
{
Student stud1;
stud1.display();
return 0;
}*/
| true |
facdf92985604c154db801ffb40ee971e68224ed | C++ | JakeBrawer/misc | /classes/yale/oop/HW3/conway_main.cpp | UTF-8 | 2,299 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <string>
#include "conway.h"
using cs427_527::Conway;
int main(int argc, char **argv)
{
char *s = argv[0] + strlen(argv[0]) - 1;
while (s > argv[0] && *(s - 1) != '/')
{
s--;
}
std::string exeName = s;
try
{
bool interactive = (argc > 1 && strcmp(argv[1], "-i") == 0);
int indexOfStartConfig = (interactive ? 2 : 1);
int indexOfMove = indexOfStartConfig;
Conway puzzle;
if (indexOfStartConfig + 1 < argc && strcmp(argv[indexOfStartConfig], "-f") == 0)
{
std::ifstream in(argv[indexOfStartConfig + 1]);
puzzle = Conway(in);
indexOfMove += 2;
}
if (!interactive)
{
int indexFirstMove = indexOfMove;
int fromR, fromC, toR, toC;
while (indexOfMove + 3 < argc &&
(fromR = atoi(argv[indexOfMove]),
fromC = atoi(argv[indexOfMove + 1]),
toR = atoi(argv[indexOfMove + 2]),
toC = atoi(argv[indexOfMove + 3]),
puzzle.isLegalMove(fromR, fromC, toR, toC)))
{
puzzle.makeMove(fromR, fromC, toR, toC);
indexOfMove += 4;
}
if (indexOfMove + 3 < argc)
{
std::cout << exeName << ": illegal move "
<< argv[indexOfMove] << " "
<< argv[indexOfMove + 1] << " "
<< argv[indexOfMove + 2] << " "
<< argv[indexOfMove + 3]
<< " in position "
<< (indexOfMove - indexFirstMove) / 4 + 1
<< " for " << std::endl
<< puzzle;
}
else
{
if (puzzle.isSolved())
{
std::cout << "SOLVED" << std::endl;
}
else
{
std::cout << puzzle;
}
}
}
else
{
std::cout << puzzle;
int fromR, fromC, toR, toC;
while (!puzzle.isSolved() && std::cin >> fromR >> fromC >> toR >> toC)
{
if (puzzle.isLegalMove(fromR, fromC, toR, toC))
{
puzzle.makeMove(fromR, fromC, toR, toC);
std::cout << puzzle;
}
else
{
std::cout << "illegal move" << std::endl;
}
}
if (puzzle.isSolved())
{
std::cout << puzzle.totalMoves() << " moves" << std::endl;
}
}
}
catch (const char *s)
{
std::cout << exeName << ": " << s << std::endl;
}
}
| true |
4edda2151d6fc8e396a3cfb20fe55cf8afea9340 | C++ | MuazAlhaidar/Fall-2020---AI-Class-Search-Algorithms-HW1---Console---Individual-Project | /PrioritySearch.hpp | UTF-8 | 1,580 | 2.859375 | 3 | [] | no_license | #ifndef _PRIORITY_
#define _PRIORITY_
#include "NodeAndMap.hpp"
#include <iostream>
using namespace NodeAndMap_namespace;
namespace PrioritySearch_namespace {
template <class T>
void PrioritySearch() {
std::priority_queue<node, std::vector<node>, T> frontierSet;
setMapAndSets();
frontierSet.push(nodeGrid[1][3]);
while (!frontierSet.empty()) {
node currentNode = frontierSet.top();
exploredSet_hashMap.emplace(currentNode.number, currentNode);
frontierSet.pop();
if (currentNode.status == FREE) {
currentNode.status = NOTFREE;
currentNode.isVisited = true;
} else if (currentNode.status == GOAL) {
currentNode.isVisited = true;
break;
}
std::vector<node> thisNodeNeighbors = getNodeNeighbors(currentNode.position);
for (short y = 0; y < thisNodeNeighbors.size(); y++) {
thisNodeNeighbors[y].number = assignNodeNumber();
thisNodeNeighbors[y].isVisited = true;
addNodesToGrid(thisNodeNeighbors[y]);
}
for (auto x : thisNodeNeighbors) {
frontierSet.push(x);
}
}
time_t now = time(0);
struct tm tstruct;
tstruct = *localtime(&now);
std::cout << "Muaz Alhaidar(omunam) - Time: ";
std::cout << (((tstruct.tm_hour - 12) < 0) ? tstruct.tm_hour : tstruct.tm_hour - 12);
std::cout << ":" << tstruct.tm_min << ":" << tstruct.tm_sec << std::endl;
// Print the map after final Success
printMap();
}
} // namespace PrioritySearch_namespace
#endif | true |
1442d185ac2bbf28d29324428220b04b1eff12bf | C++ | Saharokrafinad/OOP_Panasenko | /OOP_Panasenko/Main.cpp | UTF-8 | 751 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include "Program.h"
using namespace std;
int main(int argc, char* argv[])
{
setlocale(LC_ALL, "Russian");
if (argc != 3)
{
cout << "Не найдены файлы in_file out_file" << endl;
system("pause");
exit(1);
}
ifstream inFileStream(argv[1]);
ofstream outFileStream(argv[2]);
Container c;
cout << "Старт" << endl;
c.InContainer(inFileStream);
cout << "Контейнер заполнен" << endl;
cout << "Контейнер отсортирован" << endl;
c.Sort();
c.OutContainer(outFileStream);
c.OutRectangles(outFileStream);
c.ClearContainer();
cout << "Контейнер очищен" << endl;
cout << "Завершение работы" << endl;
system("pause");
return 0;
} | true |
9432aa1122f6427e2dce3243330d8f6e2e194be2 | C++ | Sondro/Acid | /Sources/Graphics/Commands/CommandPool.hpp | UTF-8 | 596 | 2.78125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <thread>
#include <vulkan/vulkan.h>
#include "Export.hpp"
namespace acid {
/**
* @brief Class that represents a command pool.
*/
class ACID_EXPORT CommandPool {
public:
explicit CommandPool(const std::thread::id &threadId = std::this_thread::get_id());
~CommandPool();
operator const VkCommandPool &() const { return m_commandPool; }
const VkCommandPool &GetCommandPool() const { return m_commandPool; }
const std::thread::id &GetThreadId() const { return m_threadId; }
private:
VkCommandPool m_commandPool = VK_NULL_HANDLE;
std::thread::id m_threadId;
};
}
| true |
08fb0bbed5865548356a4645afab0ff69ddd4623 | C++ | D3E0/RTA | /Solved/Multi-University Training Contest/E-Sort StringB.cpp | UTF-8 | 1,586 | 2.6875 | 3 | [] | no_license | //============================================================================
//Name:牛客多校第三场 E Sort String 字符串Hash
//https://www.nowcoder.com/acm/contest/141/E
//============================================================================
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ULL;
typedef long long LL;
const int MAX = 2e6 + 50;
struct hash_table {
ULL seed;
ULL Hash[MAX], tmp[MAX];
void set(ULL _seed) {
seed = _seed;
}
void work(char *s, int n) {
LL i, j;
tmp[0] = 1;
Hash[0] = 0;
for (i = 1; i <= n; i++) {
tmp[i] = tmp[i - 1] * seed;
}
for (i = 1; i <= n; i++) {
Hash[i] = (Hash[i - 1] * seed + (s[i] - 'a'));
}
}
// str[l..r]
ULL get(int l, int r) {
return (Hash[r] - Hash[l - 1] * tmp[r - l + 1]);
}
} h;
char str[MAX];
unordered_map<LL, int> mymap;
vector<int> ans[MAX];
int main() {
scanf("%s", str + 1);
int len = strlen(str + 1);
for (int i = 1; i <= len; i++) {
str[i + len] = str[i];
}
h.set(2333);
h.work(str, 2 * len);
int cnt = 0;
for (int i = 1; i <= len; i++) {
LL tt = h.get(i, i + len - 1);
if (!mymap.count(tt)) {
mymap[tt] = cnt++;
}
ans[mymap[tt]].push_back(i - 1);
}
printf("%d\n", cnt);
for (int i = 0; i < cnt; i++) {
printf("%d", ans[i].size());
for (int j : ans[i]) {
printf(" %d", j);
}
puts("");
}
return 0;
} | true |
ab8870293d7b2bd2e5375e4f23cfba81c4b245d3 | C++ | iagsav/AS | /T4/AvdeevaAN/task2.cpp | UTF-8 | 878 | 3.421875 | 3 | [] | no_license | #include<stdio.h>
#include<vector>
#include<time.h>
#include<stdlib.h>
using namespace std;
vector<int> countingSort(vector<int>& a, int max)
{
vector<int> counts;
counts.resize(max);
for(auto& it : a)
{
counts[it]++;
}
for(int index = 1; index < max; index++)
{
counts[index] = counts[index-1] + counts[index];
}
vector<int> L;
L.resize(a.size());
for(auto& it : a)
{
int index = counts[it] - 1;
L[index] = it;
counts[it]--;
}
return L;
}
void test(int size)
{
vector<int> arr;
arr.resize(size);
for(size_t i = 0; i < size; i++)
{
arr[i] = rand() % size;
}
time_t t1 = time(0);
vector<int> b=countingSort(arr, size);
time_t t2 = time(0);
printf("Array size %d sorted in %d sec\n", size, t2-t1);
}
int main()
{
test(100);
}
| true |
3a487a64c8e4b01e2543176566b84dbfb3ae8315 | C++ | cleggacus/opengl-tetris | /src/game/Cell.h | UTF-8 | 987 | 3.0625 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <array>
#include "../include/VertexBuffer.h"
using namespace std;
struct Vertex{
float positionX;
float positionY;
float texCoordX;
float texCoordY;
float color;
};
enum BlockType {
none, I, J, L, O, S, T, Z
};
class Cell{
private:
unsigned int mX;
unsigned int mY;
float mCellW;
float mCellH;
BlockType mColor;
public:
Cell(unsigned int x = 0, unsigned int y = 0, float w = 0, float h = 0);
~Cell();
void updateColor(BlockType c);
array<Vertex, 4> getQuadVertices();
void setPosition(unsigned int x, unsigned int y);
inline BlockType getColor() const {return mColor;};
inline unsigned int getX() const {return mX;};
inline unsigned int getY() const {return mY;};
inline unsigned int getCellWidth() const {return mCellW;};
inline unsigned int getCellHeight() const {return mCellH;};
}; | true |
76eca800426f4768d5314fe8b17e298b928db352 | C++ | CdTCzech/AdventOfCode2015 | /Days/Day13.cpp | UTF-8 | 2,887 | 2.953125 | 3 | [] | no_license | #include "Day13.h"
#include "../FileReader.h"
#include <algorithm>
#include <iterator>
#include <map>
#include <sstream>
#include <string>
namespace day13
{
int64_t part1()
{
std::map<std::string, Person> persons;
int64_t result = 0;
for (const auto& line : getLineByLine<std::vector<std::string>>("Days\\day13.txt", [](std::string& var)
{
var[var.size() - 1] = ' ';
std::istringstream iss(var);
return std::vector<std::string>(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{});
}))
{
if (persons.find(line[0]) == persons.end()) persons.insert({ line[0], Person{ line[0], {} } });
auto multiplier = 1;
if (line[2][0] == 'l') multiplier = -1;
persons.at(line[0]).neighbours.insert({ line[10], std::stoi(line[3]) * multiplier });
}
std::vector<std::string> unique;
for (auto& person : persons) unique.push_back(person.first);
std::sort(unique.begin(), unique.end());
do {
auto sum = 0;
for (size_t i = 0; i < unique.size() - 1; ++i)
{
sum += persons[unique[i]].neighbours[unique[i + 1]];
sum += persons[unique[i + 1]].neighbours[unique[i]];
}
sum += persons[unique[0]].neighbours[unique[unique.size() - 1]];
sum += persons[unique[unique.size() - 1]].neighbours[unique[0]];
if (sum > result) result = sum;
} while (std::next_permutation(unique.begin(), unique.end()));
return result;
}
int64_t part2()
{
std::map<std::string, Person> persons;
int64_t result = 0;
for (const auto& line : getLineByLine<std::vector<std::string>>("Days\\day13.txt", [](std::string& var)
{
var[var.size() - 1] = ' ';
std::istringstream iss(var);
return std::vector<std::string>(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{});
}))
{
if (persons.find(line[0]) == persons.end()) persons.insert({line[0], Person{ line[0], {} }});
auto multiplier = 1;
if (line[2][0] == 'l') multiplier = -1;
persons.at(line[0]).neighbours.insert({ line[10], std::stoi(line[3]) * multiplier });
}
std::vector<std::string> unique;
for (auto& person : persons) unique.push_back(person.first);
persons.insert({ "me", Person{ "me", {} }});
for (auto& person : unique)
{
persons.at("me").neighbours.insert({ person, 0 });
persons.at(person).neighbours.insert({ "me", 0 });
}
unique.emplace_back("me");
std::sort(unique.begin(), unique.end());
do {
auto sum = 0;
for (size_t i = 0; i < unique.size() - 1; ++i)
{
sum += persons[unique[i]].neighbours[unique[i + 1]];
sum += persons[unique[i + 1]].neighbours[unique[i]];
}
sum += persons[unique[0]].neighbours[unique[unique.size() - 1]];
sum += persons[unique[unique.size() - 1]].neighbours[unique[0]];
if (sum > result) result = sum;
} while (std::next_permutation(unique.begin(), unique.end()));
return result;
}
} // namespace day13 | true |
91749b9dee9c8529d52d9890a3e01e267d38349d | C++ | HidehikoKondo/TheLastHairCocos2dx | /the_last_hair2dx/Classes/game/GameRuleManager.cpp | UTF-8 | 2,298 | 2.640625 | 3 | [] | no_license | //
// GameRuleManager.cpp
// ther_last_hair2dx
//
// Created by 大原幸夫 on 2014/08/07.
//
//
#include "GameRuleManager.h"
USING_NS_CC;
GameRuleManager::GameRuleManager()
{
}
GameRuleManager::~GameRuleManager()
{
}
/**
* シングルトンインスタンス
*/
GameRuleManager * GameRuleManager::getInstance()
{
static GameRuleManager model;
return &model;
}
/**
* ランキングの情報を取得する
* @return CCArray[CCString] ランキングリスト
*/
cocos2d::CCArray * GameRuleManager::getRankingList(GAME_MODE mode)
{
CCArray *ret = CCArray::create();
char buff[256];
for(int index = 0; index < 10 ; index++)
{
sprintf(buff,"ranking_%02d_%02d",mode,index);
int a = CCUserDefault::sharedUserDefault()->getIntegerForKey(buff, 0);
ret->addObject(CCString::createWithFormat("%d",a));
}
return ret;
}
/**
* ランキングのスコアを登録する
*/
void GameRuleManager::setRankingScore(GAME_MODE mode,long value)
{
//検索
int newRecordIndex = 10;
char buff[256];
for(int index = 0; index < 10 ; index++)
{
sprintf(buff,"ranking_%02d_%02d",mode,index);
int a = CCUserDefault::sharedUserDefault()->getIntegerForKey(buff, 0);
if( (mode == GM_CHALENGE && a < value) ||
(mode == GM_TIME_TRIAL && a > value))
{
newRecordIndex = index;
break;
}
}
//書き換え
int afterScore = value;
int beforeScore;
for(int index = newRecordIndex; index < 10 ; index++)
{
sprintf(buff,"ranking_%02d_%02d",mode,index);
beforeScore = CCUserDefault::sharedUserDefault()->getIntegerForKey(buff, 0);
CCUserDefault::sharedUserDefault()->setIntegerForKey(buff, afterScore);
afterScore = beforeScore;
}
}
/**
* ランキングの登録がされるか
*/
bool GameRuleManager::isNewRecordScore(GAME_MODE mode,long value)
{
bool ret = false;
char buff[256];
for(int index = 0; index < 10 ; index++)
{
sprintf(buff,"ranking_%02d_%02d",mode,index);
int a = CCUserDefault::sharedUserDefault()->getIntegerForKey(buff, 0);
if(a < value)
{
ret = true;
break;
}
}
return ret;
}
| true |
ee4f5d04b8dfe4ce2f44e2da73d3b476679f0c94 | C++ | enarantu/ProjectEuler | /self_contained_solutions/problem36.cpp | UTF-8 | 812 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class Num{
int number;
string dec;
string bin;
public:
Num(int x);
bool isDoublePalindome();
};
int main(){
long long sum = 0;
for(long long i = 1 ; i < 1000000 ; i++){
Num n(i);
if(n.isDoublePalindome()){
sum += i;
}
}
cout << sum << endl;
return 0;
}
Num::Num(int x){
dec = to_string(x);
number = x;
while (x > 0){
bin.push_back( 48 + x%2 );
x /= 2;
}
}
bool Num::isDoublePalindome(){
bool ans = true;
for(size_t i = 0 ; i <= dec.size()/2 ; i++){
size_t opp = dec.size() - i - 1;
if(dec[i] != dec[opp]){
ans = false;
break;
}
}
if(ans){
for(size_t i = 0 ; i <= bin.size() ; i++){
size_t opp = bin.size() - i - 1;
if(bin[i] != bin[opp]){
ans = false;
break;
}
}
}
return ans;
} | true |
7d4baf4c991f1df176a1733416a01f7956bb073e | C++ | RiverApril/AAAA | /Document.hpp | UTF-8 | 1,901 | 2.609375 | 3 | [] | no_license | #pragma once
#include <string>
#include <vector>
#define VERSION_NORMAL 1
#define VERSION_COLOR 2
#define C_DARK_BLACK 0x0 // white when background is black
#define C_DARK_RED 0x1
#define C_DARK_GREEN 0x2
#define C_DARK_YELLOW 0x3
#define C_DARK_BLUE 0x4
#define C_DARK_MAGENTA 0x5
#define C_DARK_CYAN 0x6
#define C_DARK_WHITE 0x7
#define C_LIGHT_BLACK 0x8
#define C_LIGHT_RED 0x9
#define C_LIGHT_GREEN 0xA
#define C_LIGHT_YELLOW 0xB
#define C_LIGHT_BLUE 0xC
#define C_LIGHT_MAGENTA 0xD
#define C_LIGHT_CYAN 0xE
#define C_LIGHT_WHITE 0xF
#define C_LIGHT_GRAY C_DARK_WHITE
#define C_DARK_GRAY C_LIGHT_BLACK
#define C_WHITE C_LIGHT_WHITE
#define C_BLACK C_DARK_BLACK
struct cell{
char text;
unsigned char fg;
unsigned char bg;
cell(char t, unsigned char fg, unsigned char bg) : text(t), fg(fg), bg(bg){}
};
char colorToChar(unsigned char c);
unsigned char charToColor(char c);
class Document{
int width;
int height;
bool needsSave;
std::vector<cell*> data;
std::string filename;
public:
Document(std::string filename);
Document(const Document *other);
~Document();
void initalizeEmpty(int width, int height);
bool loadFromFile();
bool saveToFile(std::string writeName);
bool saveToFile();
cell get(int frame, int x, int y, cell ifError);
void set(int frame, int x, int y, cell c);
void insert(int frame, int x, int y, cell c);
void backspace(int frame, int x, int y, cell c);
void insertLine(int frame, int y);
void removeLine(int frame, int y);
bool resize(int newWidth, int newHeight);
void insertFrameAfter(int frame, bool copyCurrent);
void insertFrameBefore(int frame, bool copyCurrent);
void removeFrame(int frame);
void clearFrame(int frame);
int getFrameCount();
int getWidth();
int getHeight();
std::string getFilename();
bool doesNeedSave();
}; | true |
571c46bb3291cfb132cbcb5343385f11fa06bcde | C++ | SunNEET/LeetCode | /HighFrequency/65. Valid Number.cpp | UTF-8 | 2,304 | 3.625 | 4 | [] | no_license | class Solution {
public:
bool isNumber(string s) {
// 一個數字的構成 = 符號 + 浮點數 + e + 符號 + 整數
// 用 DFA 來處理這個問題會比較容易,可以把每個字元的輸入看成狀態的input,讓他發生轉移
// 先整裡一下怎麼設定不同狀態,再來設定彼此之間怎麼移轉,做題前把狀態機先畫出來
// s0: 起始狀態 (什麼都沒有)
// s1: 前半部有了"+-"符號 ("+" or "-" or " +"...)
// s2: 前半部有了數字("12" or " 1" or " -3" or "+445") (accept)
// s3: 有了e 以此區分前後半部("12e" or " 1e" or " -3e")
// s4: 後半部有了"+-"符號("12e+" or " 1e-" or " -3e+")
// s5: 後半部有了數字("12e+22", " 1e-3", " -3e+1")(accept)
// s6: 前半部有了"."("12.", " 1.", " -3.", "+445.")
// s7: 前半部"."後面的數字("12.3", " 1.")
// s8: 後半部的數字+了空白
// s9: .前沒有數字
enum InputType {
INVALID,
SPACE,
SIGN,
DIGIT,
DOT,
EXPONENT
};
const int transitionTable[][6] = {
{-1, 0, 1, 2, 9, -1}, // s0 吃到各種input時會前往的狀態
{-1, -1, -1, 2, 9, -1}, // s1
{-1, 8, -1, 2, 6, 3}, // s2
{-1, -1, 4, 5, -1, -1}, // s3
{-1, 8, -1, 5, -1, -1}, // s4
{-1, 8, -1, 5, -1, -1}, // s5
{-1, 8, -1, 7, -1, 3}, // s6
{-1, 8, -1, 7, -1, 3}, // s7
{-1, 8, -1, -1, -1, -1}, // s8
{-1, -1, -1, 7, -1, -1} // s9
};
int state = 0;
for(char c : s) {
InputType inputType = INVALID;
if(isspace(c))
inputType = SPACE;
else if(c=='+'||c=='-')
inputType = SIGN;
else if(isdigit(c))
inputType = DIGIT;
else if(c=='.')
inputType = DOT;
else if(c=='e')
inputType = EXPONENT;
state = transitionTable[state][inputType];
if(state==-1) return false;
}
return state==2 || state==6 || state==7 || state==5 || state == 8;
}
}; | true |
002049c8e66a98d74ce65499db58b875ab791987 | C++ | xRiveria/Amethyst | /Amethyst/Source/Runtime/ECS/World.h | UTF-8 | 1,537 | 2.515625 | 3 | [] | no_license | #pragma once
#include "../../Core/ISubsystem.h"
#include <vector>
#include <string>
namespace Amethyst
{
class Context;
class Entity;
class World : public ISubsystem
{
public:
World(Context* engineContext);
~World();
// === Subsystem ===
bool OnInitialize() override;
void OnUpdate(float deltaTime) override;
void CreateNewWorld();
/// Save World To File
/// Load World From File
const std::string& RetrieveWorldName() { return m_WorldName; }
void ResolveWorld() { m_ResolveWorld = true; }
bool IsWorldLoading();
//Entities
std::shared_ptr<Entity> EntityCreate(bool isActive = true);
bool EntityExists(const std::shared_ptr<Entity>& entity);
void EntityRemove(const std::shared_ptr<Entity>& entity);
std::vector<std::shared_ptr<Entity>> RetrieveEntityRoots();
const std::shared_ptr<Entity>& RetrieveEntityByName(const std::string& entityName);
const std::shared_ptr<Entity>& RetrieveEntityByID(uint32_t entityID);
const std::vector<std::shared_ptr<Entity>>& RetrieveAllEntities() { return m_Entities; }
private:
void ClearWorld();
void _EntityRemove(const std::shared_ptr<Entity>& entity);
// Common Entity Creation
/// std::shared_ptr<Entity> CreateEnvironment();
std::shared_ptr<Entity> CreateCamera();
/// std::shared_ptr<Entity> CreateDirectionalLight();
private:
std::string m_WorldName;
bool m_WasInEditorMode = false;
bool m_ResolveWorld = true;
/// Profiler Pointer.
Input* m_Input = nullptr;
std::vector<std::shared_ptr<Entity>> m_Entities;
};
} | true |
e12071ac63b98b2ac3936487e446d03f1c094312 | C++ | Jasonzhu0314/cpp-review | /map/map_sort.cc | UTF-8 | 865 | 3.1875 | 3 | [] | no_license | /*************************************************************************
> File Name: map_sort.cc
> Author:Jasonzhu
> Mail: jasonzhu_0314@163.com
> Created Time: Tue 13 Jul 2021 07:59:17 AM CST
************************************************************************/
#include <iostream>
#include <map>
using namespace std;
class MyCompare {
public:
bool operator()(int a, int b) {
return a > b;
}
};
template<class T>
void PrintMap(map<int, int, T> &m) {
for (auto it = m.begin(); it != m.end(); it++) {
cout << "key:" << (*it).first << " value:" << it->second << endl;
}
cout << endl;
}
void test02() {
map<int, int, MyCompare> m;
m.insert(pair<int, int> (1, 10));
m.insert(make_pair(3, 30));
m.insert(pair<int, int> (2, 20));
m.insert(map<int, int>::value_type(5, 50));
PrintMap(m);
}
int main() {
test02();
return 0;
}
| true |
640afd31ad04e7fe46c2128cc2e3954821aaa8a3 | C++ | piyushsaha/graph-algorithms | /sssp_undirected_unweighted_bfs.cpp | UTF-8 | 1,857 | 3.203125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int V;
vector<int> *adj;
//char *labels;
bool *visited;
int *parent;
void insertEdge(int u, int v) {
adj[u].push_back(v);
adj[v].push_back(u);
}
bool DFSRec(int s, int parent) {
visited[s] = true;
for(int a=0; a<adj[s].size(); a++) {
int adjacent = adj[s][a];
// Adjacent is visited and not parent, so cycle exists
if(visited[adjacent]==true && adjacent!=parent) {
return true;
}
// Adjacent is not visited
else if(visited[adjacent]==false) {
// Loop exists in the adjacent vertex's DFS, so cycle exists
if(DFSRec(adjacent, s)) {
return true;
}
}
}
// If both above conditions fail, NO cycle exists
return false;
}
void shortestPath(int s=0) {
int dist[V];
for(int i=0; i<V; i++) {
dist[i] = INT_MAX;
}
queue<int> q;
dist[s] = 0;
q.push(s);
int unit = 1;
while(q.empty() == false) {
int f = q.front();
q.pop();
for(int a=0; a<adj[f].size(); a++) {
int adjacent = adj[f][a];
if(dist[f] + unit < dist[adjacent]) {
dist[adjacent] = dist[f] + unit;
q.push(adjacent);
}
}
}
for(int i=0; i<V; i++) {
if(dist[i] == INT_MAX) {
cout << "Distance from " << s << " to " << i << ": INFINITY" << endl;
}
else {
cout << "Distance from " << s << " to " << i << ": " << dist[i] << endl;
}
}
}
int main() {
cout << "Enter no. of nodes: ";
cin >> V;
adj = new vector<int>[V];
visited = new bool[V];
// labels = new char[V];
// cout << "Enter labels: " << endl;
// for(int i=0; i<n; i++) {
// char l;
// cin >> l;
// labels[size] = l;
// size++;
// }
for(int i=0; i<V; i++) {
visited[i] = false;
}
int u, v;
while(u!=-1) {
cout << "Enter edge from and to (enter either as -1 to stop entering edges): ";
cin >> u >> v;
if(u!=-1 && v!=-1) {
insertEdge(u, v);
}
}
shortestPath();
return 0;
}
| true |
a5ae46bf718085c258af78782a4c215d40e1e2e4 | C++ | simhoonnam/algorithm | /Recursion Function,DFS,BFS/2.cpp | UTF-8 | 477 | 3.078125 | 3 | [] | no_license | #include<stdio.h>
int result[11000000], tmp = 0, middle = 0;
void binaryTree(int n) {
if (n == 1) {
result[tmp++] = n;
}
else{
binaryTree(n - 1);
result[tmp++] = n;
if (n != middle)
binaryTree(n - 1);
}
}
int main() {
int n, i;
scanf("%d",&n);
middle = n;
binaryTree(n);
for (i = 0; i < tmp; i++) {
printf("%d",result[i]);
}
for (i = tmp-2; i >=0 ; i--) {
printf("%d", result[i]);
}
printf("\n");
return 0;
} | true |
af3b49e58e78ae424fdb4c880f630b5513f3fcd4 | C++ | jrbitt/quimera | /Quimera/Atributo.h | UTF-8 | 350 | 3.375 | 3 | [] | no_license | #pragma once
template<class V>
class Atributo
{
private:
string nome;
V valor;
public:
Atributo() {
nome = "";
}
Atributo(string n, V v) {
nome = n;
valor = v;
}
~Atributo(){}
void setNome(string n) {
nome = n;
}
void setValor(V v) {
valor = v;
}
string getNome() {
return nome;
}
V getValor() {
return valor;
}
};
| true |
c5a1616c3a939f518f3039c72e441e987c23d8a3 | C++ | Jaimee007/practicas_info | /magos/casashogwarts.h | UTF-8 | 508 | 2.5625 | 3 | [] | no_license | #ifndef CASASHOGWARTS_H
#define CASASHOGWARTS_H
#include <iostream>
#include "magos.h"
using namespace std;
class CasasHogwarts
{
private:
string _nombre;
int _num_miembros;
Magos *miembros;
public:
CasasHogwarts(string nombre, int miembros);
~CasasHogwarts();
int Size();
void ReSize(int numero);
Magos &operator [] (int indice);
CasasHogwarts &operator <<(Magos &m);
friend ostream &operator <<(ostream &os, const CasasHogwarts &c);
};
#endif // CASASHOGWARTS_H
| true |
f707ad6b371b70256174b96e9f1a66198d05e4ed | C++ | mansasha21/OOP | /cache(pattern strategy)/MemoryCache.hpp | UTF-8 | 462 | 2.671875 | 3 | [
"Unlicense"
] | permissive | #pragma once
#include "BaseCache.hpp"
#include <unordered_map>
class MemoryCache final: public BaseCache
{
std::unordered_map<std::string, std::string> data_;
public:
MemoryCache() = default;
~MemoryCache() override = default;
bool has(const std::string& key) override;
std::string read(const std::string& key) override;
void write(const std::string& key, const std::string& value) override;
void erase(const std::string& key) override;
}; | true |
5978db917ad1b370c08989b706db5b34a2d08448 | C++ | MregXN/Leetcode | /BinarySearch/349.cpp | UTF-8 | 1,081 | 3.828125 | 4 | [] | no_license | // 给定两个数组,编写一个函数来计算它们的交集。
//
// 示例 1:
// 输入:nums1 = [1,2,2,1], nums2 = [2,2]
// 输出:[2]
// 示例 2:
// 输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
// 输出:[9,4]
//
// 说明:
// 输出结果中的每个元素一定是唯一的。
// 我们可以不考虑输出结果的顺序。
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_map <int,int> m;
for (auto a : nums1) m[a] = 0;
vector<int> res;
for(auto a : nums2)
{
if( m.find(a) != m.end() )
{
if(m[a] == 0)res.push_back(a);
m[a] ++;
}
}
return res;
}
};
int main(){
vector<int> nums1 = {4,9,5};
vector<int> nums2 = {9,4,9,8,4};
Solution so;
so.intersection(nums1,nums2);
return 0;
} | true |
7a97641e136b8008a735ffb05b25638e13ae3cb7 | C++ | feedliu/LeetCode | /exist.cpp | UTF-8 | 3,381 | 3.609375 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <cstring>
using std::vector;
using std::string;
struct position{
int x;
int y;
vector<int> path; // 1 : left
// 2 : top
// 3 : right
// 4 : bottom
};
bool contains(vector<vector<char>>& board, position target){
int x = target.x;
int y = target.y;
vector<int> path = target.path;
bool contain = false;
for(int i = path.size() - 1; i > -1; i --){
switch(path[i]){
case 1:
if(x - 1 == target.x && y == target.y)
contain = true;
x--;
break;
case 2:
if(x == target.x && y - 1 == target.y)
contain = true;
y--;
break;
case 3:
if(x + 1 == target.x && y == target.y)
contain = true;
x++;
break;
case 4 :
if(x == target.x && y + 1 == target.y)
contain = true;
y++;
break;
default:
break;
}
}
return contain;
}
vector<position> getPosition(vector<vector<char>>& board, string& word, int end){
vector<position> positions;
if(end < 1) {
for(int i = 0; i < board.size(); i++){
for(int j = 0; j < board[i].size(); j++){
if(board[i][j] == word[end]) positions.push_back(position{i, j, vector<int>()});
}
}
return positions;
}
vector<position> temps = getPosition(board, word, end - 1);
if(temps.size() == 0) return positions;
for(int i = 0; i < temps.size(); i++){
int x = temps[i].x;
int y = temps[i].y;
if(x > 0 && board[x - 1][y] == word[end]) {
vector<int> path = temps[i].path;
path.push_back(3);
position newPos = position{x - 1, y, path};
if(!contains(board, newPos))
positions.push_back(newPos);
}
if(x < board.size() - 1 && board[x + 1][y] == word[end]) {
vector<int> path = temps[i].path;
path.push_back(1);
position newPos = position{x + 1, y, path};
if(!contains(board, newPos))
positions.push_back(newPos);
}
if(y > 0 && board[x][y - 1] == word[end]) {
vector<int> path = temps[i].path;
path.push_back(4);
position newPos = position{x, y - 1, path};
if(!contains(board, newPos))
positions.push_back(newPos);
}
if(y < board[0].size() - 1 && board[x][y + 1] == word[end]) {
vector<int> path = temps[i].path;
path.push_back(2);
position newPos = position{x, y + 1, path};
if(!contains(board, newPos))
positions.push_back(newPos);
}
}
return positions;
}
bool exist(vector<vector<char>>& board, string word) {
vector<position> positions = getPosition(board, word, word.length() - 1);
return positions.size();
}
int main(){
vector<vector<char>> board = {{'a', 'a'}, {'a', 'a'}};
string test = "aaaaa";
bool result = exist(board, test);
std::cout << result << std::endl;
return 0;
} | true |
1168b1ff08fab876a7a6c059ee01252109ff9991 | C++ | franciscomatos/Supermarket-Distribution-Network-ASA-P1 | /main.cpp | UTF-8 | 4,694 | 2.796875 | 3 | [] | no_license | #include <vector>
#include <stdio.h>
#include <algorithm>
/*will be used for output*/
int subnetworks = 0;
int nConnections = 0;
std::vector<int> scc;
std::vector<std::vector<int> > connections;
bool sortFunction(const std::vector<int>& a, const std::vector<int>&b) {
if(a[0] == b[0])
return a[1] < b[1];
else
return a[0] < b[0];
}
bool checkForDuplicates(std::vector<int> * list, int * origin, int * item) {
int i, size = (*list).size();
for(i = 0; i < size; i++) {
if((*list)[i] == (*item)) {
return true;
}
}
return false;
}
int findScc(int item, int * rootLow) {
int i, size = scc.size();
for(i = 0; i < size; i++) {
if(rootLow[scc[i]] == rootLow[item]) return scc[i];
}
return -1;
}
void tarjanVisit(int i, std::vector<std::vector<int> > * graph, int * visited,
int * visitedVertices, int * iVisited, int * low, std::vector<int> * stack,
int * stackedVertices, int * rootLow) {
int j, size = (*graph)[i].size();
visitedVertices[i] = 1;
low[i] = *visited;
iVisited[i] = (*visited)++;
(*stack).push_back(i);
stackedVertices[i] = 1;
for(j = 0; j < size; j++) {
if(visitedVertices[(*graph)[i][j]] == 0) {
tarjanVisit((*graph)[i][j], graph, visited, visitedVertices,
iVisited, low, stack, stackedVertices, rootLow);
low[i] = std::min(low[i],low[(*graph)[i][j]]);
} else if(stackedVertices[(*graph)[i][j]] == 1) {
low[i] = std::min(low[i],iVisited[(*graph)[i][j]]);
}
if(i != (*graph)[i][j]) {
if(low[(*graph)[i][j]] != iVisited[i]) {
nConnections++;
connections[nConnections-1].push_back(i);
connections[nConnections-1].push_back((*graph)[i][j]);
}
}
}
if(low[i] == iVisited[i]) {
subnetworks++;
int n, smallest = (*stack).back();
do {
n = (*stack).back();
rootLow[n] = low[i];
if(n < smallest) smallest = n;
(*stack).pop_back();
stackedVertices[n] = 0;
} while(n != i);
scc[subnetworks-1] = smallest;
}
/*cleans the memory*/
(*graph)[i].clear();
}
void tarjan(std::vector<std::vector<int> > * graph, int * nVertices, int * rootLow) {
int visited = 0;
int * visitedVertices = new int[*nVertices]();
int * iVisited = new int[*nVertices]();
int * low = new int[*nVertices]();
int * stackedVertices = new int[*nVertices]();
std::vector<int> stack (*nVertices);
int i;
for(i = 0; i < *nVertices; i++) {
visitedVertices[i] = 0;
stackedVertices[i] = 0;
}
for(i = 0; i < *nVertices; i++) {
if(visitedVertices[i] == 0) {
tarjanVisit(i, graph, &visited, visitedVertices, iVisited,
low, &stack, stackedVertices, rootLow);
}
}
/*cleans the memory*/
delete[] visitedVertices;
delete[] iVisited;
delete[] low;
delete[] stackedVertices;
stack.clear();
}
int main() {
int nVertices, allConnections, a, b, i;
scanf("%d %d", &nVertices, &allConnections);
std::vector<std::vector<int> > connectedVertices(nVertices);
scc.resize(nVertices);
connections.resize(allConnections);
for(i = 0; i < allConnections; ++i){
scanf("%d %d", &a, &b);
connectedVertices[a-1].push_back(b-1);
}
int * rootLow = new int[nVertices]();
tarjan(&connectedVertices, &nVertices, rootLow);
scc.resize(subnetworks);
connections.resize(nConnections);
std::vector<std::vector<int> > connectionsIndexes(nVertices);
int sccOrigin, sccDestiny, size = connections.size();
for(i = 0; i < size; i++) {
sccOrigin = findScc(connections[i][0], rootLow);
sccDestiny = findScc(connections[i][1], rootLow);
if(sccOrigin != sccDestiny &&
checkForDuplicates(&(connectionsIndexes[sccOrigin]), &sccOrigin, &sccDestiny) == false) {
connectionsIndexes[sccOrigin].push_back(sccDestiny);
connections[i][0] = sccOrigin;
connections[i][1] = sccDestiny;
} else {
connections[i][0] = -1;
connections[i][1] = -1;
nConnections--;
}
}
std::sort(connections.begin(), connections.end(), sortFunction);
printf("%d\n%d\n",subnetworks,nConnections);
for(i = 0; i < size; i++) {
if(connections[i][0] != -1 && connections[i][1] != -1)
printf("%d %d\n", connections[i][0]+1, connections[i][1]+1);
}
/*cleans the memory*/
size = connectedVertices.size();
for(i = 0; i < size; i++)
connectedVertices[i].clear();
for(i = 0; i < nConnections; i++)
connections[i].clear();
for(i = 0; i < nVertices; i++)
connectionsIndexes[i].clear();
connectedVertices.clear();
scc.clear();
connections.clear();
connectionsIndexes.clear();
delete[] rootLow;
return 0;
}
| true |
b180afd509b87a9d709c551fa8691c8f8433d2cf | C++ | baactree/Algorithm | /Geometry/rotating_calipers.cpp | UTF-8 | 366 | 2.828125 | 3 | [] | no_license | double dist(point a, point b){
return hypot(a.x-b.x, a.y-b.y);
}
double calipus(const vector<point>& p){
int n = p.size();
double ret=-1;
int j=1;
for(int i=0;i<n;i++){
int ni=(i+1)%n;
while(true){
int nj=(j+1)%m;
if(ccw(hull[ni]-hull[i], hull[nj]-hull[j])<0)
j=nj;
else
break;
}
ret=max(ret, dist(hull[i], hull[j]));
}
return ret;
}
| true |
2bedfead9c476bf41c18472bc56f4bc7c301549f | C++ | DerKontrolleur/reaktionswand | /libraries/SensorNew/SensorNew.cpp | UTF-8 | 2,011 | 2.90625 | 3 | [] | no_license | #include "SensorNew.h"
Sensor::Sensor(int latchpin, int datapin, int clockpin) {
_latchpin = latchpin;
_datapin = datapin;
_clockpin = clockpin;
pinMode(_latchpin, OUTPUT);
pinMode(_clockpin, OUTPUT);
pinMode(_datapin, INPUT);
digitalWrite(_latchpin, LOW);
delayMicroseconds(5);
digitalWrite(_latchpin, HIGH);
_sensor = ShiftIn(_datapin, _clockpin);
}
byte Sensor::get() {
return _sensor;
}
byte Sensor::ShiftIn(int datapin, int clockpin) {
int i;
int temp = 0;
int pinstate;
byte datain = 0;
pinMode(clockpin, OUTPUT);
pinMode(datapin, INPUT);
for(i = 7; i >= 0; i--) {
digitalWrite(clockpin, 0);
delayMicroseconds(2);
temp = digitalRead(datapin);
if(temp) {
pinstate = 1;
datain = datain | (1 << i);
}
else {
pinstate = 0;
}
digitalWrite(clockpin, 1);
}
return datain;
}
void Sensor::set(int latchpin, int datapin, int clockpin) {
_latchpin = latchpin;
_datapin = datapin;
_clockpin = clockpin;
pinMode(_latchpin, OUTPUT);
pinMode(_clockpin, OUTPUT);
pinMode(_datapin, INPUT);
digitalWrite(_latchpin, LOW);
delayMicroseconds(5);
digitalWrite(_latchpin, HIGH);
_sensor = ShiftIn(_datapin, _clockpin);
}
int Sensor::check(int i) {
digitalWrite(_latchpin, LOW);
delayMicroseconds(5);
digitalWrite(_latchpin, HIGH);
_sensor = ShiftIn(_datapin, _clockpin);
switch(i) {
case 0:
if (_sensor&0x01) return 0;
break;
case 1:
if (_sensor&0x02) return 1;
break;
case 2:
if (_sensor&0x04) return 2;
break;
case 3:
if (_sensor&0x08) return 3;
break;
case 4:
if (_sensor&0x10) return 4;
break;
case 5:
if (_sensor&0x20) return 5;
break;
case 6:
if (_sensor&0x40) return 6;
break;
case 7:
if (_sensor&0x80) return 7;
break;
}
return -1;
delay(20);
}
void Sensor::printStatus(byte value) {
for(int i = 0; i <= 7; ++i) {
if((value >> i) & 1)
Serial.print(1);
else
Serial.print(0);
}
}
void Sensor::print() {
}
| true |
35419cd17023e1c283cf05b3fc81d25b7044b3fd | C++ | XeCycle/cxxtest | /uncaught-destruct-static.cc | UTF-8 | 300 | 3.015625 | 3 | [] | no_license | #include <iostream>
struct print_on_destruct {
~print_on_destruct()
{
std::cout << "destructed\n";
}
};
void fn()
{
static print_on_destruct a;
(void)a;
}
int main()
{
try {
print_on_destruct stack_var;
fn();
throw 1;
} catch(...) {
return 1;
}
return 0;
}
| true |
8b149323ee5631b71a6e0507b344bbb6ba5f4d31 | C++ | tonyli00000/Competition-Code | /UVA Online Judge/10763/10763/10763.cpp | UTF-8 | 656 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <math.h>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <functional>
using namespace std;
int min(int x, int y) {
if (x < y)return x;
else return y;
}
int max(int x, int y) {
if (x > y)return x;
else return y;
}
int main()
{
long n,i,j,k;
while (cin >> n && n != 0) {
map<pair<int, int>, int> p;
for (i = 0; i < n; i++) {
int x, y;
cin >> x >> y;
pair<int, int> l(min(x,y),max(x,y));
int a = ++p[l];
if (a == 2)p.erase(l);
}
if (p.empty())cout << "YES\n";
else cout << "NO\n";
}
return 0;
}
| true |
10c506df0eb076e8a8820c4c885b1829b7cb2193 | C++ | rafael-radkowski/setforge | /src/Model3D.h | UTF-8 | 2,085 | 3 | 3 | [
"MIT"
] | permissive | #pragma once
/*
class Model3D
This class implements a simple model renderer with the sole purpose to show the object in a window.
It links the shader code with the geometry with a default light source and calls the draw function.
Features:
- Loads an obj file and renders it.
- Links a shader program to the obj geometry.
- Adds a default light source, attaches this light source to the camera (viewmatrix) and points it towards
the 3D model
Usage:
renderer = new Model3D();
renderer->create("path to model");
Use 'draw()' to only draw the model.
Note that an OpenGL window context must be ready.
Rafael Radkowski
Iowa State University
rafael@iastate.edu
+1 (515) 294 7044
Feb 19, 2019
All copyrights reserved
--------------------------------------------------------------------------
last edited:
*/
// stl
#include <iostream>
#include <vector>
#include <string>
// GLM include files
#define GLM_FORCE_INLINE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp> // transformation
#include <glm/gtx/quaternion.hpp> // quaternions
// local
#include "ModelOBJ.h"
#include "ShaderProgram.h"
#include "CommonTypes.h"
#include "ModelCoordinateSystem.h"
using namespace std;
class Model3D {
public:
/*
Constructor
*/
Model3D();
~Model3D();
/*
Create the model instance.
@param path_and_file - string containg the relative or absolute path to the model.
@return - true, if model was successfully loaded.
*/
bool create(string path_and_file);
/*
Draw the model
@param vm - a glm 4x4 view matrix
*/
bool draw(glm::mat4& vm);
private:
// members
// the model to render
cs557::OBJModel* _obj_model;
glm::mat4 _projectionMatrix;
glm::mat4 _viewMatrix;
glm::mat4 _modelMatrix;
// The light source
cs557::LightSource _light0;
cs557::LightSource _light1;
cs557::LightSource _light2;
// Material
cs557::Material _mat0;
// a corodinate system
cs557::CoordinateSystem _coordinateSystem;
glm::mat4 _modelMatrixCoordSystem; // for the coordinate system
}; | true |
dafef7fb9d6e8e855b35a8e5c0db21b42c49f672 | C++ | dd-harp/MASH | /macro/src/flux_movement/flux_movement.h | UTF-8 | 2,724 | 2.703125 | 3 | [] | no_license | #ifndef SRC_MARKOV_FLOW_H
#define SRC_MARKOV_FLOW_H
#include <exception>
#include <map>
#include <sstream>
#include <vector>
#include <variant>
#include "armadillo"
#include "boost/random/binomial_distribution.hpp"
#include "boost/random/mersenne_twister.hpp"
#include "boost/random/uniform_real_distribution.hpp"
namespace dd_harp {
using patch_id = int;
using human_id = int;
using clock_time = double;
using movement_sequence = std::vector<std::tuple<patch_id,clock_time>>;
using patch_sequence = std::vector<std::tuple<human_id, bool, clock_time>>;
// This type is a sentinel that a variant has not been set.
struct no_parameter {};
using flux_movement_parameter = std::variant<no_parameter, int, double, arma::Mat<double>>;
class flux_movement; // Forward declaration for friending.
class flux_movement_result {
public:
patch_id starting_patch(human_id query) const;
size_t human_count() const;
/*!
* For the human, the movement sequence will be a
* set of events with predetermined times.
*
* @param query - Which human's movements we want.
* @return movement_sequence - The set of patches and times.
*/
movement_sequence
movements_of_human(human_id query) const;
patch_sequence
duration_in_patch(patch_id query) const;
void allocate(human_id human_count, patch_id patch_count);
//! Remove events without resizing the event queue storage.
void clear();
friend class flux_movement;
private:
std::vector<movement_sequence> human_location;
std::vector<patch_sequence> patch_state;
};
/*! Markovian movement of individuals.
*
* Individuals have ids and are assigned to patches.
* Each patch specifies the rate of movement to other patches.
* The rate for an individual to leave a patch is the sum of
* the rates to all other patches. The rate for any individual
* to leave is that times the number of people in the patch.
*/
class flux_movement {
// The result is a buffer that is owned by the machine,
// so that it won't churn memory. It is read-only to others.
flux_movement_result result;
public:
void init(
const std::map<std::string, flux_movement_parameter>& parameters,
const std::vector<std::vector<int>>& initial_state
);
const flux_movement_result*
step(double time_step);
private:
bool initialized{false};
boost::mt19937 rng;
arma::Mat<double> flow_cumulant;
arma::umat flow_index;
arma::Col<double> patch_rate_with_people;
arma::uvec patch_index;
double total_rate;
int patch_count;
int human_count;
std::vector<std::vector<int>> human_location;
};
} // namespace dd_harp
#endif //SRC_MARKOV_FLOW_H
| true |
7351366761eda6eedd91f888d621337d538465db | C++ | pv-912/Programming | /C++ Files/Previous/DP/binomial.cpp | UTF-8 | 343 | 2.796875 | 3 | [] | no_license | #include<iostream>
using namespace std;
void solve(){
int n,k;
cin>>n>>k;
int arr[n+1][k+1];
for(int i=0; i<=n; i++){
for(int j= 0; j<=min(i,k); j++){
if(j==0 || j==i)
arr[i][j] = 1;
else
arr[i][j] = arr[i-1][j] + arr[i-1][j-1];
}
}
cout<<arr[n][k]<<endl;
}
int main(){
int t;
cin>>t;
while(t--){
solve();
}
} | true |
c0059ee7150efa4cf623ae8efccabb64a8a363ac | C++ | Stef4nio/Markov-Normal-Algorithm | /SubstitutionManager.cpp | UTF-8 | 1,629 | 2.984375 | 3 | [] | no_license | //
// Created by stef4 on 2/2/2020.
//
#include "SubstitutionManager.h"
#include "Substitution.h"
#include <iostream>
void SubstitutionManager::PushSubstitutionToList(Substitution substitution)
{
if(!isInitialized)
{
_lastElement->Data = substitution;
isInitialized = true;
return;
}
Node<Substitution>* currNode = NodeFactory::CreateNode<Substitution>();
currNode->Data = substitution;
_lastElement->NextNode = currNode;
_lastElement = currNode;
}
void SubstitutionManager::AddSubstitution(char *findStr, char *replaceStr, bool isFinish)
{
Substitution currSubstitution = Substitution(findStr,replaceStr,isFinish);
PushSubstitutionToList(currSubstitution);
}
void SubstitutionManager::AddSubstitution(char *initStr)
{
Substitution currSubstitution = Substitution(initStr);
PushSubstitutionToList(currSubstitution);
}
void SubstitutionManager::ProcessString(StringList* string)
{
//bool isChanged = false;
Node<Substitution>* listCopy = _substitutionList;
while(listCopy!= nullptr)
{
Substitution currSubstitution = listCopy->Data;
if((*string).FindAndReplace(currSubstitution.FindString,currSubstitution.ReplaceString))
{
std::cout<<string->GetString()<<std::endl;
//isChanged = true;
if(currSubstitution.IsFinishing)
{
break;
}
listCopy = _substitutionList;
}
listCopy = listCopy->NextNode;
/*if(listCopy == nullptr && isChanged)
{
listCopy = _substitutionList;
}*/
}
} | true |
d633c5a5d8c3b06e09aa87f1a245e92ef291bf3c | C++ | FeilongHou/Autonomous-Robot | /ROBOTCODE-2.ino | UTF-8 | 32,336 | 2.671875 | 3 | [] | no_license |
bool RedDrop = false;
bool BlueDrop = false;
bool GreenDrop = false;
bool YellowDrop = false;
bool inHallway = true ;
bool inRoom = false;
bool room1Complete = false;
bool room2Complete = false;
bool room3Complete = false;
bool room4Complete = false;
bool room1Enter = false;
bool room2Enter = false;
bool room3Enter = false;
bool room4Enter = false;
bool room1Exit = false;
bool room2Exit = false;
bool room3Exit = false;
bool room4Exit = false;
int roomID = 0;
int currentRoom;
#include <Servo.h> // servo library
Servo servo1; // servo control object
//360 servo setup
#include <NewPing.h> //include NewPing library
#include <Servo.h> //include Servo library
int RForward = 0;
int RBackward =180 ;
int LForward = 0;
int LBackward = 180;
int BForward = 0;
int BBackward = 180;
int RNeutral = 90;
int LNeutral = 90;
int BNeutral = 90;//constants for motor full speed
int RForwardS = 87;
int RBackwardS =93 ;
int LForwardS = 87;
int LBackwardS = 93;
int BForwardS = 87;
int BBackwardS = 93;
int RForwardM = 86;
int RBackwardM =94 ;
int LForwardM = 86;
int LBackwardM = 94;
int BForwardM = 86;
int BBackwardM = 94;
int RNeutralS = 90;
int LNeutralS = 90;
int BNeutralS = 90;//constants SLOW motor speed
Servo leftMotor;
Servo rightMotor;
Servo backMotor; //declare motors
// sonar setup
long durationF;
long durationL;
long durationR; //time it takes to recieve PING signal
//operational setup
const int dangerThresh = 7; //threshold for obstacles (in cm)
const int sideDangerThresh = 11 ;
int distanceF, distanceR, distanceL; //distances on either side
// color sensor setup
#include <Wire.h>
#include <Math.h>
byte i2cWriteBuffer[10];
byte i2cReadBuffer[10];
#define SensorAddressWrite 0x29 //
#define SensorAddressRead 0x29 //
#define EnableAddress 0xa0 // register address + command bits
#define ATimeAddress 0xa1 // register address + command bits
#define WTimeAddress 0xa3 // register address + command bits
#define ConfigAddress 0xad // register address + command bits
#define ControlAddress 0xaf // register address + command bits
#define IDAddress 0xb2 // register address + command bits
#define ColorAddress 0xb4 // register address + command bits
unsigned int clear_color = 0;
unsigned int red_color = 0;
unsigned int green_color = 0;
unsigned int blue_color = 0;
void setup()
{
displayColorCodes();
//set push rod back to load hopper
int position;
for(position = 300; position >0 ; position -= 2)
{
servo1.write(position); // Move to next position
delay(20); // Short pause to allow it to move
}
//360 servo setup
Serial.begin(9600);
rightMotor.attach(10);
leftMotor.attach(12);
backMotor.attach(11);
//color sensor setup
Wire.begin();
Serial.begin(9600); // start serial for output
init_TCS34725();
get_TCS34725ID();
// 180 Servo Setup
servo1.attach(13, 900, 2100); //(pin,min pulse,max pulse)
currentRoom = 0;
robotStop();
delay(5000);
getToYellow();
}
void loop()
//////////////////////////////////////////////////MAIN OPERATIONS LOOP//////////////////////////////////////////////////////////////////////////////////////
{
working();
} //end of loop
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//*************************************************************FUNCTIONS****************************************************************************************
///////////////////ROBOT MOTION FUNCTIONS///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void robotLeft()
{
leftMotor.write(LForward);
rightMotor.write(RForward);
backMotor.write(BForward);//turn left
}
void robotRight()
{
leftMotor.write(LBackward);
rightMotor.write(RBackward);
backMotor.write(BBackward);//turn right
}
void robotDriftLeft()
{
leftMotor.write(LNeutral); // drift left
rightMotor.write(RForward);
backMotor.write(BNeutral);
}
void robotDriftRight()
{
leftMotor.write(LBackward); // drift right
rightMotor.write(RNeutral);
backMotor.write(BNeutral);
}
void robotStop()
{
leftMotor.write(LNeutral); // stop robot
rightMotor.write(RNeutral);
backMotor.write(BNeutral);
}
void robotForward()
{
leftMotor.write(LBackward); // forward
rightMotor.write(RForward);
backMotor.write(BNeutral);
}
void robotSForward()
{
leftMotor.write(LBackwardS); // forward
rightMotor.write(RForwardS);
backMotor.write(BNeutralS);
}
void robotForwardM()
{
leftMotor.write(LBackwardM); // forward
rightMotor.write(RForwardM);
backMotor.write(BNeutral);
}
void robotSBackward()
{
leftMotor.write(LForwardS); // backward slow
rightMotor.write(RBackwardS);
backMotor.write(BNeutralS);
}
void robotBackward()
{
leftMotor.write(LForward); // backward
rightMotor.write(RBackward);
backMotor.write(BNeutral);
}
void pivotForward()
{
driftRight();
delay(1500);
driftLeft();
delay(1500);
}
void driftLeft()
{
leftMotor.write(LBackward);
rightMotor.write(RForwardS);
backMotor.write(BNeutralS);
}
void driftRight()
{
leftMotor.write(LBackwardS);
rightMotor.write(RForward);
backMotor.write(BNeutralS);
}
/////////////////////////////SONAR FUNCTIONS//////////////////////////////////////////////////////////////////////////////////////////////
long showDistance()
{
Serial.print("DistanceF: ");
Serial.print(distanceF);
Serial.print(" \tDistanceR: ");
Serial.print(distanceR);
Serial.print(" \tDistanceL: ");
Serial.println(distanceL);
}
long pingF()
{
const int trigPinF = 3;
const int echoPinF = 2; //set up pins
pinMode(trigPinF, OUTPUT);
digitalWrite(trigPinF, LOW);
delayMicroseconds(2);
digitalWrite(trigPinF, HIGH);
delayMicroseconds(5);
digitalWrite(trigPinF, LOW);
//Get duration it takes to receive echo
pinMode(echoPinF, INPUT);
durationF = pulseIn(echoPinF, HIGH);
//Convert duration into distance
return (durationF / 29 / 2);
}
long pingL()
{
const int trigPinL = 5;
const int echoPinL = 4; //set up pins
pinMode(trigPinL, OUTPUT);
digitalWrite(trigPinL, LOW);
delayMicroseconds(2);
digitalWrite(trigPinL, HIGH);
delayMicroseconds(5);
digitalWrite(trigPinL, LOW);
pinMode(echoPinL, INPUT); //Get duration it takes to receive echo
durationL = pulseIn(echoPinL, HIGH);
return (durationL / 29 / 2); //Convert duration into distance
}
long pingR()
{
const int trigPinR = 7;
const int echoPinR = 6; //set up pins
pinMode(trigPinR, OUTPUT);
digitalWrite(trigPinR, LOW);
delayMicroseconds(2);
digitalWrite(trigPinR, HIGH);
delayMicroseconds(5);
digitalWrite(trigPinR, LOW);
pinMode(echoPinR, INPUT); //Get duration it takes to receive echo
durationR = pulseIn(echoPinR, HIGH);
return (durationR / 29 / 2); //Convert duration into distance
}
void getDistance()
{
distanceF = pingF();
distanceL = pingL();
distanceR = pingR();
showDistance();
}
//////////////////////////COLOR SENSOR CODE///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void displayColorCodes()
{
Serial.print("clear color="); // shows value number for each color value
Serial.print(clear_color, DEC);
Serial.print(" red color=");
Serial.print(red_color, DEC);
Serial.print(" green color=");
Serial.print(green_color, DEC);
Serial.print(" blue color=");
Serial.println(blue_color, DEC);
}
void Writei2cRegisters(byte numberbytes, byte command)
{
byte i = 0;
Wire.beginTransmission(SensorAddressWrite); // Send address with Write bit set
Wire.write(command); // Send command, normally the register address
for (i=0;i<numberbytes;i++) // Send data
{
Wire.write(i2cWriteBuffer[i]);
Wire.endTransmission();
delayMicroseconds(100); // allow some time for bus to settle
}
}
byte Readi2cRegisters(int numberbytes, byte command)
{
byte i = 0;
Wire.beginTransmission(SensorAddressWrite); // Write address of read to sensor
Wire.write(command);
Wire.endTransmission();
delayMicroseconds(100); // allow some time for bus to settle
Wire.requestFrom(SensorAddressRead,numberbytes); // read data
for(i=0;i<numberbytes;i++)
{
i2cReadBuffer[i] = Wire.read();
Wire.endTransmission();
delayMicroseconds(100); // allow some time for bus to settle
}
}
void init_TCS34725(void)
{
i2cWriteBuffer[0] = 0x10;
Writei2cRegisters(1,ATimeAddress); // RGBC timing is 256 - contents x 2.4mS =
i2cWriteBuffer[0] = 0x00;
Writei2cRegisters(1,ConfigAddress); // Can be used to change the wait time
i2cWriteBuffer[0] = 0x00;
Writei2cRegisters(1,ControlAddress); // RGBC gain control
i2cWriteBuffer[0] = 0x03;
Writei2cRegisters(1,EnableAddress); // enable ADs and oscillator for sensor
}
void get_TCS34725ID(void)
{
Readi2cRegisters(1,IDAddress);
if (i2cReadBuffer[0] = 0x44)
{
Serial.println("TCS34725 is present");
}
else
{
Serial.println("TCS34725 not responding");
}
}
void get_Colors(void)
{
Readi2cRegisters(8,ColorAddress);
readColorValues();
// yellowTape Detector
if(clear_color >= 6000&& clear_color <= 8841 && red_color >= 2138 && red_color <= 3906 && green_color >= 1819 && green_color <= 3376 && blue_color >= 797 && blue_color <= 1546)
{
Serial.print ("on YellowTape ");
roomID = 4;
}
//greenTape Detector
if(clear_color >= 1025&& clear_color <= 2192 && red_color >= 278 && red_color <= 482 && green_color >= 360 && green_color <= 517 && blue_color >= 272 && blue_color <= 426)
{
Serial.print ("on GreenTape ");
roomID = 3;
}
//whiteTape detector
if(red_color >= 1000 && green_color >= 1000 && blue_color >= 1000)
{
Serial.print ("on WhiteTape ");
}
//redTapeDetector
if(clear_color >= 1800 && clear_color <= 3500 && red_color >= 1000 && red_color <= 2500 && green_color >= 325 && green_color <= 750 && blue_color >= 300 && blue_color <= 650)
{
Serial.print ("on RedTape ");
roomID = 1;
}
//blueTapeDetector
if(clear_color >= 1691&& clear_color <= 2126 && red_color >= 360 && red_color <= 566 && green_color >= 474 && green_color <= 696 && blue_color >= 746 && blue_color <= 986)
{
Serial.print ("on BlueTape ");
roomID = 2;
}
//blackFloorDerector
if(clear_color >= 0 && clear_color <= 1000 && red_color >= 0 && red_color <= 500 && green_color >= 0 && green_color <= 500 && blue_color >= 0 && blue_color <= 500)
{
Serial.print ("on Black Floor ");
}
// target detector
if(clear_color >= 1 && clear_color <= 12000 && red_color >= 3000 && red_color <= 5000 && green_color >= 1300 && green_color <= 3000 && blue_color >= 600 && blue_color <= 2000)
{
Serial.print (" on target ");
}
else
{
Serial.print ("not on target ");
}
displayColorCodes();
Serial.println(roomID);
Serial.print( "= room ID");
Serial.println(currentRoom);
Serial.print( "= current room");
}
void readColorValues()
{
clear_color = (unsigned int)(i2cReadBuffer[1]<<8) + (unsigned int)i2cReadBuffer[0]; //******** these variables needed to be declared in loop before using if statement
red_color = (unsigned int)(i2cReadBuffer[3]<<8) + (unsigned int)i2cReadBuffer[2];
green_color = (unsigned int)(i2cReadBuffer[5]<<8) + (unsigned int)i2cReadBuffer[4];
blue_color = (unsigned int)(i2cReadBuffer[7]<<8) + (unsigned int)i2cReadBuffer[6];
}
///////////////////////////////////////OPERATIONAL FUNCTIONS///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void stayInRoom() // robot goes into slow mode to pick up colors better
{
inRoom = true;
inHallway = false;
get_Colors();
if ( (2000 > clear_color && red_color > blue_color && red_color > 1000 && currentRoom ==1)||(7000 > clear_color && blue_color > red_color && blue_color > 1000 && currentRoom ==2)||( clear_color >= 1025&& clear_color <= 2192 && red_color >= 278 && red_color <= 482 && green_color >= 360 && green_color <= 517 && blue_color >= 272 && blue_color <= 426 && currentRoom == 3)||(
clear_color >= 4906&& clear_color <= 8841 && red_color >= 2138 && red_color <= 3906 && green_color >= 1819 && green_color <= 3376 && blue_color >= 797 && blue_color <= 1546&& currentRoom == 4))//sees color tape ture around
{
robotStop(); //stop reverse turn 90 degrees(stay in room)
delay(500);
robotBackward();
delay(1000);
distanceL = pingL();
distanceR = pingR();
if (distanceL>distanceR) //if left is less obstructed
{
leftMotor.write(LForward);
rightMotor.write(RForward);
backMotor.write(BForward);//turn left
delay(2000);
Serial.print("right obstruction");
robotStop();
delay (500);
}
else if (distanceR>distanceL) //if right is less obstructed
{
leftMotor.write(LBackward);
rightMotor.write(RBackward);
backMotor.write(BBackward);//turn right
delay(2000);
robotStop();
delay(500);
Serial.print("Left obstruction");
}
else //if they are equally obstructed
{
leftMotor.write(LForward);
rightMotor.write(RForward);
backMotor.write(BForward);//turn 180 degrees
delay(2000);
Serial.print("equal onstruction");
}
get_Colors();
stayInRoom();
}
else if (clear_color >= 1 && clear_color <= 12000 && red_color >= 3000 && red_color <= 5000 && green_color >= 1300 && green_color <= 3000 && blue_color >= 600 && blue_color <= 2000)//on target
{
pillDrop();
}
else if(inRoom == true)
{
slowAvoidWalls();
get_Colors();
Serial.println("/////////////////STAY IN ROOM////////////////////");
stayInRoom();
}
}
void avoidWalls()
{
distanceF = pingF();
distanceR = pingR();
distanceL = pingL();
if(distanceL > dangerThresh && distanceR > dangerThresh)
{
forwardScan();
get_Colors();
}
else if (distanceL < sideDangerThresh && distanceR > sideDangerThresh)
{
leftMotor.write(LBackward); // drift right away from wall
rightMotor.write(RNeutral);
backMotor.write(BNeutral);
Serial.print(" avoiding left wall ");
}
else if (distanceL > sideDangerThresh && distanceR < sideDangerThresh)
{
leftMotor.write(LNeutral); // drift left away from wall
rightMotor.write(RForward);
backMotor.write(BNeutral);
Serial.print(" avoiding right wall ");
}
else
{
leftMotor.write(LForward); // full reverse
rightMotor.write(RBackward);
backMotor.write(BNeutral);
delay(500);
compareDistance();
Serial.print(" avoiding both walls ");
}
}
void pillDrop()
{
int position;
leftMotor.write(LNeutral); // stop robot
rightMotor.write(RNeutral);
backMotor.write(BNeutral);
Serial.println ("///////////PILL DROP////////////");
int i;
for(i=0; i<1; i++)
{
for(position = 300; position >0 ; position -= 2)
{
servo1.write(position); // Move to next position
delay(20); // Short pause to allow it to move
}
}
dropFlagSelect();
distanceL = pingL();
distanceR = pingR();
if (distanceL>distanceR) //if left is less obstructed
{
robotLeft();
delay(2000);
robotStop();
delay(500);
leftMotor.write(LNeutral);
rightMotor.write(RForward);
backMotor.write(BBackward);//diagonal left
delay(1000);
Serial.print("right obstruction");
robotStop();
delay (500);
}
else if (distanceR>distanceL) //if right is less obstructed
{
robotRight();
delay(2000);
robotStop();
delay(500);
leftMotor.write(LBackward);
rightMotor.write(RNeutral);
backMotor.write(BForward);//diagonal right
delay(1000);
robotStop();
delay(500);
Serial.print("Left obstruction");
}
else //if they are equally obstructed
{
leftMotor.write(LForward);
rightMotor.write(RForward);
backMotor.write(BForward);//turn 180 degrees
delay(1000);
Serial.print("equal onstruction");
}
leaveRoom();
}
void forwardScan()
{
distanceF = pingF();
if (distanceF>dangerThresh) //if path is clear
{
robotForward();
Serial.print(" clear path ");
}
else //if path is blocked
{
robotStop();
delay(1000);
compareDistance();
Serial.print(" obstruction front ");
}
distanceL = pingL();
distanceR = pingR();
}
void compareDistance()
{
distanceL = pingL();
distanceR = pingR();
if (distanceL>distanceR) //if left is less obstructed
{
leftMotor.write(LForward);
rightMotor.write(RForward);
backMotor.write(BForward);//turn left
delay(800);
Serial.print("right obstruction");
robotStop();
delay (500);
}
else if (distanceR>distanceL) //if right is less obstructed
{
leftMotor.write(LBackward);
rightMotor.write(RBackward);
backMotor.write(BBackward);//turn right
delay(800);
robotStop();
delay(500);
Serial.print("Left obstruction");
}
else //if they are equally obstructed
{
leftMotor.write(LForward);
rightMotor.write(RForward);
backMotor.write(BForward);//turn 180 degrees
delay(2000);
Serial.print("equal onstruction");
}
}
void slowForwardScan()
{
distanceF = pingF();
if (distanceF>dangerThresh) //if path is clear
{
robotSForward();
Serial.print(" clear path ");
}
else //if path is blocked
{
leftMotor.write(LNeutral);
rightMotor.write(RNeutral);
backMotor.write(BNeutral);
delay(1000);
compareDistance();
Serial.print(" obstruction front ");
}
distanceL = pingL();
distanceR = pingR();
}
void slowAvoidWalls()
{
distanceF = pingF();
distanceR = pingR();
distanceL = pingL();
if(distanceL > dangerThresh && distanceR > dangerThresh)
{
slowForwardScan();
}
else if (distanceL < sideDangerThresh && distanceR > sideDangerThresh)
{
leftMotor.write(LBackwardS); // drift right away from wall
rightMotor.write(RNeutralS);
backMotor.write(BNeutralS);
Serial.print(" avoiding left wall ");
}
else if (distanceL > sideDangerThresh && distanceR < sideDangerThresh)
{
leftMotor.write(LNeutralS); // drift left away from wall
rightMotor.write(RForwardS);
backMotor.write(BNeutralS);
Serial.print(" avoiding right wall ");
}
else
{
leftMotor.write(LForwardS); // full reverse
rightMotor.write(RBackwardS);
backMotor.write(BNeutralS);
leftMotor.write(LForward);
rightMotor.write(RForward);
backMotor.write(BForward);//turn 90 degrees
delay(1200);
Serial.print(" avoiding both walls ");
}
}
void leaveRoom() //after dropping pill seach for exit of room and do not perform any other actions
{
displayColorCodes();
if((2000 > clear_color && red_color > blue_color && red_color > 1000 && currentRoom ==1)||(7000 > clear_color && blue_color > red_color && blue_color > 1000 && currentRoom ==2)||( clear_color >= 1025&& clear_color <= 2192 && red_color >= 278 && red_color <= 482 && green_color >= 360 && green_color <= 517 && blue_color >= 272 && blue_color <= 426 && currentRoom == 3)||(
clear_color >= 4906&& clear_color <= 8841 && red_color >= 2138 && red_color <= 3906 && green_color >= 1819 && green_color <= 3376 && blue_color >= 797 && blue_color <= 1546&& currentRoom == 4))
{
exitRoom();
}
else
{
slowAvoidWalls();
get_Colors();
Serial.println(" ///////////////////////leave/////////////// ");
leaveRoom();
}
}
void exitRoom()
{
robotStop();
delay(500);
robotForward();
delay(500);
Serial.println("****************************************************************************************************************EXIT");
inHallway = true;
inRoom = false;
roomID = 0;
currentRoom = 0;
exitFlagSelect();
robotForward();
delay(1000);
get_Colors();
working();
}
void working()
{
get_Colors();
if(inHallway == true && RedDrop == false && roomID == 1 || inHallway == true && BlueDrop == false && roomID == 2 || inHallway == true && GreenDrop == false && roomID == 3|| inHallway == true && YellowDrop == false && roomID == 4)
{
get_Colors();
enterFlagSelect();
robotForward();
delay(1000);
stayInRoom();
}
else if( (inHallway == true && room1Exit == true && roomID == 1) || (inHallway == true && room2Exit == true && roomID == 2) || (inHallway == true && room3Exit == true && roomID == 3)|| (inHallway == true && room4Exit == true && roomID == 4))
{
robotStop(); //stop reverse turn 90 degrees(stay in room)
delay(500);
Serial.println("NOT THAT ROOM!!!");
robotBackward();
delay(2000);
compareDistance();
get_Colors();
roomID=0;
working();
}
else if (inHallway == true)
{
hallwayMode();
working();
}
}
void hallwayMode()
{
stopOnWhite();
get_Colors();
displayFlags();
Serial.println ("####################################HALWAY###########################################");
}
/////////////////////////////////////////////////////////////////////////FLAGS///////////////////////////////////////////////////////////////////////////
void dropFlagSelect()
{
if(room1Enter == true)
{
RedDrop = true;
Serial.println("REDDROP = TRUE");
currentRoom == 1;
}
if(room2Enter == true)
{
BlueDrop = true;
Serial.println("BLUEDROP = TRUE");
currentRoom =2;
}
if (room3Enter == true)
{
GreenDrop = true;
Serial.println("GREENDROP = TRUE");
currentRoom = 3;
}
if (room4Enter == true)
{
YellowDrop = true;
Serial.println("YELLOWDROP = TRUE");
currentRoom =4;
}
}
void enterFlagSelect()
{
if(roomID == 1)
{
room1Enter = true;
Serial.println("ROOM1ENTER = TRUE");
currentRoom = 1;
}
if(roomID == 2)
{
room2Enter = true;
Serial.println("ROOM2ENTER = TRUE");
currentRoom = 2;
}
if (roomID == 3)
{
room3Enter = true;
Serial.println("ROOM3ENTER = TRUE");
currentRoom = 3;
}
if (roomID == 4)
{
room4Enter = true;
Serial.println("ROOM4ENTER = TRUE");
currentRoom = 4;
}
}
void exitFlagSelect()
{
if (room1Enter == true && RedDrop == true)
{
room1Exit = true;
Serial.println("ROOM1EXIT = TRUE");
}
if (room2Enter == true && BlueDrop == true)
{
room2Exit = true;
Serial.println("ROOM2EXIT = TRUE");
}
if (room3Enter == true && GreenDrop == true )
{
room3Exit = true;
Serial.println("ROOM3EXIT = TRUE");
}
if (room4Enter == true && YellowDrop == true)
{
room4Exit = true;
Serial.println("ROOM4EXIT = TRUE");
}
}
void displayFlags()
{
if (room1Exit == true)//red
{
Serial.println("room 1 complete");
}
else if (room1Exit == false)
{
Serial.println("room 1 incomplete");
}
if (room2Exit == true)//blue
{
Serial.println("room 2 complete");
}
else if (room2Exit == false)
{
Serial.println("room 2 incomplete");
}
if (room3Exit == true)//green
{
Serial.println("room 3 complete");
}
else if(room3Exit == false)
{
Serial.println("room 3 incomplete");
}
if (room4Exit == true)//yellow
{
Serial.println("room 4 complete");
}
else if(room4Exit == false)
{
Serial.println("room 4 incomplete");
}
}
void midAvoidWalls()
{
distanceF = pingF();
distanceR = pingR();
distanceL = pingL();
if(distanceL > dangerThresh && distanceR > dangerThresh)
{
midForwardScan();
}
else if (distanceL < sideDangerThresh && distanceR > sideDangerThresh)
{
leftMotor.write(LBackwardM); // drift right away from wall
rightMotor.write(RNeutralS);
backMotor.write(BNeutralS);
Serial.print(" avoiding left wall ");
}
else if (distanceL > sideDangerThresh && distanceR < sideDangerThresh)
{
leftMotor.write(LNeutralS); // drift left away from wall
rightMotor.write(RForwardM);
backMotor.write(BNeutralS);
Serial.print(" avoiding right wall ");
}
else
{
leftMotor.write(LForwardM); // full reverse
rightMotor.write(RBackwardM);
backMotor.write(BNeutralS);
leftMotor.write(LForward);
rightMotor.write(RForward);
backMotor.write(BForward);//turn 90 degrees
delay(1200);
Serial.print(" avoiding both walls ");
}
}
void midForwardScan()
{
distanceF = pingF();
if (distanceF>dangerThresh) //if path is clear
{
robotForwardM();
Serial.print(" clear path ");
}
else //if path is blocked
{
robotStop();
delay(1000);
compareDistance();
Serial.print(" obstruction front ");
}
distanceL = pingL();
distanceR = pingR();
}
void stopOnWhite() // robot goes into slow mode to pick up colors better
{
if (red_color >= 1000 && green_color >= 1000 && blue_color >= 1000)//on white tape
{
robotStop();
delay(1000);
readTape();
colorCheck();
}
else
{
midAvoidWalls();
}
}
void colorCheck()
{
if(clear_color >= 0 && clear_color <= 1000 && red_color >= 0 && red_color <= 500 && green_color >= 0 && green_color <= 500 && blue_color >= 0 && blue_color <= 500)//on black
{
jumpBackward();
}
else if (red_color >= 1000 && green_color >= 1000 && blue_color >= 1000)//on white tape
{
jumpForward();
}
else if((clear_color >= 1800 && clear_color <= 3500 && red_color >= 1000 && red_color <= 2500 && green_color >= 325 && green_color <= 750 && blue_color >= 300 && blue_color <= 650)|| (clear_color >= 1691&& clear_color <= 2126 && red_color >= 360 && red_color <= 566 && green_color >= 474 && green_color <= 696 && blue_color >= 746 && blue_color <= 986)|| (clear_color >= 4906&& clear_color <= 8841 && red_color >= 2138 && red_color <= 3906 && green_color >= 1819 && green_color <= 3376 && blue_color >= 797 && blue_color <= 1546)|| (clear_color >= 1025&& clear_color <= 2192 && red_color >= 278 && red_color <= 482 && green_color >= 350 && green_color <= 517 && blue_color >= 272 && blue_color <= 426))
{
get_Colors();
working();
}
else
{
robotBackward();
delay(1000);
stopOnWhite();
}
}
void jumpBackward()
{
int i;
for(i=0; i<=5; i++)
{
if((clear_color >= 1800 && clear_color <= 3500 && red_color >= 1000 && red_color <= 2500 && green_color >= 325 && green_color <= 750 && blue_color >= 300 && blue_color <= 650)|| (clear_color >= 1691&& clear_color <= 2126 && red_color >= 360 && red_color <= 566 && green_color >= 474 && green_color <= 696 && blue_color >= 746 && blue_color <= 986)|| (clear_color >= 4906&& clear_color <= 8841 && red_color >= 2138 && red_color <= 3906 && green_color >= 1819 && green_color <= 3376 && blue_color >= 797 && blue_color <= 1546)|| (clear_color >= 1025&& clear_color <= 2192 && red_color >= 278 && red_color <= 482 && green_color >= 350 && green_color <= 517 && blue_color >= 272 && blue_color <= 426))
{
get_Colors();
working();
}
else
{
robotBackward();
delay(100);
robotStop();
delay(500);
readTape();
}
}
robotStop();
delay(500);
stopOnWhite();
}
void jumpForward()
{
int i;
for(i=0; i<=5; i++)
{
if((clear_color >= 1800 && clear_color <= 3500 && red_color >= 1000 && red_color <= 2500 && green_color >= 325 && green_color <= 750 && blue_color >= 300 && blue_color <= 650)|| (clear_color >= 1691&& clear_color <= 2126 && red_color >= 360 && red_color <= 566 && green_color >= 474 && green_color <= 696 && blue_color >= 746 && blue_color <= 986)|| (clear_color >= 4906&& clear_color <= 8841 && red_color >= 2138 && red_color <= 3906 && green_color >= 1819 && green_color <= 3376 && blue_color >= 797 && blue_color <= 1546)|| (clear_color >= 1025&& clear_color <= 2192 && red_color >= 278 && red_color <= 482 && green_color >= 350 && green_color <= 517 && blue_color >= 272 && blue_color <= 426))
{
get_Colors();
working();
}
else
{
robotForward();
delay(100);
robotStop();
delay(500);
readTape();
}
}
robotStop();
delay(500);
robotBackward();
delay(600);
robotStop();
delay(500);
stopOnWhite();
}
void readTape()
{
Serial.println("reading tape");
get_Colors();
get_Colors();
get_Colors();
get_Colors();
get_Colors();
}
void safeNav()
{
long unsigned int time = millis;
if(time <= 3000)
{
robotForward;
Serial.println(time);
}
else if (time >= 3000 && time <= 3500)
{
robotStop();
Serial.println(time);
}
else if (time >= 3500 && time <= 4000)
{
robotLeft();
Serial.println(time);
}
else if (time >= 4000 && time <= 4500)
{
robotStop();
Serial.println(time);
}
else if (time >= 4500 && time <= 5000)
{
robotRight();
Serial.println(time);
}
else if (time >= 5000 && time <= 5500)
{
robotStop();
Serial.println(time);
}
else if (time >= 5500 && time <= 6000)
{
robotRight();
Serial.println(time);
}
else if (time >= 6000 && time <= 6500)
{
robotStop();
Serial.println(time);
}
else if (time >= 6500 && time <= 7000)
{
robotLeft();
Serial.println(time);
}
else if (time >= 7000 && time <= 7500)
{
robotStop();
Serial.println(time);
}
else
{
time = time - time;
Serial.println(time);
}
}
void getToYellow()
{
robotForward();
delay(6000);
robotStop();
delay(500);
robotRight();
delay(1100);
robotStop();
delay(500);
robotForward();
delay(4000);
robotStop();
delay(500);
robotRight();
delay(1100);
robotStop();
delay(500);
}
//**************************************************************************************************************************************************************
////////////////////////////COMMENTS//////////////////////////////////////////////
//(clear_color >= 500 && clear_color <= 5000 && red_color >= 200 && red_color <= 1000 && green_color >= 400 && green_color <= 2100 && blue_color >= 200 && blue_color <= 1500) = YELLOWTAPE
//(clear_color >= 500 && clear_color <= 5000 && red_color >= 200 && red_color <= 1000 && green_color >= 400 && green_color <= 2100 && blue_color >= 200 && blue_color <= 1500) === GREENTAPE
//(red_color >= 1000 && green_color >= 1000 && blue_color >= 1000) =============================================================================================================== WHITETAPE
//(clear_color >= 500 && clear_color <= 10000 && red_color >= 1000 && red_color <= 2400 && green_color >= 200 && green_color <= 1500 && blue_color >= 200 && blue_color <= 1500) = REDTAPE
//(clear_color >= 1000 && clear_color <= 3000 && red_color >= 0 && red_color <= 1000 && green_color >= 100 && green_color <= 900 && blue_color >= 800 && blue_color <= 1200) ===== BLUETAPE
//(clear_color >= 0 && clear_color <= 1000 && red_color >= 0 && red_color <= 500 && green_color >= 0 && green_color <= 500 && blue_color >= 0 && blue_color <= 500) ============== BLACKFLOOR
//(clear_color >= 1 && clear_color <= 12000 && red_color >= 3000 && red_color <= 5000 && green_color >= 1300 && green_color <= 3000 && blue_color >= 600 && blue_color <= 2000)=== TARGET
//
//
//
//
/*
new color tape
(clear_color >= 1800 && clear_color <= 3500 && red_color >= 1000 && red_color <= 2500 && green_color >= 325 && green_color <= 750 && blue_color >= 300 && blue_color <= 650)
window Red
(clear_color >= 1691&& clear_color <= 2126 && red_color >= 360 && red_color <= 566 && green_color >= 474 && green_color <= 696 && blue_color >= 746 && blue_color <= 986)
window Blue
(clear_color >= 4906&& clear_color <= 8841 && red_color >= 2138 && red_color <= 3906 && green_color >= 1819 && green_color <= 3376 && blue_color >= 797 && blue_color <= 1546)
window Yellow
(clear_color >= 1025&& clear_color <= 2192 && red_color >= 278 && red_color <= 482 && green_color >= 360 && green_color <= 517 && blue_color >= 272 && blue_color <= 426)
window Green
*/
| true |
7d0d8ab00a3d0c891cbc3c396c83d247e0a3982c | C++ | carlshen/clean-cpp | /CompositePattern/src/commandprocessor.h | UTF-8 | 567 | 2.921875 | 3 | [] | no_license | #ifndef COMMANDPROCESSOR_H_
#define COMMANDPROCESSOR_H_
#include "command.h"
#include <iostream>
#include <memory>
#include <stack>
class CommandProcessor
{
public:
void execute(const CommandPtr& command) {
command->execute();
commandHistory.push(command);
}
void undoLastCommand() {
if (commandHistory.empty()) {
std::cout << "[WARN] No commands in history" << std::endl;
return;
}
commandHistory.top()->undo();
commandHistory.pop();
}
private:
std::stack<std::shared_ptr<Revertable>> commandHistory;
};
#endif /* COMMANDPROCESSOR_H_ */
| true |
37f569d97f4f34470c20f30f558e9e32120739b5 | C++ | YIP10/TTS-GrafkomH-672018219 | /main.cpp | UTF-8 | 9,540 | 2.875 | 3 | [] | no_license | #include <stdlib.h>
#include <GL/glut.h>
#include <math.h>
void segi () {
glBegin (GL_POLYGON) ;
glVertex2f (-10,50) ; //garis bawahan,depan garis kiri
glVertex2f (25,120) ; //garis bawahan
glVertex2f (60,50) ; //garis pucukan,depan garis kanan
glVertex2f (25,-20) ;//garis pucukan
glEnd ();
}
void tupat (){
glBegin (GL_QUADS) ;
glVertex2f (0,50) ; //garis bawahan,depan garis kiri
glVertex2f (25,100) ; //garis bawahan
glVertex2f (50,50) ; //garis pucukan,depan garis kanan
glVertex2f (25,0) ;//garis pucukan
glEnd ();
}
void render (){
glClear(GL_COLOR_BUFFER_BIT);
glColor3f (0.7,1,0);
segi ();
glTranslatef (50,0,0);
segi ();
glTranslatef (50,0,0);
segi ();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (0,0,0);
glColor3f(0,0.5,0.9);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-25,90,0);
glColor3f (0.1,0,0.8);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glColor3f (0,0.5,0.9);
glTranslatef (0,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-25,90,0);
glColor3f (0.7,1,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glColor3f (0,0.5,0.9);
glTranslatef (0,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (25,90,0);
glColor3f (0.1,0,0.8);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glColor3f (1,0,0);
glTranslatef (0,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (25,90,0);
glColor3f (0.7,1,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glColor3f (0,0.5,0.9);
glTranslatef (0,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-25,90,0);
glColor3f (0.1,0,0.8);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glColor3f (0,0.5,0.9);
glTranslatef (0,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (0,-540,0);
glColor3f (0.1,0,0.8);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glTranslatef (50,0,0);
segi();
glColor3f (1,0,0);
glTranslatef (0,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glTranslatef (-50,0,0);
tupat();
glFlush ();
}
int main (int argc, char **argv)
{
glutInit (&argc , argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_DEPTH | GLUT_RGBA);
glutInitWindowPosition (100,100);
glutInitWindowSize (640,480) ; //ukuran dari jendela
glutCreateWindow ("TTS GrafKom 672018219") ;
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
glutDisplayFunc (render) ; //yang dirender
glutMainLoop () ;
}
| true |
81f41c37ffd965c086b920328e5caf344e7e552d | C++ | pmdoll/tomcat | /src/cpp/pro_gen/Pos.h | UTF-8 | 2,321 | 3.90625 | 4 | [
"MIT"
] | permissive | /**
* @brief This file defines the members and methods
* implemented as part of the Pos class
*/
#pragma once
#include <string>
/**
* @brief This class represents a 3D coordinate
*/
class Pos {
private:
int x;
int y;
int z;
public:
/**
* @brief Get the X coordinate of this object
*
* @return int The x coordinate
*/
int getX();
/**
* @brief Get the Y coordinate of this object
*
* @return int The y coordinate
*/
int getY();
/**
* @brief Get the Z coordinate of this object
*
* @return int The z coordinate
*/
int getZ();
/**
* @brief Set the x value of this Pos object
*
* @param x The value x is to be set to
*/
void setX(int x);
/**
* @brief Set the y value of this Pos object
*
* @param y The value y is to be set to
*/
void setY(int y);
/**
* @brief Set the z value of this Pos object
*
* @param z The value z is to be set to
*/
void setZ(int z);
/**
* @brief Shift the x value by a given amount
*
* @param shift The amount to shift by which may be positive or negative
*/
void shiftX(int shift);
/**
* @brief Shift the y value by a given amount
*
* @param shift The amount to shift by which may be positive or negative
*/
void shiftY(int shift);
/**
* @brief Shift the z value by a given amount
*
* @param shift The amount to shift by which may be positive or negative
*/
void shiftZ(int shift);
/**
* @brief Gets a string representation of the various
* fields and values stores in an instance as a TSV
*
* @return string The TSV representation
*/
std::string toTSV();
/**
* @brief Construct a new Pos object
*/
Pos();
/**
* @brief Construct a new Pos object
*
* @param x The x coordinate
* @param y The y coordinate
* @param z The z coordinate
*/
Pos(int x, int y, int z);
/**
* @brief Construct a new Pos object as a copy
* of the given Pos object
*
* @param other The object whose fields are to be copied
*/
Pos(const Pos& other);
/**
* @brief Destroy the Pos object
*/
~Pos();
};
| true |
51e8ddd3d2b481bfdd0f777da7232aa6eca0d018 | C++ | prateeks97/Cpp_Data_Structures_and_Algorithms | /C++ Practice/Data Structures and Algorithms/Queue/queue_array.cpp | UTF-8 | 1,241 | 3.78125 | 4 | [] | no_license | #include <iostream>
#include <cmath>
#include <cstring>
#define MAX_SIZE 101
using namespace std;
class Queue{
int A[MAX_SIZE];
int front;
int rear;
public:
Queue(){
front = -1;
rear = -1;
}
bool IsEmpty(){
return (front == -1 && rear == -1);
}
void Enqueue(int x){
if ((rear+1)%MAX_SIZE == front){
cout << "Queue already full.\n";
return;
}
else if (IsEmpty()){
front = 0;
rear = 0;
A[rear] = x;
}
else{
rear = (rear+1)%MAX_SIZE;
}
A[rear] = x;
}
void Print(){
cout << "Queue is: ";
for (int i = front; i<=rear; i++){
cout << A[i] << " ";
}
cout << endl;
}
void Dequeue(){
if (IsEmpty()){
cout << "Queue empty.\n";
return;
}
else if (front == rear){
front = -1;
rear = -1;
}
else
front = (front+1)%MAX_SIZE;
}
};
int main(){
Queue q;
//cout<< q.IsEmpty();
q.Enqueue(2);
//cout<< q.IsEmpty();
q.Enqueue(5);
q.Print();
q.Dequeue();
q.Print();
return 0;
}
| true |
ad10da52fbe5d9cc6842b17369527a54a02ca808 | C++ | tlikhomanenko/flashlight | /flashlight/pkg/speech/augmentation/SoundEffect.h | UTF-8 | 2,468 | 2.828125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <memory>
#include <mutex>
#include <random>
#include <sstream>
#include <string>
#include <vector>
namespace fl {
namespace pkg {
namespace speech {
namespace sfx {
/**
* Base class for sound effects.
*/
class SoundEffect {
public:
SoundEffect() = default;
virtual ~SoundEffect() = default;
virtual void apply(std::vector<float>& sound) = 0;
virtual std::string prettyString() const = 0;
};
/**
* A container for chaining sound effect. It serially applies calls to all added
* sound effects.
*/
class SoundEffectChain : public SoundEffect {
public:
SoundEffectChain() {}
~SoundEffectChain() override = default;
void apply(std::vector<float>& sound) override;
std::string prettyString() const override;
void add(std::shared_ptr<SoundEffect> SoundEffect);
bool empty();
protected:
std::vector<std::shared_ptr<SoundEffect>> soundEffects_;
};
/**
* Normalize amplitudes to range -1..1 using dynamic range linear compression.
* No-op if the signal's amplitudes are already within that range.
*/
class Normalize : public SoundEffect {
public:
explicit Normalize(bool onlyIfTooHigh = true);
~Normalize() override = default;
void apply(std::vector<float>& sound) override;
std::string prettyString() const override;
private:
bool onlyIfTooHigh_;
};
/**
* Clamps amplitudes to range -1..1.
* No-op if the signal's amplitudes are already within that range.
*/
class ClampAmplitude : public SoundEffect {
public:
explicit ClampAmplitude() {}
~ClampAmplitude() override = default;
void apply(std::vector<float>& sound) override;
std::string prettyString() const override;
};
/**
* Amplifies (or decreases amplitude of) the signal with a random ratio in the
* specified range.
*/
class Amplify : public SoundEffect {
public:
struct Config {
float ratioMin_;
float ratioMax_;
unsigned int randomSeed_;
};
explicit Amplify(const Amplify::Config& config);
~Amplify() override = default;
void apply(std::vector<float>& sound) override;
std::string prettyString() const override;
private:
std::mt19937 randomEngine_;
std::uniform_real_distribution<> randomRatio_;
std::mutex mutex_;
};
} // namespace sfx
} // namespace speech
} // namespace pkg
} // namespace fl
| true |
f89cf48622496b35fe3a7f0ee2d6e4fa7b6aee58 | C++ | ms303956362/myexercise | /Cpp/LeetCode/wc312_2.cpp | UTF-8 | 607 | 2.75 | 3 | [] | no_license | #include "usual.h"
class Solution {
public:
int longestSubarray(vector<int>& nums) {
int n = nums.size(), max_num = *max_element(nums.begin(), nums.end());
int i = 0, ans = 1;
while (i < n) {
if (nums[i] != max_num) {
++i;
} else {
int j = i + 1;
while (j < n && nums[j] == max_num) {
++j;
}
ans = max(ans, j - i);
i = j;
}
}
return ans;
}
};
int main(int argc, char const *argv[])
{
return 0;
}
| true |
c739c8243227bc5bd9ef5c84bf6fd40de0ab88f6 | C++ | mayali123/data-structure | /实验课代码/stack.cpp | GB18030 | 2,681 | 3.328125 | 3 | [] | no_license | #include<stdio.h>
#include<malloc.h>
#define ElemType char
#define MAXSIZE 100
#define Status int
#define Error 0
#define True 1
#define FALSE 0
#define OK 1
typedef struct stack{
ElemType data[MAXSIZE];
int top;
}ST;
ST* InitStack()
{
ST* stack =(ST*)malloc(sizeof(ST)) ;
stack->top =-1;
return stack;
}
Status Push(ST*stack,ElemType e)
{
if(stack->top==MAXSIZE-1)
return FALSE;
stack->data[++stack->top] = e;
return OK;
}
Status Pop(ST*stack,ElemType *e)
{
if(stack->top==-1)
return FALSE;
*e = stack->data[stack->top--];
return OK;
}
void DestroyStack(ST* stack)
{
free(stack);
}
// Ϊշ 1 Ϊշ0
int StackEmpty(ST* stack)
{
return (stack->top == -1);
}
int GetTop(ST* stack,ElemType * e)
{
if (stack->top == -1)
return Error;
*e = stack->data[stack->top];
return True;
}
void show(ST* stack)
{
for (int i = 0; i <= stack->top; i++)
{
printf("%d ", stack->data[i]);
}
}
void trans(char *exp,char *postexp)
{
ST * p=InitStack();
int k=0;
char e;
for(int i=0;exp[i]!='\0';i++)
{
switch(exp[i])
{
case '(':
Push(p,exp[i]);
break;
case ')':
while(1)
{
Pop(p,&e);
if(e =='(')
break;
postexp[k++]=e;
}
break;
case '+':
while(!StackEmpty(p))
{
GetTop(p,&e);
if(e!='(')
{
Pop(p,&e);
postexp[k++] = e;
}
else
break;
}
Push(p,exp[i]);
break;
case '-':
case '*':
break;
case '/':
break;
default:
while('0'<=exp[i]&&exp[i]<='9')
{
postexp[k++]=exp[i];
i++;
}
postexp[k++] = ' ';
}
}
while(!StackEmpty(p))
{
Pop(p,&e);
printf("e=%c ",e);
postexp[k++] = e;
}
postexp[k++]='\0';
}
/*int comp(char *exp)
{
ST *p =InitStack();
int num1,num2,e;
for(int i=0;exp[i]!='\0';i++)
{
switch(exp[i])
{
case '+':
Pop(p,&num1);
Pop(p,&num2);
Push(p,num1+num2);
break;
case '-':
Pop(p,&num1);
Pop(p,&num2);
Push(p,num2-num1);
break;
case '*':
Pop(p,&num1);
Pop(p,&num2);
Push(p,num2*num1);
break;
case '/':
Pop(p,&num1);
Pop(p,&num2);
Push(p,num2/num1);
break;
default:
int a=0;
while('0'<=exp[i]&&exp[i]<='9')
{
a =a*10+exp[i]-'0';
i++;
}
Push(p,a);
}
}
GetTop(p,&e);
DestroyStack(p);
return e;
}
*/
int main()
{
/*int i=comp("122 2 -");
printf("%d",i);
return 0;*/
char ch[]="123 + 2",ch1[100];
trans(ch,ch1);
printf("%s",ch1);
}
| true |
13205ea25bfaf538e1dfe510307812c1190efb03 | C++ | hhhjjjja/Cpp | /Assignment/161014_Circle배열 분리/161014_Circle배열 분리/main.cpp | UHC | 1,543 | 3.84375 | 4 | [] | no_license | #include <iostream>
#include "Circle.h" //Circle.h include
using namespace std;
int main() {
cout << "ϰ ϴ ?"; //ϰ ϴ ?
int n, radius; //n= , radius=
cin >> n; //n Է
if(n <= 0) return 0; //Է¹ n 0 ۰ų 0ȯ
Circle *pArray = new Circle [n]; //n Circle迭
for(int i=0;i<n;++i) { //i 0 n +1ϸ鼭 {}ݺ
cout << "" << i+1 << ": "; //" (i+1) : " -> () {} ѹǸ 1, 2=2...
cin >> radius; //radius Է
pArray[i].setRadius(radius); // Circle ü Է¹ ʱȭ
}
int count =0; //īƮ
Circle*p = pArray; //pArray ϰ ϱ p
for(int i=0;i<n;++i) { //i 0 n +1ϸ鼭 {}ݺ
cout << p->getArea() << ' '; //getArea ȯ
if(p->getArea() >= 100 && p->getArea() <= 200) // 100 200 īƮ
count++; // ϸ count +1
p++; // 迭 Ѿ
}
cout << endl << " 100 200 " << count << endl; //count
delete [] pArray; //ü 迭 Ҹ
}
| true |
74f13359a3aff30fc7a2d2506b728f58b14f5a0e | C++ | llundell/CS311 | /treesort.h | UTF-8 | 4,364 | 3.65625 | 4 | [] | no_license | // treesort.h
// Laura Lundell & Khan Howe
// Started: 11/13/18
// Updated: 11/20/18
// Header for function template treesort.h
// Exercise A: Treesort
/* Sources used:
* Dr. Chappell's slides treesort.h skeleton
* Charles helped eliminate checking for nullptr in insert() and traverse()
* and instead checking if left/right children exist before inserting/traversing
*/
#ifndef FILE_TREESORTNOBSTREE_H_INCLUDED
#define FILE_TREESORTNOBSTREE_H_INCLUDED
#include <iterator>
#include <memory>
// struct BSTreeNode
// Takes client-specified value type
// Invariants:
// _data = data
// _left = left in the node or a nullptr
// _right = right in the node or a nullptr
// Requrements on types:
// ValType needs a copy constructor,
// destructor that doesn't throw, and
// operator < for insert() function
template <typename ValType>
struct BSTreeNode
{
ValType _data;
std::shared_ptr<BSTreeNode<ValType>> _leftChild;
std::shared_ptr<BSTreeNode<ValType>> _rightChild;
BSTreeNode() :_data(), _leftChild(nullptr), _rightChild(nullptr)
{}
// BSTreeNode Constructor
// Pre-conditions:
// Data must be valid, non-empty
// Post-conditions:
// Creates Binary Search Tree node with no children
// Strong guarantee, exception neutral but
// exception may throw if ValType throws
explicit BSTreeNode(const ValType & data,
std::shared_ptr<BSTreeNode<ValType>> leftChild = nullptr,
std::shared_ptr<BSTreeNode<ValType>> rightChild = nullptr)
:_data(data),
_leftChild(leftChild),
_rightChild(rightChild)
{}
//Destructor
~BSTreeNode() = default;
};
// Insert()
// Pre-condition:
// Takes a pointer to a tree and a data item
// by reference
// Post-condition:
// Inserts data item uses recursive calls to
// place item in sorted place
// Requrements on types:
// ValType needs a copy constructor,
// destructor that doesn't throw, and
// operator < for insert() function
// Exceptions:
// Throws if ValType operation throws
template <typename ValType>
void insert(std::shared_ptr<BSTreeNode<ValType>> & treeNode,
ValType & item)
{
if (item < treeNode-> _data)
{
if (treeNode-> _leftChild) {
insert(treeNode-> _leftChild, item);
}
else {
treeNode-> _leftChild = std::make_shared<BSTreeNode<ValType>>(item);
}
}
else {
if (treeNode-> _rightChild) {
insert(treeNode-> _rightChild, item);
}
else {
treeNode-> _rightChild = std::make_shared<BSTreeNode<ValType>>(item);
}
}
}
// traverse()
// Pre-conditions:
// Takes valid pointer
// Post-condition:
// Traverses a binary tree
// Completes inorder traversal of binary search tree using recursion
// Takes a pointer to a tree and an iterator by reference
// Requrements on types:
// ValType needs a copy constructor,
// destructor that doesn't throw, and
// operator < for insert() function
// Exceptions: May throw if ValType operation throws
// No-throw guarantee, exception neutral
// Part of the FDIter type, not its own type
template <typename FDIter>
FDIter traverse(std::shared_ptr<BSTreeNode<typename std::iterator_traits<FDIter>::value_type>> & treeNode,
FDIter iter)
{
if (treeNode-> _leftChild) {
iter = traverse(treeNode-> _leftChild, iter);
}
*iter = (treeNode-> _data);
++iter;
if (treeNode-> _rightChild) {
iter = traverse(treeNode-> _rightChild, iter);
}
return iter;
}
// treesort()
// Pre-conditions:
// Iterators first, last must be in the same range
// FDIter last must be greater than or equal to first
// Post-condition:
// Sort a given range using Treesort
// Requrements on types:
// ValType needs a copy constructor,
// destructor that doesn't throw, and
// operator < for insert() function
// Exceptions: May throw if ValType operation throws
template<typename FDIter>
void treesort(FDIter first, FDIter last)
{
using ValType = typename std::iterator_traits<FDIter>::value_type;
if (first == last) {
return;
}
auto root = std::make_shared<BSTreeNode<ValType>>(*first);
auto current = first;
++current;
for ( ; current != last; ++current) {
insert(root, *current);
}
traverse(root, first);
}
#endif //#ifndef FILE_TREESORT_H_INCLUDED
| true |
01b3e9d9487b812e6765405ad63f3a0f1e0f4d48 | C++ | Suanec/BachelorOfIS | /专业课程序解疑/指针通过角标符操作/指针通过角标符操作/指针通过角标符操作.cpp | GB18030 | 1,259 | 2.84375 | 3 | [] | no_license | #include<iostream>
# include <stdio.h>
using namespace std;
struct S
{
int i;
int *p;
};
void main()
{
S s;
int *p = &s.i;
p[0] = 1;
p[1] = 5;
cout<<"p[0] = "<<p[0]<<";"<<"s.i = "<<s.i<<endl;
cout<<"&p[0] = "<<&p[0]<<";&s.i = "<<&s.i<<endl;
cout <<"p[1] = " <<p[1]<<"; s.p = "<<s.p<<" "<<endl;
cout<<"&p[1] = "<<&p[1]<<";&s.p = "<<&s.p<<";&s.p[1] = "<<&s.p[1]<<endl;
cout << endl;
s.p = p;
cout<<"p[0] = "<<p[0]<<";s.i = "<<s.i<<endl;
cout<<"&p[0] = "<<&p[0]<<";&s.i = "<<&s.i<<endl;
cout<<"p[1] = "<<p[1]<<";s.p = "<<s.p<<";s.p[1] = "<<s.p[1]<<endl;
cout<<"&p[1] = "<<&p[1]<<";&s.p = "<<&s.p<<";&s.p[1] = "<<&s.p[1]<<endl;
s.p[1] = 1;
cout<<"s.p = "<<s.p<<";&s.p = "<<&s.p<<endl;
/* char fn=NULL, ln = NULL;
printf("һĸ\n");
scanf("%c", &ln);
printf("һĸ%c\n", ln);
printf("ڶĸ\n");
scanf("%c", &fn);cout<<"<<";
cin>>fn;scanf("%c", &fn);cout<<">>";
printf("ڶĸ%c\n", fn);
cout<<&fn<<" "<<&ln<<endl;
char *p123,*q123;
p123=&fn;
q123=&ln;
cout<<&p123<<" "<<&q123<<endl;
int f=sizeof("\n");
cout<<f<<endl;
f=sizeof("123");
cout<<f<<endl;*/
int a=1024,b=1;
int z=1024<<2;
cout<<z<<endl;//z=4096
system("pause");
} | true |
6d1e24e4e8a833ce1dfad1f3703137cd7f5d70d2 | C++ | frank1iu/PlayCompiler | /compiler.hpp | UTF-8 | 2,140 | 2.546875 | 3 | [] | no_license | #pragma once
#include "parser.hpp"
#include "runtime.hpp"
#include <string>
#include <array>
using namespace std;
static int last_label = 0;
class Compiler {
public:
Compiler();
// reference counts of each register
// -1 means reserved
// r5, r6, r7 start as reserved, so there are actually
// 8 - 3 = 5 available registers to use.
array<int, 8> registers;
// compiles a program represented as a string
// multiple s-expressions are ok
void compile_program(string program);
// if any register has a positive reference count
// this function will return true.
bool all_registers_free() const;
// exports all emitted assembly code as a string
string toString() const;
private:
vector<string> asm_code;
vector<string> asm_fn;
vector<string> asm_data;
int rc_ralloc();
void rc_keep_ref(int r_dest);
void rc_free_ref(int r_dest);
int load_value(Token* program);
int load_value_stack(Token* program);
int compile_one(Token* program);
int expr_define(Token* program);
int expr_define_stack(Token* program);
int expr_define_fn(Token* program);
int expr_set(Token* program);
int expr_void(Token* program);
int expr_write(Token* program);
int expr_call(Token* program);
int expr_not(Token* program);
int expr_sub(Token* program);
int expr_sub1(Token* program);
int expr_add(Token* program);
int expr_add1(Token* program);
int expr_begin(Token* program);
int expr_addr(Token* program);
int expr_deref(Token* program);
int expr_equals(Token* program);
int expr_less_than(Token* program);
int expr_greater_than(Token* program);
int expr_if(Token* program);
int expr_while(Token* program);
int expr_for(Token* program);
void stack_define(string name, int size);
void stack_shrink(int size);
string next_label();
string rtos(int r) const;
void emit(string code, Token* program);
void emit(string code, string debug);
int _ralloc_return_val = -1;
void ralloc_force_return(int r_dest);
RuntimeStack stack;
FunctionTable ft;
}; | true |
cc3f37dbc2e81f933eecfe0afc6e0b7f267eb1b6 | C++ | Zhgsimon/Piscine_ece | /arete.cpp | UTF-8 | 554 | 2.78125 | 3 | [] | no_license | #include "arete.h"
Arete::Arete(int id, int sommet_depart, int sommet_arrive): m_id{id},m_sommet_depart{sommet_depart},m_sommet_arrive{sommet_arrive}
{
}
void Arete::ajouterPoids(float poids){
m_poids.push_back(poids);
}
float Arete::getPoids()const{
return m_poids[0];
}
float Arete::getPoids2()const{
return m_poids[1];
}
int Arete::getSommetDepart() const{
return m_sommet_depart;
}
int Arete::getSommetArrive() const{
return m_sommet_arrive;
}
int Arete::getId() const {
return m_id;
}
Arete::~Arete()
{
//dtor
}
| true |
511f64768c23ebe25789057c9d9a5ff0998b3ed0 | C++ | tyuety/201811050983 | /programming/2.2.cpp | GB18030 | 1,112 | 3.515625 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
struct num
{
int number;
struct num *next;
};
int getnumber(int m,int n);
int getnumber1(int m,int n);
int main()
{
int m,n;
scanf("%d%d",&m,&n);
printf("Ϊ:%d\n\n\n",getnumber(m,n));
return 0;
}
int getnumber(int m,int n)
{
struct num *p,*p1,*head,*temp;
int i=0,flag;
p=(struct num*)malloc(sizeof(struct num));
head=p;
while(i<m)
{
p1=p;
p->number=i+1;
p=(struct num*)malloc(sizeof(struct num));
p1->next=p;
i++;
}
p1->next=head; //γɻ״б
free(p);
temp=p1; //tempǰָǰ
i=1;
while(i<m)
{
flag=1; //
//Ҫɾıŵָ
while(flag<n)
{
temp=head;
head=head->next;
flag++;
}
temp->next=head->next;
printf("ɾӵı:%d\n",head->number);
free(head);
head=temp->next;
i++;
}
return head->number;
}
| true |
1daead4d0847dfb32b1bc0d1267c20be98218574 | C++ | ianjamesx/University | /COSC 220/Lab4/vectorAux.cpp | UTF-8 | 1,486 | 3.28125 | 3 | [] | no_license | /*
vectorAux.cpp
Implementations of template functions
Cosc-220 Lab 7
Thomas Anastasio
Created: February 25, 2003
Current: March 13, 2003
*/
////////// THIS CODE IS PROVIDED TO STUDENTS /////////////
#include "vectorAux.h"
#include <vector>
#include <algorithm>
#include <iostream>
template <typename T>
void removeDup(std::vector<T> & v){
/*
//sort vector elements
sort(v.begin(), v.end());
//erase element if it is a duplicatetd::
v.erase(unique(v.begin(), v.end()), v.end());
*/
//different approach
using namespace std;
vector<int>v1;
int i;
for(i = 0; i < v.size(); i++){
unsigned index = seqVectSearch(v, 5);
// if(index != v.end()){
// v1.push_back(v[i]);
//}
}
}
template <typename T>
unsigned seqVectSearch(const std::vector<T> & v, unsigned first,
unsigned last, const T& target){
unsigned i;
/// Complete the code. Use the text's sequential search
/// algorithm for arrays as a model.
for(i = 0; i < 10; i++){
if(v[i] == target){
return i;
}
}
return last; // return last if target not found
}
template <typename T>
void writeVector(const std::vector<T> & v){
unsigned i;
unsigned n = v.size();
for (i = 0; i < n; i++)
std::cout << v[i] << ' ';
std::cout << std::endl;
}
| true |
0974e102abf137324ae9a8ef472a35b8e5d18a71 | C++ | Jenocn/MessageCenter | /cpp/ClassType.h | UTF-8 | 792 | 2.671875 | 3 | [] | no_license | /*
By Jenocn
https://jenocn.github.io/
*/
#ifndef __CLASS_TYPE_H_H__
#define __CLASS_TYPE_H_H__
template<typename T>
class ClassTypeCounter final
{
public:
static int _count;
public:
ClassTypeCounter()
{
_index = _count;
++_count;
}
public:
int _index{ 0 };
};
template<typename T>
int ClassTypeCounter<T>::_count = 0;
//=================================================
template<typename TClass, typename TCounter>
class ClassType
{
private:
static ClassTypeCounter<TCounter> __counter;
public:
static int GetClassType() { return __counter._index; }
static int GetTypeCount() { return ClassTypeCounter<TCounter>::_count; }
};
template<typename TClass, typename TCounter>
ClassTypeCounter<TCounter> ClassType<TClass, TCounter>::__counter;
#endif // !__CLASS_TYPE_H_H__ | true |
30ab0f7e19e18ec9adb4ca82c0f8d7ce2b54edb5 | C++ | AtwoodHuang/redbase | /src/rm_pagehdr.h | UTF-8 | 1,673 | 2.875 | 3 | [] | no_license | #ifndef REDBASE_RM_PAGEHDR_H
#define REDBASE_RM_PAGEHDR_H
#include <iostream>
#include "bitmap.h"
#include <cstring>
struct RMPageHdr {
int free; // 和common_thing里定义一样
char * freeSlotMap; // 记录freeslot 的bitmap
int numSlots; //slot总数
int numFreeSlots; //空闲slot数
RMPageHdr(int numSlots) : numSlots(numSlots), numFreeSlots(numSlots)
{
freeSlotMap = new char[this->mapsize()];
}
~RMPageHdr()
{
delete [] freeSlotMap;
}
//总大小
int size() const
{
return sizeof(free) + sizeof(numSlots) + sizeof(numFreeSlots) + bitmap(numSlots).numChars()*sizeof(char);
}
//bitmap大小
int mapsize() const
{
return this->size() - sizeof(free) - sizeof(numSlots) - sizeof(numFreeSlots);
}
//内容放到buff里
int to_buf(char *& buf) const
{
memcpy(buf, &free, sizeof(free));
memcpy(buf + sizeof(free), &numSlots, sizeof(numSlots));
memcpy(buf + sizeof(free) + sizeof(numSlots), &numFreeSlots, sizeof(numFreeSlots));
memcpy(buf + sizeof(free) + sizeof(numSlots) + sizeof(numFreeSlots), freeSlotMap, this->mapsize()*sizeof(char));
return 0;
}
//从buff读入
int from_buf(const char * buf)
{
memcpy(&free, buf, sizeof(free));
memcpy(&numSlots, buf + sizeof(free), sizeof(numSlots));
memcpy(&numFreeSlots, buf + sizeof(free) + sizeof(numSlots), sizeof(numFreeSlots));
memcpy(freeSlotMap, buf + sizeof(free) + sizeof(numSlots) + sizeof(numFreeSlots), this->mapsize()*sizeof(char));
return 0;
}
};
#endif //REDBASE_RM_PAGEHDR_H
| true |
1ac7edbb6db0c27130801ad6fb8402ba815ca817 | C++ | Ronnie-Git/Starting-point | /5.everyday/2019-04/12/1.最大乘积.cpp | UTF-8 | 1,095 | 3.140625 | 3 | [] | no_license | /*************************************************************************
> File Name: 1.最大乘积.cpp
> Author: x
> Mail: x.com
> Created Time: 2019年04月12日 星期五 21时54分31秒
************************************************************************/
#include <iostream>
using namespace std;
const int INF = 0x3f3f3f3f;
typedef long long LL;
void init(LL *arr) {
arr[0] = arr[1] = INF;
arr[2] = arr[3] = arr[4] = -INF - 1;
return ;
}
int main() {
LL arr[5] = {0}, x, n;
init(arr);
cin >> n;
for (LL i = 0; i < n; i++) {
cin >> x;
if (x >= arr[4]) {
arr[2] = arr[3];
arr[3] = arr[4];
arr[4] = x;
} else if (x >= arr[3]) {
arr[2] = arr[3];
arr[3] = x;
} else if (x >= arr[2]) {
arr[2] = x;
}
if (x <= arr[0]) {
arr[1] = arr[0];
arr[0] = x;
} else if (x <= arr[1]) {
arr[1] = x;
}
}
cout << max(arr[0] * arr[1] * arr[4], arr[2] * arr[3] * arr[4]);
return 0;
}
| true |
9db1169fa6823873a5a997efd5225e8e592bba2e | C++ | dmauk/ASCII-Game-Test | /ASCII GAME/Player.h | UTF-8 | 349 | 3.046875 | 3 | [] | no_license | #pragma once
class Player {
public:
//Constructors
Player();
void init(int health, int attack, int defense, int level, int experience);
//Functions
void setLocation(int x, int y);
void getLocation(int &x, int& y);
private:
//Stats
int _health;
int _attack;
int _defense;
int _level;
int _experience;
//Location
int _x;
int _y;
}; | true |
e6da0176f7dc60c14a159cb81a5dd10926067bac | C++ | bingluen/CSE-CODE | /PD2-A6/PD2-A6/Vector.cpp | UTF-8 | 6,343 | 3.765625 | 4 | [] | no_license | // Member-function definitions for class Vector.
#include "Vector.h" // include definition of class Vector
// constructor
template< typename T >
Vector< T >::Vector( unsigned int n, const T val )
{
size = n;
capacity = n;
ptr = new T[ n ];
if( n > 0 )
for ( unsigned int i = 0; i < n; i++ )
ptr[ i ] = val;
} // end Vector constructor
// destructor
template< typename T >
Vector< T >::~Vector()
{
delete [] ptr;
} // end destructor
template< typename T >
T* Vector< T >::begin() const
{
return ptr;
}
template< typename T >
T* Vector< T >::end() const
{
return ptr + size;
}
template< typename T >
unsigned int Vector< T >::getSize() const
{
return size;
}
/* Assignment 6 - implement */
template< typename T >
Vector< T >::Vector(const Vector< T > &vectorToCopy)
{
// Constructs a vector with a copy of each of the elements in vectorToCopy, in the same order.
//copy size & capacity
this->size = vectorToCopy.size;
this->capacity = vectorToCopy.capacity;
//allocate memory
this->ptr = new T[this->capacity];
//copy data
memcpy(this->ptr, vectorToCopy.ptr, this->size * sizeof(T));
}
template< typename T >
const Vector< T > &Vector< T >::operator=(const Vector< T > &right)
{
// assignment operator
//check capacity
if (right.size > this->capacity)
{
//if right.size > this->Capacity, call reserve to reallocate memory
this->reserve(right.size);
}
//set size
this->size = right.size;
//copy data
memcpy(this->ptr, right.ptr, this->size * sizeof(T));
return *this;
}
template< typename T >
bool Vector< T >::operator==(const Vector< T > &right) const
{
// equality operator
//check size
if (this->size != right.size)
return false;
//compare every digit
for (T *p = this->begin(), *rP = right.begin()
; p < this->end()
; p++, rP++)
{
if (*p != *rP)
return false;
}
return true;
}
template< typename T >
bool Vector< T >::operator!=(const Vector< T > &right) const
{
// inequality operator; returns opposite of == operator
return !(*(this) == right);
}
template< typename T >
T &Vector< T >::operator[](unsigned int pos)
{
// subscript operator for non-const objects returns modifiable lvalue
return ptr[pos];
}
template< typename T >
T Vector< T >::operator[](unsigned int pos) const
{
// subscript operator for const objects returns rvalue
return ptr[pos];
}
template< typename T >
void Vector< T >::resize(unsigned int n)
{
// Resizes the container so that it contains n elements.
// If n is smaller than the current container size,
// the content is reduced to its first n elements, removing those beyond.
// If n is greater than the current container size,
// the content is expanded by inserting at the end as many elements as needed to reach a size of n.
// The new elements are initialized as 0.
// If n is also greater than the current container capacity,
// an automatic reallocation of the allocated storage space takes place.
//check capacity, if n > capacity call reserve to reallocate memory
if (n > this->capacity)
{
this->reserve(n);
}
//init new element as 0
memset(this->end(), 0, this->capacity - this->getSize());
this->size = n;
}
template< typename T >
void Vector< T >::reserve(unsigned int n)
{
// Requests that the vector capacity be enough to contain n elements.
// If n is greater than the current vector capacity,
// the function causes the container to reallocate its storage increasing its capacity to n.
// In all other cases, the function call does not cause a reallocation and
// the vector capacity is not affected.
if (n > this->capacity)
{
T* tempPtr = ptr;
this->capacity = n;
this->ptr = new T[this->capacity];
//copy data
memcpy(this->ptr, tempPtr, this->size * sizeof(T));
delete[]tempPtr;
}
}
template< typename T >
void Vector< T >::assign(T *first, T *last)
{
// Assigns new contens to the vector, replacing its current contents,
// and modifying its size accordingly.
// The new contents are elements constructed from each of the elements
// in the range between first and last, in the same order.
unsigned int length = last - first;
//if length > this->capacity, reallocate memory
if (length > this->capacity)
{
this->reserve(length);
}
//copy data
memcpy(this->ptr, first, length * sizeof(T));
//reset size
this->size = length;
}
template< typename T >
void Vector< T >::push_back(const T val)
{
// Adds a new element at the end of the vector, after its current last element.
// The content of val is copied to the new element.
// This effectively increases the vector size by one,
// which causes an automatic reallocation of the allocated storage space
// if -and only if- the new vector size surpasses the current vector capacity.
//if cpapcity is not enought to add new element, reallocate memory
if (this->size + 1 > this->capacity)
{
this->reserve(this->size + 1);
}
//push data
*(this->end()) = val;
//increment size
this->size++;
}
template< typename T >
T* Vector< T >::insert(T *position, const T val)
{
// The vector is extended by inserting a new element before the element at the specified position,
// effectively increasing the container size by one.
// This causes an automatic reallocation of the allocated storage space if -and only if-
// the new vector size surpasses the current vector capacity.
// Relocates all the elements that were after position to their new positions.
//if cpapcity is not enought to add new element, reallocate memory
if (this->size + 1 > this->capacity)
{
this->reserve(this->size + 1);
}
//To vacated position, do move data
memmove(position + 1, position, this->end() - position);
//insert data
*position = val;
//increment size
this->size++;
}
template< typename T >
T* Vector< T >::erase(T *position)
{
// Removes from the vector a single element.
// This effectively reduces the container size by one.
// Relocates all the elements after the element erased to their new positions.
//move data to overwrite value which want to earse.
memmove(position, position + 1, (this->end() - 1) - position);
//decrease size
this->size--;
}
| true |
17aee290d2d9a75c364b180eb2cb1eafea28e5cc | C++ | scipianus/Algorithm-contests | /USACO/USACO - February 2012 - Silver/Overplanting/Overplanting.cpp | UTF-8 | 1,557 | 2.734375 | 3 | [] | no_license | /*
PROB: planting
LANG: C++
*/
#include<fstream>
#include<vector>
#define MOD 666013
#define MAX 100000000
using namespace std;
int n;
long long sol;
struct Interval{int st,dr;};
struct Element{int lin; vector <Interval> v;};
vector <Element> Hash[666013];
inline bool Sortare(Interval A,Interval B)
{
if(A.st==B.st)
return A.dr>B.dr;
return A.st<B.st;
}
void Rezolvare()
{
int poz,k,i,st,dr;
long long lg;
vector <Interval> A;
for(poz=0;poz<666013;poz++)
{
if(Hash[poz].size()==0)
continue;
for(k=0;k<Hash[poz].size();k++)
{
A=Hash[poz][k].v;
sort(A.begin(),A.end(),Sortare);
st=A[0].st;
dr=A[0].dr;
for(i=1;i<A.size();i++)
{
if(A[i].st<=dr)
dr=max(A[i].dr,dr);
else
{
lg=(long long)(dr-st+1);
sol+=lg;
st=A[i].st;
dr=A[i].dr;
}
}
lg=(long long)(dr-st+1);
sol+=lg;
}
}
}
int main()
{
int i,j,k,x1,x2,y1,y2,poz;
Interval aux;
Element aux2;
bool gasit;
ifstream fin("planting.in");
fin>>n;
for(i=1;i<=n;i++)
{
fin>>x1>>y1>>x2>>y2;
x1+=MAX;
x2+=MAX;
y1+=MAX;
y2+=MAX;
aux.st=y2;
aux.dr=y1-1;
for(j=x1;j<x2;j++)
{
poz=j%MOD;
gasit=false;
for(k=0;k<Hash[poz].size() && !gasit;k++)
{
aux2=Hash[poz][k];
if(aux2.lin==j)
{
gasit=true;
Hash[poz][k].v.push_back(aux);
}
}
if(!gasit)
{
aux2.lin=j;
aux2.v.clear();
aux2.v.push_back(aux);
Hash[poz].push_back(aux2);
}
}
}
fin.close();
Rezolvare();
ofstream fout("planting.out");
fout<<sol<<"\n";
fout.close();
return 0;
}
| true |
d76fe963f72aa89e482a063a788a6fda2c444e8e | C++ | Tudor67/Competitive-Programming | /LeetCode/Problems/Algorithms/#2360_LongestCycleInAGraph_sol1_dfs_O(N)_time_O(N)_extra_space_174ms_103MB.cpp | UTF-8 | 986 | 3.09375 | 3 | [
"MIT"
] | permissive | class Solution {
private:
void dfs(int node, int level, vector<int>& levelOf, vector<bool>& isInStack, vector<int>& edges, int& res){
levelOf[node] = level;
isInStack[node] = true;
int nextNode = edges[node];
if(nextNode != -1){
if(levelOf[nextNode] == -1){
dfs(nextNode, level + 1, levelOf, isInStack, edges, res);
}else if(isInStack[nextNode]){
res = max(res, levelOf[node] - levelOf[nextNode] + 1);
}
}
isInStack[node] = false;
}
public:
int longestCycle(vector<int>& edges) {
const int N = edges.size();
int res = -1;
vector<int> levelOf(N, -1);
vector<bool> isInStack(N, false);
for(int node = 0; node < N; ++node){
if(levelOf[node] == -1){
dfs(node, 0, levelOf, isInStack, edges, res);
}
}
return res;
}
}; | true |
31e178dfc78bb40f05acc0511efb9e3edf0577eb | C++ | planetarymike/mars_lya_solar_occultation | /interp_1d.h | UTF-8 | 9,769 | 3.078125 | 3 | [] | no_license | //interp_1d.h -- base class for interpolation routines
#include <cmath>
#include "nr3.h"
#ifndef __Interp_H_
#define __Interp_H_
using std::pow;
struct Base_interp
// Abstract base class used by all interpolation routines in this
// chapter. Only interp is called by the user.
{
int n, mmm, jsav, cor, dj;
double *xx, *yy;
Base_interp(VecDoub_I &x, VecDoub_I &y, int m)
// constructor. set up for interpolating on a table of x's and y's
// of length m. Normally called by derived class, not user.
: n(x.size()), mmm(m), jsav(0), cor(0) {
if (n==0) {
xx = NULL;
yy = NULL;
} else {
xx = new double[n];
yy = new double[n];
}
for (int i=0;i<n;i++) {
xx[i]=x[i];
yy[i]=y[i];
}
dj = NR_MIN(1, (int) pow((double) n, 0.25) );
}
Base_interp(const Base_interp &B) {
n=B.n;
mmm=B.mmm;
jsav=B.jsav;
cor=B.cor;
dj=B.dj;
if (n==0) {
xx = NULL;
yy = NULL;
} else {
xx = new double[n];
yy = new double[n];
}
for (int i=0; i<n; i++) {
xx[i]=B.xx[i];
yy[i]=B.yy[i];
}
}
Base_interp&
operator= (const Base_interp &B) {
n=B.n;
mmm=B.mmm;
jsav=B.jsav;
cor=B.cor;
dj=B.dj;
if (n==0) {
xx = NULL;
yy = NULL;
} else {
xx = new double[n];
yy = new double[n];
}
for (int i=0; i<n; i++) {
xx[i]=B.xx[i];
yy[i]=B.yy[i];
}
}
~Base_interp() {
if (n>0) {
delete [] xx;
delete [] yy;
}
}
double interp(double x)
// Given a value x, return an interpolated value, using data
// pointed to by xx and yy.
{
int jlo = cor ? hunt(x) : locate (x);
return rawinterp(jlo, x);
}
int index(double x)
// Given a value x, return an interpolated value, using data
// pointed to by xx and yy.
{
int jlo = cor ? hunt(x) : locate(x);
return jlo;
}
int locate(const double x);
int hunt(const double x);
virtual double rawinterp(int jlo, double x) = 0;
// derived classes provide this as the actual interpolation method used.
};
int Base_interp::locate(const double x)
// given a value x, return a value j such that x is (insofar as
// possible) centered in the subrange xx[j..j+mmm-1], where xx is the
// stored pointer. The values in xx must be monotonic, either
// increasing or decreasing. The returned value is not less than 0,
// nor greater than n-1).
{
int ju, jm, jl;
// std::cout << "n = " << n << ", mmm = " << mmm << "\n";
if (n < 2 || mmm < 2 || mmm > n) {
// std::cout << "n = " << n << ", mmm = " << mmm << std::endl;
throw("locate size error");
}
bool ascnd = (xx[n-1] >= xx[0]); // true if ascending order of
// table, false otherwise
jl = 0;//lower and upper size limits
ju = n-1;
while (ju-jl > 1) { // until the appropriate range is found
jm = (ju+jl) >> 1; // find the midpoint
if (x >= xx[jm] == ascnd)
jl = jm; // and replace either the lower limit
else
ju = jm; // or the upper limit, as appropriate
}
cor = abs(jl-jsav) > dj ? 0 : 1; // decide whether to use hunt() or
// locate() next time
jsav = jl;
return NR_MAX(0,NR_MIN(n-mmm,jl-((mmm-2)>>1)));
}
int Base_interp::hunt(const double x)
// given a value x, return a value j such that x is (insofar as
// possible) centered in the subrange xx[j..j+mmm-1], where xx is the
// stored pointer. The values in xx must be monotonic, either
// increasing or decreasing. The returned value is not less than 0,
// nor greater than n-1).
{
int jl = jsav, jm, ju, inc = 1;
// std::cout << "n = " << n << ", mmm = " << mmm << std::endl;
if (n < 2 || mmm < 2 || mmm > n) {
std::cout << "n = " << n << ", mmm = " << mmm << std::endl;
throw("hunt size error");
}
bool ascnd = (xx[n-1] >= xx[0]); // does table ascend?
if (jl < 0 || jl > n-1) { // input guess not useful. go directly to
// bisection
jl = 0;
ju = n-1;
} else {
if (x >= xx[jl] == ascnd) { // hunt up:
for(;;) {
ju = jl + inc;
if (ju >= n-1) { ju = n-1; break; } // off end of table
else if (x < xx[ju] == ascnd) break; // found bracket
else {
jl = ju;
inc += inc;
}
}
} else { // hunt down:
ju = jl;
for (;;) {
jl = jl - inc;
if (jl <= 0) {jl = 0; break;} // off end of table
else if (x >= xx[jl] == ascnd) break; // found bracket
else {
ju = jl;
inc += inc;
}
}
}
}
while (ju - jl > 1) { // hunt is done, so begin final bisection
jm = (ju+jl) >> 1;
if (x >= xx[jm] == ascnd)
jl = jm;
else
ju = jm;
}
cor = abs(jl - jsav) > dj ? 0 : 1; // decide whether to use hunt or
// locate next time
jsav = jl;
return NR_MAX(0,NR_MIN(n-mmm,jl-((mmm-2)>>1)));
}
struct Linear_interp : Base_interp
// piecewise linear interpolation object. Construct with x and y
// vectors, then call interp for interpolated values
{
Linear_interp(VecDoub_I &xv, VecDoub_I &yv) : Base_interp(xv,yv,2) {}
Linear_interp() : Base_interp(VecDoub(0),VecDoub(0),2) {}
double rawinterp(int j, double x) {
if(xx[j] == xx[j+1]) return yy[j]; // table defective, but recover
else return yy[j] + ((x-xx[j])/(xx[j+1]-xx[j]))*(yy[j+1]-yy[j]);
}
};
struct Poly_interp : Base_interp
// Polynomial interpolation object. Construct with x and y vectors and
// the number M of points to be used locally (polynomial order plus
// one), then call interp for interpolated values.
{
double dy;
Poly_interp(VecDoub_I &xv, VecDoub_I &yv, int m)
: Base_interp(xv, yv,m), dy(0.0) {}
double rawinterp(int jl, double x);
};
double Poly_interp::rawinterp(int jl, double x)
// Given a value x, and using pointers to dara xx and yy, this routine
// returns an interpolated value y, and stores an error estimate
// dy. The returned value is obtained by mmm-point polynomial
// interpolation on the subrange xx[jl..jl+mmm-1]
{
int i, m, ns = 0;
double y, den, dif, dift, ho, hp, w;
const double *xa = &xx[jl], *ya = &yy[jl];
VecDoub c(mmm), d(mmm);
dif = abs(x-xa[0]);
for (i = 0; i < mmm; i++) { // find the index ns of the closest table
// entry
if ((dift = abs(x-xa[i])) < dif) {
ns = i;
dif = dift;
}
c[i] = ya[i];
d[i] = ya[i];
}
y = ya[ns--]; // initial approximataion to y
for (m = 1; m < mmm; m++) { // for each column of the tableau
for (i = 0; i < mmm-m; i++) { // we loop over the current C's and
// D's and update them
ho = xa[i]-x;
hp = xa[i+m]-x;
w = c[i+1]-d[i];
if ((den=ho-hp) == 0.0) throw("Poly_interp error");
den = w/den;
d[i] = hp*den;
c[i] = ho*den;
}
y += (dy = (2*(ns+1) < (mmm-m) ? c[ns+1] : d[ns--]));
// After each column in the tableau is completed, we secide which
// correction, c or d, we want to add to our accumulating value od
// y, i.e. which path to take throught the tableau --- forking up
// or down. We do this in such a way as to take the most "straight
// line" path through the tableau to its apex, updating ns
// accordingly to keep track of where we are. This route keeps the
// partial approximations centered (insofar as is possible) on the
// target x. The last dy added is thus the error indication.
}
return y;
}
/* struct Poly_log_interp : Poly_interp { */
/* // same thing as poly_interp, but in the log-log space */
/* Poly_log_interp(VecDoub_I &xv, VecDoub_I &yv, int m) */
/* : Poly_interp(xv, yv,m) {} */
/* double rawinterp(int jl, double x) */
/* // Given a value x, and using pointers to dara xx and yy, this routine */
/* // returns an interpolated value y, and stores an error estimate */
/* // dy. The returned value is obtained by mmm-point polynomial */
/* // interpolation on the subrange xx[jl..jl+mmm-1] */
/* { */
/* int i, m, ns = 0; */
/* double y, den, dif, dift, ho, hp, w; */
/* const double *xa = &xx[jl], *ya = &yy[jl]; */
/* VecDoub c(mmm), d(mmm); */
/* dif = abs(x-xa[0]); */
/* for (i = 0; i < mmm; i++) { // find the index ns of the closest table */
/* // entry */
/* if ((dift = abs(x=xa[i])) < dif) { */
/* ns = i; */
/* dif = dift; */
/* } */
/* c[i] = ya[i]; */
/* d[i] = ya[i]; */
/* } */
/* y = ya[ns--]; // initial approximataion to y */
/* for (m = 1; m < mmm; m++) { // for each column of the tableau */
/* for (i = 0; i < mmm-m; i++) { // we loop over the current C's and */
/* // D's and update them */
/* ho = xa[i]-x; */
/* hp = xa[i+m]-x; */
/* w = c[i+1]-d[i]; */
/* if ((den=ho-hp) == 0.0) throw("Poly_interp error"); */
/* den = w/den; */
/* d[i] = hp*den; */
/* c[i] = ho*den; */
/* } */
/* y += (dy = (2*(ns+1) < (mmm-m) ? c[ns+1] : d[ns--])); */
/* // After each column in the tableau is completed, we secide which */
/* // correction, c or d, we want to add to our accumulating value od */
/* // y, i.e. which path to take throught the tableau --- forking up */
/* // or down. We do this in such a way as to take the most "straight */
/* // line" path through the tableau to its apex, updating ns */
/* // accordingly to keep track of where we are. This route keeps the */
/* // partial approximations centered (insofar as is possible) on the */
/* // target x. The last dy added is thus the error indication. */
/* } */
/* return std::exp(y); */
/* } */
/* double interp(double x) */
/* // Given a value x, return an interpolated value, using data */
/* // pointed to by xx and yy. */
/* { */
/* x = std::log(x); */
/* int jlo = cor ? hunt(x) : locate (x); */
/* return rawinterp(jlo, x); */
/* } */
/* } */
#endif
| true |
3f11ab8e9e159ad9046358cf7698fd105fb7c97a | C++ | nikiryota0731/robocon2019 | /LCD_big_kai/LCD_big_kai.ino | UTF-8 | 5,594 | 2.515625 | 3 | [] | no_license | #include<LiquidCrystal.h>
#include<Wire.h>
#include"swController.h"
#include"slaveReceiver.h"
LiquidCrystal lcd(7,12,6,11,8,10,9);
bool monitor_flag[4] = {0, 0, 0, 0};
int taswBL_pin = A3, taswB_pin = A2;
int taswR_pin = A0, taswY_pin = A1;
int Red_led_pin = 2, Blue_led_pin = 3;
int tosw_pin = 4;
byte send_data;
bool taswR = 0, taswY = 0, taswBL = 0, taswB = 0, tosw = 0;
bool pageClear1, pageClear2, pageClear3, pageClear4;
bool state1, state2, state3, state4;
//送られてくるデータ
int reciveData1;
int reciveData2;
int reciveData3;
int reciveData4;
byte page;
//slaveのアドレス
const int i2cAddress = 11;
//オブジェクト生成
swController TaswR;
swController TaswY;
swController TaswBL;
swController TaswB;
swController Tosw;
slaveReceiver i2c(9);
void setup()
{
pageClear1 = pageClear2 = pageClear3 = pageClear4 = 0;
Wire.begin(i2cAddress);
Wire.onRequest(requestEvent);
Wire.onReceive(receiveEvent);
Serial.begin(115200);
Wire.setClock(400000UL);
lcd.begin(16, 4);
pinMode(taswR_pin, INPUT_PULLUP);
pinMode(taswY_pin, INPUT_PULLUP);
pinMode(taswBL_pin, INPUT_PULLUP);
pinMode(taswB_pin, INPUT_PULLUP);
pinMode(tosw_pin, INPUT_PULLUP);
pinMode(Blue_led_pin, OUTPUT);
pinMode(Red_led_pin, OUTPUT);
}
void loop()
{
if (page == 0)
{
lcd.setCursor(16, 0);
lcd.print("axis");
lcd.setCursor(0, 0);
lcd.print("Xaxis : ");
lcd.print(reciveData1); lcd.print(" ");
lcd.setCursor(0, 1);
lcd.print("Yaxis : ");
lcd.print(reciveData2); lcd.print(" ");
lcd.setCursor(4, 2);
lcd.print("gyro_now : ");
lcd.print(reciveData3); lcd.print(" ");
lcd.setCursor(4, 3);
lcd.print("gyro_offset : ");
lcd.print(reciveData4); lcd.print(" ");
pageClear2 = 1;
pageClear3 = 1;
pageClear4 = 1;
if (pageClear1)
{
lcd.clear();
pageClear1 = 0;
}
}
//////////////////////////////////////////////////////////////
if (page == 1)
{
lcd.setCursor(17, 0);
lcd.print("pos");
lcd.setCursor(0, 0);
lcd.print("Xaxis : ");
lcd.print(reciveData1); lcd.print(" ");
lcd.setCursor(0, 1);
lcd.print("Yaxis : ");
lcd.print(reciveData2); lcd.print(" ");
lcd.setCursor(4, 2);
lcd.print("moveX : ");
lcd.print(reciveData3); lcd.print(" ");
lcd.setCursor(4, 3);
lcd.print("moveY : ");
lcd.print(reciveData4); lcd.print(" ");
pageClear1 = 1;
pageClear3 = 1;
pageClear4 = 1;
if (pageClear2)
{
lcd.clear();
pageClear2 = 0;
}
}
//////////////////////////////////////////////////////////////
if (page == 2)
{
lcd.setCursor(16, 0);
lcd.print("omni");
lcd.setCursor(0, 0);
lcd.print("MoveX : ");
lcd.print(reciveData1); lcd.print(" ");
lcd.setCursor(0, 1);
lcd.print("MoveY : ");
lcd.print(reciveData2); lcd.print(" ");
lcd.setCursor(4, 2);
lcd.print("TurnX : ");
lcd.print(reciveData3); lcd.print(" ");
lcd.setCursor(4, 3);
lcd.print("NULL : ");
lcd.print(reciveData4); lcd.print(" ");
pageClear1 = 1;
pageClear2 = 1;
pageClear4 = 1;
if (pageClear3)
{
lcd.clear();
pageClear3 = 0;
}
}
//////////////////////////////////////////////////////////////
if (page == 3)
{
lcd.setCursor(15, 0);
lcd.print("motor");
lcd.setCursor(0, 0);
lcd.print("mainRoll : ");
lcd.print(reciveData1); lcd.print(" ");
lcd.setCursor(0, 1);
lcd.print("subRoll : ");
lcd.print(reciveData2); lcd.print(" ");
lcd.setCursor(4, 2);
lcd.print("sheet : ");
lcd.print(reciveData3); lcd.print(" ");
lcd.setCursor(4, 3);
lcd.print("clothesPin : ");
lcd.print(reciveData4); lcd.print(" ");
pageClear1 = 1;
pageClear2 = 1;
pageClear3 = 1;
if (pageClear4)
{
lcd.clear();
pageClear4 = 0;
}
}
//////////////////////////////////////////////////////////////
TaswR.update(digitalRead(taswR_pin));
TaswY.update(digitalRead(taswY_pin));
TaswBL.update(digitalRead(taswBL_pin));
TaswB.update(digitalRead(taswB_pin));
Tosw.update(digitalRead(tosw_pin));
taswR = TaswR.getData();
taswY = TaswY.getData();
taswB = TaswB.getData();
taswBL = TaswBL.getData();
tosw = Tosw.getData();
if (tosw)
{
digitalWrite(Red_led_pin, LOW);
digitalWrite(Blue_led_pin, HIGH);
}
else
{
digitalWrite(Red_led_pin, HIGH);
digitalWrite(Blue_led_pin, LOW);
}
reciveData1 = i2c.getData(0) << 8 | i2c.getData(1);
reciveData2 = i2c.getData(2) << 8 | i2c.getData(3);
reciveData3 = i2c.getData(4) << 8 | i2c.getData(5);
reciveData4 = i2c.getData(6) << 8 | i2c.getData(7);
page = i2c.getData(8);
bitWrite(send_data, 0, tosw);
bitWrite(send_data, 1, taswR);
bitWrite(send_data, 2, taswY);
bitWrite(send_data, 3, taswB);
bitWrite(send_data, 4, taswBL);
// i2c.show();
// Serial.print("RB "); Serial.print(taswR); Serial.print("\t");
// Serial.print("YB "); Serial.print(taswY); Serial.print("\t");
// Serial.print("BB "); Serial.print(taswB); Serial.print("\t");
// Serial.print("BLB "); Serial.print(taswBL); Serial.print("\t");
// Serial.print(tosw); Serial.print("\t");
// Serial.print(reciveData1); Serial.print("\t");
// Serial.print(reciveData2); Serial.print("\t");
// Serial.print(reciveData3); Serial.print("\t");
// Serial.print(reciveData4); Serial.print("\t");
Serial.print(page);
// Serial.print(send_data, BIN);
Serial.println("");
}
void requestEvent()
{
Wire.write(send_data);
}
void receiveEvent(int any)
{
i2c.Update();
}
| true |
b39312dd7848bab2115dbfc3b09c073416368bec | C++ | mephi-student/laba3_new | /main.cpp | UTF-8 | 11,469 | 3.21875 | 3 | [] | no_license | #define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "binarytree.hpp"
#include "binarytree.cpp"
#include "functions.cpp"
#include "functions.hpp"
#include <random>
double randDouble(double n1, double n2) {
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<double> dist(n1, n2);
return dist(mt);
}
int randInt(int n1, int n2) {
return round(randDouble(n1, n2));
}
std::string randString(int n1, int n2) {
int N = randInt(n1, n2);
std::string buf = "abcdefghijklmnopqrstuvwxyz";
std::string result = "";
for (int i = 0; i < N; i++) {
result += buf[randInt(0, sizeof(buf) - 1)];
}
return result;
}
TEST_CASE("Test binary tree random INT") {
/* Тестируется создание древа через заполнение случайными числами */
Tree<int> tree;
for (int i = 0; i < 100; ++i) {
tree.push(randInt(-100, 100));
}
SECTION("Test length") {
CHECK(tree.getLength() == 100);
}
SECTION("Test push") {
CHECK(tree.getLength() == 100);
tree.push(randInt(-100, 100));
CHECK(tree.getLength() == 101);
}
SECTION("Test delete") {
int number = randInt(-100, 100);
CHECK(tree.getLength() == 100);
tree.push(number);
CHECK(tree.getLength() == 101);
tree.deleteNode(number);
CHECK(tree.getLength() == 100);
}
SECTION("Test check") {
CHECK(tree.getLength() == 100);
tree.push(0);
CHECK(tree.getLength() == 101);
CHECK(tree.checkPresence(0) == true);
}
}
TEST_CASE("Test binary tree random DOUBLE") {
/* Тестируется создание древа через заполнение случайными числами */
Tree<double> tree;
for (double i = 0; i < 100; ++i) {
tree.push(randDouble(-100, 100));
}
SECTION("Test length") {
CHECK(tree.getLength() == 100);
}
SECTION("Test push") {
CHECK(tree.getLength() == 100);
tree.push(randDouble(-100, 100));
CHECK(tree.getLength() == 101);
}
SECTION("Test delete") {
double number = randDouble(-100, 100);
CHECK(tree.getLength() == 100);
tree.push(number);
CHECK(tree.getLength() == 101);
tree.deleteNode(number);
CHECK(tree.getLength() == 100);
}
SECTION("Test check") {
double number = randDouble(-100, 100);
CHECK(tree.getLength() == 100);
tree.push(number);
CHECK(tree.getLength() == 101);
CHECK(tree.checkPresence(number) == true);
}
}
TEST_CASE("Test binary tree random STRING") {
/* Тестируется создание древа через заполнение случайными числами */
Tree<std::string> tree;
for (int i = 0; i < 100; ++i) {
tree.push(randString(10, 20));
}
SECTION("Test length") {
CHECK(tree.getLength() == 100);
}
SECTION("Test push") {
CHECK(tree.getLength() == 100);
tree.push(randString(-100, 100));
CHECK(tree.getLength() == 101);
}
SECTION("Test delete") {
std::string str = randString(10, 20);
CHECK(tree.getLength() == 100);
tree.push(str);
CHECK(tree.getLength() == 101);
tree.deleteNode(str);
CHECK(tree.getLength() == 100);
}
SECTION("Test check") {
std::string str = randString(10, 20);
CHECK(tree.getLength() == 100);
tree.push(str);
CHECK(tree.getLength() == 101);
CHECK(tree.checkPresence(str) == true);
}
}
TEST_CASE("Test binary tree fixed INT") {
std::vector<int> data = {4, 10, 1, 13, 43, 19, 12, 3};
Tree<int> tree;
for (auto i : data) {
tree.push(i);
}
SECTION("Test getLength") {
CHECK(tree.getLength() == 8);
}
SECTION("Test traverse") {
CHECK(tree.getStringPLK() == "19 43 12 13 10 3 1 4 ");
CHECK(tree.getStringKLP() == "4 1 3 10 13 12 43 19 ");
}
SECTION("Test checkPresence key") {
for (auto i : data) {
CHECK(tree.checkPresence(i) == true);
}
CHECK(tree.checkPresence(-42342) == false);
}
SECTION("Test checkPresence tree") {
std::vector<int> newData = {13, 12, 43, 19};
Tree<int> newTree;
for (auto i : newData) {
newTree.push(i);
}
CHECK(tree.checkPresence(newTree) == true);
newTree.push(342);
CHECK(tree.checkPresence(newTree) == false);
}
SECTION("Test getSubtree") {
Tree<int> subtree = tree.getSubTree(10);
CHECK(subtree.getStringPLK() == "19 43 12 13 10 ");
CHECK(subtree.getStringKLP() == "10 13 12 43 19 ");
CHECK(subtree.getLength() == 5);
}
SECTION("Test map 1") {
Tree<int> mapped = tree.map(intPlusOne);
CHECK(mapped.getStringPLK() == "20 44 13 14 11 4 2 5 ");
CHECK(mapped.getStringKLP() == "5 2 4 11 14 13 44 20 ");
}
SECTION("Test map 2") {
Tree<int> mapped = tree.map(intMinusTen);
CHECK(mapped.getStringPLK() == "9 33 2 3 0 -7 -9 -6 ");
CHECK(mapped.getStringKLP() == "-6 -9 -7 0 3 2 33 9 ");
}
SECTION("Test where 1") {
Tree<int> whered = tree.where(intIfEven);
CHECK(whered.getStringPLK() == "12 10 4 ");
CHECK(whered.getStringKLP() == "4 10 12 ");
CHECK(whered.getLength() == 3);
}
SECTION("Test where 2") {
Tree<int> whered = tree.where(intIfOdd);
CHECK(whered.getStringPLK() == "19 43 13 3 1 ");
CHECK(whered.getStringKLP() == "1 3 13 43 19 ");
CHECK(whered.getLength() == 5);
}
SECTION("Test compareTrees") {
Tree<int> newTree;
for (auto i : data) {
newTree.push(i);
}
CHECK(tree.compareTrees(newTree) == true);
newTree.deleteNode(10);
CHECK(tree.compareTrees(newTree) == false);
}
}
TEST_CASE("Test binary tree fixed DOUBLE") {
std::vector<double> data = {4.2, 10.4, 1.5, 13.1, 43.8, 19.6, 12.9, 3.3};
Tree<double> tree;
for (auto i : data) {
tree.push(i);
}
SECTION("Test getLength") {
CHECK(tree.getLength() == 8);
}
SECTION("Test traverse") {
CHECK(tree.getStringPLK() == "19.6 43.8 12.9 13.1 10.4 3.3 1.5 4.2 ");
CHECK(tree.getStringKLP() == "4.2 1.5 3.3 10.4 13.1 12.9 43.8 19.6 ");
}
SECTION("Test checkPresence key") {
for (auto i : data) {
CHECK(tree.checkPresence(i) == true);
}
CHECK(tree.checkPresence(-423.42) == false);
}
SECTION("Test checkPresence tree") {
std::vector<double> newData = {13.1, 12.9, 43.8, 19.6};
Tree<double> newTree;
for (auto i : newData) {
newTree.push(i);
}
CHECK(tree.checkPresence(newTree) == true);
newTree.push(342.2);
CHECK(tree.checkPresence(newTree) == false);
}
SECTION("Test getSubtree") {
Tree<double> subtree = tree.getSubTree(10.4);
CHECK(subtree.getStringPLK() == "19.6 43.8 12.9 13.1 10.4 ");
CHECK(subtree.getStringKLP() == "10.4 13.1 12.9 43.8 19.6 ");
CHECK(subtree.getLength() == 5);
}
SECTION("Test map 1") {
Tree<double> mapped = tree.map(doublePlusOne);
CHECK(mapped.getStringPLK() == "20.6 44.8 13.9 14.1 11.4 4.3 2.5 5.2 ");
CHECK(mapped.getStringKLP() == "5.2 2.5 4.3 11.4 14.1 13.9 44.8 20.6 ");
}
SECTION("Test map 2") {
Tree<double> mapped = tree.map(doubleMinusTen);
CHECK(mapped.getStringPLK() == "9.6 33.8 2.9 3.1 0.4 -6.7 -8.5 -5.8 ");
CHECK(mapped.getStringKLP() == "-5.8 -8.5 -6.7 0.4 3.1 2.9 33.8 9.6 ");
}
SECTION("Test where 1") {
Tree<double> whered = tree.where(doubleIfLargerThanTen);
CHECK(whered.getStringPLK() == "19.6 43.8 12.9 13.1 10.4 ");
CHECK(whered.getStringKLP() == "10.4 13.1 12.9 43.8 19.6 ");
CHECK(whered.getLength() == 5);
}
SECTION("Test where 2") {
Tree<double> whered = tree.where(doubleIfLesserThanFive);
CHECK(whered.getStringPLK() == "3.3 1.5 4.2 ");
CHECK(whered.getStringKLP() == "4.2 1.5 3.3 ");
CHECK(whered.getLength() == 3);
}
SECTION("Test compareTrees") {
Tree<double> newTree;
for (auto i : data) {
newTree.push(i);
}
CHECK(tree.compareTrees(newTree) == true);
newTree.deleteNode(10.4);
CHECK(tree.compareTrees(newTree) == false);
}
}
TEST_CASE("Test binary tree fixed STRING") {
std::vector<std::string> data = {"father", "MOTHER", "sister", "BROTHER", "book", "ham", "priEST", "government"};
Tree<std::string> tree;
for (auto i : data) {
tree.push(i);
}
SECTION("Test getLength") {
CHECK(tree.getLength() == 8);
}
SECTION("Test traverse") {
CHECK(tree.getStringPLK() == "priEST government ham sister book BROTHER MOTHER father ");
CHECK(tree.getStringKLP() == "father MOTHER BROTHER book sister ham government priEST ");
}
SECTION("Test checkPresence key") {
for (auto i : data) {
CHECK(tree.checkPresence(i) == true);
}
CHECK(tree.checkPresence("severity") == false);
}
SECTION("Test checkPresence tree") {
std::vector<std::string> newData = {"ham", "priEST", "government"};
Tree<std::string> newTree;
for (auto i : newData) {
newTree.push(i);
}
CHECK(tree.checkPresence(newTree) == true);
newTree.push("chak chak");
CHECK(tree.checkPresence(newTree) == false);
}
SECTION("Test getSubtree") {
Tree<std::string> subtree = tree.getSubTree("sister");
CHECK(subtree.getStringPLK() == "priEST government ham sister ");
CHECK(subtree.getStringKLP() == "sister ham government priEST ");
CHECK(subtree.getLength() == 4);
}
SECTION("Test map 1") {
Tree<std::string> mapped = tree.map(stringChangeRegister);
CHECK(mapped.getStringPLK() == "brother PRIest GOVERNMENT HAM SISTER mother BOOK FATHER ");
CHECK(mapped.getStringKLP() == "FATHER BOOK mother SISTER HAM GOVERNMENT PRIest brother ");
}
SECTION("Test map 2") {
Tree<std::string> mapped = tree.map(stringMakeLoud);
CHECK(mapped.getStringPLK() == "priEST! government! ham! sister! book! BROTHER! MOTHER! father! ");
CHECK(mapped.getStringKLP() == "father! MOTHER! BROTHER! book! sister! ham! government! priEST! ");
}
SECTION("Test where 1") {
Tree<std::string> whered = tree.where(stringIfLargerThanEight);
CHECK(whered.getStringPLK() == "government ");
CHECK(whered.getStringKLP() == "government ");
CHECK(whered.getLength() == 1);
}
SECTION("Test where 2") {
Tree<std::string> whered = tree.where(stringIfLesserThanSix);
CHECK(whered.getStringPLK() == "ham book ");
CHECK(whered.getStringKLP() == "book ham ");
CHECK(whered.getLength() == 2);
}
SECTION("Test compareTrees") {
Tree<std::string> newTree;
for (auto i : data) {
newTree.push(i);
}
CHECK(tree.compareTrees(newTree) == true);
newTree.deleteNode("book");
CHECK(tree.compareTrees(newTree) == false);
}
}
| true |