Problem written by Eric Roberts
Handouts:
KarelReference
Day1: InvertBeepers.java
For a world of any size, with any configuration of beepers (no square will have more than one), invert all the beepers so that, where there was a beeper previously there is no beeper... and where there was no beeper previously, there is a beeper. Consider the following example.
/**
* Program: Invert
* ---------------
* Invert all the beepers so that, where there was a beeper previously
* there is no beeper... and where there was no beeper previously, there is a
* beeper.
*/
public class InvertBeepers extends SuperKarel {
public void run() {
invertRow();
returnToWest();
while(leftIsClear()) {
turnLeft();
move();
turnRight();
invertRow();
returnToWest();
}
}
/**
* Method: Invert Row
* ------------------
* Invert a single row. At the start, Karel should be facing east from
* the west side of the row. After Karel should be facing east from the
* east side of the same row, and all beepers in the row will be inverted.
*/
private void invertRow() {
while(frontIsClear()) {
invertBeeper();
move();
}
invertBeeper();
}
/**
* Method: Invert Beeper
* --------------------
* Inverts the beeper configuration on a square. If there was previously
* a beeper, it is picked up. If there was previously no beeper, a beeper
* is placed.
*/
private void invertBeeper() {
if(beepersPresent()) {
pickBeeper();
} else {
putBeeper();
}
}
/**
* Method: Return To West
* ----------------------
* Turn around and go back to the wall that you came from!
*/
private void returnToWest() {
turnAround();
while(frontIsClear()) {
move();
}
turnAround();
}
}