cs106a – Assignment #1 – Task #3

In this exercise, your job is to get Karel to create a checkerboard pattern of beepers inside an empty rectangular world, as illustrated in the following before-and-after diagram:

cs106 – assignment #1 – task #3 – 8×8

This problem has a nice decomposition structure along with some interesting algorithmic issues. As you think about how you will solve the problem, you should make sure that your solution works with checkerboards that are different in size from the standard 8×8 checkerboard shown in the example. Odd-sized checkerboards are tricky, and you should make sure that your program generates the following pattern in a 5×3 world:
cs106 – assignment #1 – task #3 – 5×3

Another special case you need to consider is that of a world which is only one column wide or one row high. The starter folder contains several sample worlds that test these special cases, and you should make sure that your program works for each of them.


Start by working on the first row which by definition has a beeper at the first position. Then face north and continue as long as the top has not been reached. If a beeper is present, the next row is an even one (starting with a beeper at the second position), if not it is an odd one (starting with a beeper at the first position). Move up, face into direction of the row and work:

	public void run() {
		oddRow();
		faceNorth();
		while (frontIsClear()) {
			if (beepersPresent()) {
				move();
				faceRow();
				evenRow();
			} else {
				move();
				faceRow();
				oddRow();
			}
			faceNorth();
		}
	}

As mentioned before an odd row has a beeper at the first position. Then – if possible – move two positions and plant the next beeper:

	private void oddRow() {
		putBeeper();
		while(frontIsClear()) {
			move();
			if (frontIsClear()) {
				move();
				putBeeper();
			}
 		}
	}

An even row starts with the second position:

	private void evenRow() {
		while(frontIsClear()) {
			move();
			putBeeper();
			if (frontIsClear()) {
				move();
			}
 		}
	}

To face into direction of the row, assume Karel faces north and check if the right or left is blocked:

	private void faceRow() {
		if (rightIsBlocked()) {
			turnLeft();
		} else if (leftIsBlocked()) {
			turnRight();
		} 		
	}	

To face north, just check if Karel currently faces east or west and turn accordingly:

	private void faceNorth() {
		if (facingEast()) {
			turnLeft();
		} else if (facingWest()) {
			turnRight();
		} 		
	}

The code for this assignment is available on github.

FacebooktwitterredditpinterestlinkedintumblrmailFacebooktwitterredditpinterestlinkedintumblrmail

Leave a Reply

Your email address will not be published.