PR2004 from the 2004 AP Computer Science exam has you working with an array of integers to model a robot cleaning up a hallway. The robot keeps going until there are no more “toys” in the hallway. That is, all elements in the integer array are 0.
Here’s the shell class for Robot
.
Part A
For the first part we’re implementing forwardMoveBlocked
. This method should return true if the robot cannot move in the direction it’s facing.
If the robot is facingRight
and is at the rightmost side of the array, he can’t move. Same is true if he’s facing left – !facingRight
– and pos
is 0
. Otherwise it returns false
.
Part B
The move
method, well, moves the robot according to the following rules. A move is one of the following.
- If there are items in the current position, 1 is removed
- If there are no items and can move, move
- If cannot move, turn around.
What caught me is that after removing an item, if that spot is 0 then the robot moves. So, it can both remove an item and move to the next spot in a single move.
So what I did was to check if there’s a toy at the current position. If there is, remove one. After removing it, check if all the toys are removed from that position. If it is, try to move or turn around if the robot can’t move.
Part C
clearHall
keeps moving until the hall is entirely clear – all elements are zero – and counts how many moves it took.
Want to stay in touch and keep up to date with the latest posts @ CompSci.rocks?