1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
#include <iostream> #include <string> class MarsRover { public: MarsRover(int x = 0, int y = 0, char direction = 'N') : x(x), y(y), direction(direction) {} void move(const std::string& commands) { for (char command : commands) { switch (command) { case 'L': turnLeft(); break; case 'R': turnRight(); break; case 'M': moveForward(); break; default: std::cerr << "Invalid command: " << command << "\n"; break; } } } void printPosition() const { std::cout << "Rover Position: (" << x << ", " << y << "), Facing: " << direction << "\n"; } private: int x, y; char direction; void turnLeft() { switch (direction) { case 'N': direction = 'W'; break; case 'W': direction = 'S'; break; case 'S': direction = 'E'; break; case 'E': direction = 'N'; break; } } void turnRight() { switch (direction) { case 'N': direction = 'E'; break; case 'E': direction = 'S'; break; case 'S': direction = 'W'; break; case 'W': direction = 'N'; break; } } void moveForward() { switch (direction) { case 'N': ++y; break; case 'E': ++x; break; case 'S': --y; break; case 'W': --x; break; } } }; int main() { MarsRover rover; std::string commands; std::cout << "Enter commands for the rover (L = turn left, R = turn right, M = move forward): "; std::cin >> commands; rover.move(commands); rover.printPosition(); return 0; } |
Explanation
- Class Definition (
MarsRover
):- Private Members:
x
andy
: Coordinates of the rover on a 2D grid.direction
: The direction the rover is facing (N
for North,E
for East,S
for South,W
for West).
- Public Methods:
MarsRover(int x, int y, char direction)
: Constructor to initialize the rover’s position and direction.void move(const std::string& commands)
: Processes a string of commands (L
for turn left,R
for turn right,M
for move forward).- Calls
turnLeft()
,turnRight()
, ormoveForward()
based on each command.
- Calls
void printPosition() const
: Prints the rover’s current position and direction.
- Private Methods:
void turnLeft()
: Changes the rover’s direction when turning left.void turnRight()
: Changes the rover’s direction when turning right.void moveForward()
: Moves the rover one unit forward in the direction it is facing.
- Private Members:
main
Function:- Creates a
MarsRover
object with default initialization. - Prompts the user to enter a string of commands.
- Executes the commands using the
move
method. - Prints the final position and direction of the rover.
- Creates a