# PR2004 Robot Solution

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.

public class Robot {
private int[] hall;
private int pos;
private boolean facingRight;

public boolean forwardMoveBlocked() { // part A }
private void move() { // part B }
public int clearHall() { // part C }
private boolean hallIsClear() {
// implementation not shown
}
}

### 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.

private boolean forwardMoveBlocked() {
if (facingRight && pos >= hall.length - 1)
return true;
else if (!facingRight && pos == 0)
return true;
return false;
}

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.

private void move() {
if (hall[pos] > 0)
hall[pos]--;
if (hall[pos] == 0) {
if (forwardMoveBlocked()) {
facingRight = !facingRight;
}
else if (facingRight) {
pos++;
}
else {
pos--;
}
}
}

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.

public int clearHall() {
int cnt = 0;
while (!hallIsClear()) {
move();
cnt++;
}
return cnt;
}