Reputation: 83
This is homework. I got a robot that travels a grid. I need to store every coordinates he visits and then check if he has visited them before. Right now i am storing the coordinates in a Pair but how can i store the Pair in a list/array so i can compare later coordinates he visits with it and add it to the list if he has not been there before?
Here is my code.
#include <iostream>
#include <array>
#include <utility>
#include <list>
using namespace std;
void check (pair<int, int> foo)
{
int points[10000];
cout << "x " <<foo.first;
cout << "y "<< foo.second << endl;
}
int main()
{
int numberOfLines = 0;
string strDirection;
int counter = 0;
cin >> numberOfLines;
do
{
counter++;
int tempStrSize = 0;
int y = 0;
int x = 0;
int intDirection = 0;
cin >> strDirection;
tempStrSize = strDirection.size();
char direction[tempStrSize];
pair<int, int> foo;
for(int i = 0; i<tempStrSize; i++)
{
direction[i] = strDirection.at(i);
}
for (int i = 0; i < tempStrSize; i++)
{
if(direction[i] == 'h' || direction[i] == 'H')
{
if(intDirection == 3)
{
intDirection = 0;
}
else if(intDirection != 3)
{
intDirection++;
}
}
else if(direction[i] == 'v' || direction[i] == 'V')
{
if(intDirection == 0)
{
intDirection = 3;
}
else if(intDirection != 0)
{
intDirection--;
}
}
else if(direction[i] == 'f' || direction[i] == 'F')
{
if(intDirection == 0)
{
y++;
foo = make_pair(x,y);
}
if(intDirection == 1)
{
x++;
foo = make_pair(x,y);
}
if(intDirection == 2)
{
y--;
foo = make_pair(x,y);
}
if(intDirection == 3)
{
x--;
foo = make_pair(x,y);
}
}
check(foo);
}
cout << endl;
cout << x << " " << y << endl;
}
while(counter < numberOfLines);
return 0;
}
Upvotes: 0
Views: 1674
Reputation: 42746
I would use a Map or an unordered_map:
#include <unordered_map>
unordered_map<pair<int, int>,bool> visitedPoints;
bool checkVisited(pair<int, int> &coords)
{
return visitedPoints.find(coords) != visitedPoints.end();
}
void addVisited(pair<int, int> &coords)
{
if(!checkVisited(coords)) visitedPoints[coords] = true;
}
Just to check if the pair is in the map and save the visited points.
Upvotes: 1