Im working on a C program that simulates a robot on a grid T
I\'m working on a C++ program that simulates a robot on a grid. The grid has a pre-designated \"goal\" position to be found. There is a time limit as to how long the simulation of the bot on the grid is allowed. The simulation ends when either the Bot finds the goal or when the limit of simulation steps is reached.
So far I know that there will be atleast two classes: one for the grid and one for the bot. The grid is a square that has (x,y) coordinates that contain the goal position. The bottom left corner of the grid is (0,0). The x and y are both greater than or equal to 0. The dimensions of the grid and the goal position are provided as input (How do I represent this in my class?). The grid has no wrap around so if the bot moves into a wall the position doesn\'t change and it moves on to the next command.
Right now I\'m just trying to figure out how to set up this grid class.
Solution
#include <iostream>
#include<string>
using namespace std;
#include <map>
class Grid
{
private:
int nrow;
int ncol;
int goal_x;
int goal_y;
int *grid; // we will represent matrix as a pointer
public:
Grid(int _nrow, int _ncols, int _goal_x, int _goal_y){
nrow = _nrow;
ncol = _ncols;
goal_x = _goal_x;
goal_y = _goal_y;
grid = new int[nrow*ncol]; // allocate memory for grid
for (int i = 0; i < nrow; ++i)
{
for (int j = 0; j < ncol; ++j)
{
grid[i*ncol + j] = 0; // reset all to 0
}
}
}
void print_goal(){
cout << \" x and y co-ordinates of goal are \" << goal_x << \" \" << goal_y << endl;
}
void set_robot(int x, int y){
// reset the grid and set robot position as 1
for (int i = 0; i < nrow; ++i)
{
for (int j = 0; j < ncol; ++j)
{
grid[i*ncol + j] = 0;
}
}
grid[x*ncol + y] = 1;
}
void get_robot(){
// reset the grid and set robot position as 1
for (int i = 0; i < nrow; ++i)
{
for (int j = 0; j < ncol; ++j)
{
if(grid[i*ncol + j] == 1){
cout << \" robot co-ordinates are \" << i << \" \" << j << endl;
}
}
}
}
};
int main(int argc, char const *argv[])
{
Grid g(10,10,5,5);
g.print_goal();
g.set_robot(3,6);
g.get_robot();
return 0;
}
OUTPUT
x and y co-ordinates of goal are 5 5
robot co-ordinates are 3 6