StoneMasonKarel Solution

So the second assignment is a bit harder and requires some “while” and “if” logic. Here is the problem:

Here is my solution:


Update: I’ve had several people email me and say that this is not the fully correct solution. Although my solution works in Karel’s current world, you can’t assume the columns he’s stoning are 5 units high. Check out the comments for some better solutions or post your own!

<pre>/*
 * File: StoneMasonKarel.java
 * --------------------------
 * The StoneMasonKarel subclass as it appears here does nothing.
 * When you finish writing it, it should solve the "repair the quad"
 * problem from Assignment 1.  In addition to editing the program,
 * you should be sure to edit this comment so that it no longer
 * indicates that the program does nothing.
 */

import stanford.karel.*;

public class StoneMasonKarel extends SuperKarel {

	public void run () {
		while (frontIsClear()) {
			BeeperUp();
			MoveUp();
			BeeperDown();
			MoveDown();
		}
	}
	private void BeeperUp() {
		turnLeft();
		while (frontIsClear()) {
			if (noBeepersPresent()) {
			putBeeper();
			}
			move();
		}
	}
	private void BeeperDown() {
		turnRight();
		while (frontIsClear()) {
			if (noBeepersPresent()) {
			putBeeper();
			}
			move();
		}
	}
	private void MoveUp() {
		turnRight();
		for (int i=0; i<4; i++) {
			move();
		}
	}
	private void MoveDown() {
		turnLeft();
		if (frontIsClear()) {
			for (int i=0; i<4; i++) {
				move();
			}
		}
	}
}</pre>

I will try to put in more explanation for what my logic is for future solution. This one took me a while to figure out, and I was really really proud when I made it work!

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.