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 17,500+ Swift developers and enthusiasts who get my weekly updates.

  • nick

    this doesn’t solve the problem i’m afraid!

    i’m very new to this, so i can’t tell you the right way yet, but the columns can be *different* heights. if you lower one column below the first you get an error. i’ll see if i can find the answer.

    • nick

      finally got it, hope this helps someone:

      import stanford.karel.*;
      
      public class StoneMasonKarel extends SuperKarel {
      
      	public void run () {
      		while (frontIsClear()) {
      			turnLeft();
      			fixColumn();
      			returnToStart();
      			moveToNext();
      		}
      		fixLastColumn();
      	}
      	
      	private void fixColumn() {
      		while (frontIsClear()) {
      			if (noBeepersPresent()) {
      				putBeeper();
      			} else { 
      				move();
      			}
      		}
      	}
      	
      	private void returnToStart() {
      		turnAround();
      		fixColumn();
      		turnLeft();
      	}
      	
      	private void moveToNext() {
      		for (int x=0; x<4; x++) {
      			move();
      		}
      	}
      	
      	private void fixLastColumn() {
      		if (leftIsBlocked()){
      			if (noBeepersPresent()) {
      				putBeeper();
      		} else {
      			turnLeft();
      			fixColumn();
      			returnToStart();
      		}
      		}
      	}
      }
      
      • you can put the following tags around your code so it’s nicer to read:

        [sourcecode language=""css""]

        //your code goes here

        [/sourcecode]

        Thanks for sharing!

    • Looks like you are correct. Karel needs to first check if there is a wall above or below it once it reaches a new column, and if there isn’t, Karel needs to clean up the extra beepers above / below it.

  • nick

    oh, and thanks for the site btw, very useful!

    • Glad you like it 🙂 I started it because I had a hard time finding some of the solutions myself. The disclaimer of course is that I’m a newbie just like everyone else, so if you find mistakes, definitely let me know like you did just now.

  • Sanjay Singh

    Code posted by nick does not work. It has quite few flaws and does not work under other worlds. My code for same is given below, it factors all of conditions required in Assignment file :

     
    import stanford.karel.*;
    
    public class StoneMasonKarel extends SuperKarel {
    
    	public void run() {
    		while (facingEast()) {
    			ascendColumn();
    			descendColumn();
    			moveFourSteps();
    		}
    		turnLeft();
    	}
    
    	private void ascendColumn() {
    		if (leftIsClear()) {
    			turnLeft();
    			while (frontIsClear()) {
    				move();
    			}
    			turnAround();
    		} else {
    			dropBeeper();
    
    		}
    	}
    
    	private void descendColumn() {
    		if (facingSouth()) {
    			dropBeeper();
    			while (frontIsClear()) {
    				move();
    				dropBeeper();
    			}
    			if (leftIsClear()) {
    				turnLeft();
    			}
    		}
    	}
    
    	private void dropBeeper() {
    		if (noBeepersPresent()) {
    			putBeeper();
    		}
    	}
    
    	private void moveFourSteps() {
    		if (frontIsClear()) {
    			for (int i = 0; i < 4; i++) {
    				move();
    			}
    		}
    	}
    }
    
     
    
  • Sanjay Singh
    import stanford.karel.*;
    
    public class StoneMasonKarel extends SuperKarel {
    
    	public void run() {
    		while (facingEast()) {
    			ascendColumn();
    			descendColumn();
    			moveFourSteps();
    		}
    		turnLeft();
    	}
    
    	private void ascendColumn() {
    		if (leftIsClear()) {
    			turnLeft();
    			while (frontIsClear()) {
    				move();
    			}
    			turnAround();
    		} else {
    			dropBeeper();
    
    		}
    	}
    
    	private void descendColumn() {
    		if (facingSouth()) {
    			dropBeeper();
    			while (frontIsClear()) {
    				move();
    				dropBeeper();
    			}
    			if (leftIsClear()) {
    				turnLeft();
    			}
    		}
    	}
    
    	private void dropBeeper() {
    		if (noBeepersPresent()) {
    			putBeeper();
    		}
    	}
    
    	private void moveFourSteps() {
    		if (frontIsClear()) {
    			for (int i = 0; i &lt; 4; i++) {
    				move();
    			}
    		}
    	}
    }
    
  • Pingback: Stanford CS106a Assignment 1 – Problem #2 « Programming…()

  • Thanks for a great blog for us doing CS106a through iTunes U. Here is my solution, also posted here: http://programzero.wordpress.com/2012/02/18/stanford-cs106a-assignment-1-problem-2/

    import stanford.karel.*;
    
    public class StoneMasonKarel extends SuperKarel {
    	public void run(){
    		while(frontIsClear()){	//Karel will do this loop as ong as its front is clear
    			fixColumn();
    			moveToNext();
    		}
    		fixColumn(); //To fix the last column, avoid OBOB
    	}
    
    	//Moves Karel to next column. Pre cond: facing east
    	private void moveToNext() {
    		for (int i=0; i<4; i++){
    			move();
    		}
    
    	}
    
    	//Makes Karel fix one column. Pre cond: facing east.
    	//End condition: facing east
    	private void fixColumn(){
    		turnLeft();
    		while(frontIsClear()){			//If the front is clear
    			if(beepersPresent()){		//AND any beepers present at current corner
    				move();					//Karel will move
    			}
    
    			else{						//if not, he will put a beeper and move
    				putBeeper();
    				move();
    			}
    		}
    
    		if(noBeepersPresent()){ //fixes the top of the column
    			putBeeper();
    		}
    		returnToBottom();
    		turnLeft();
    	}
    
    	//Makes Karel return to bottom om column. Pre cond: facing North
    	//End cond: facing south, 1st avenue
    	private void returnToBottom(){
    		turnAround();
    		while(frontIsClear()){
    			move();
    		}
    	}
    }
  • Dear Natasha,

    I appreciate your site very much!
    It is very clearly set up and I enjoy all the aids you provide.
    I’ve just started the CS106A myself but have a hard tme concentrating on it 100% (I also have a full-time job and 4 kids so you can imagine 😉 )
    Anyway, at this time I am struggling with the second assignment and looked at your solutions here, I hope they wilol help me understand better and find my own original solution, I only have experience with programming RPG on IBM-AS400 systems and that is quite different.

    I guess I will gbe comming back here a lot so I just wanted to say that your efforts are appreciated!
    Thanks!

    Tamar

    • Hi Tamar,

      Glad to hear you find these helpful 🙂 Keep going with the course – it is definitely worth it! The first few assignments are extra hard to “weed out” the weak students in the class, since this is Stanford, but after the third assignment it gets A LOT easier.

      Best,
      Natasha

  • Tamar

    Just changed my program and it is working much better, it really helps looking at other persons solutions to start understanding the stuff better, i am enjoying it very much, too bad i have only about two hours each week, but at least i print out the code and think of ideas on the bus, which can be very helpfull if i dont fall asleep on the way 😉

    • Scott

      So, looks like “ProgrammingZero” nailed it. I finally got mine working. It isn’t as bulletproof, but I got it working for a few “worlds” and I thought I’d share anyways. I’m glad to see others out there taking this course and I’m glad we can all learn from each other. Thanks for the site!

      import stanford.karel.SuperKarel;
      
      public class StoneMasonKarel extends SuperKarel {
      	public void run(){
      		turnLeft();
      		putBeeper();
      		placeIfNoBeepersFound();
      		runGauntlet();
      	}
      	
      	private void placeIfNoBeepersFound() {
      		while (frontIsClear()){
      			move();
      			if(noBeepersPresent()) {
      			  putBeeper();
      			  }
      		}
      	}
      
      	private void runGauntlet() {
      		for(int i=0; i<5; i++){
      		turnIfBlocked();
      		moveEveryFour();
      		}
      	}
      	
      	private void turnIfBlocked() {
      		while (frontIsBlocked()) {
      			if (facingNorth() && rightIsClear()) {
      				turnRight();
      			} else if (facingEast() && rightIsClear()) {
      				turnRight();
      				move();
      				turnRight();
      					if (noBeepersPresent()){
      						putBeeper();
      					}
      			} else if (facingWest() && leftIsClear()) {
      				turnLeft();
      				move();
      				turnLeft();
      					if (noBeepersPresent()){
      						putBeeper();
      						}
      			} else if (facingWest() && leftIsBlocked()) {
      				turnAround();
      					if (noBeepersPresent()){
      						putBeeper();
      						}			
      				} else if (frontIsClear()) {
      			moveEveryFour();
      			}
      		}
      	}
      
      	private void moveEveryFour() {
      		while (frontIsClear()) {
      			for(int j=0; j<4; j++){
      				move();
      			}
      			if (noBeepersPresent()) {
      			putBeeper();			
      			}
      		}
      	}
      }
      
      • Thanks for sharing Scott! My answers may or may not be “correct” 🙂

  • Tyler

    Thanks for having this, will certainly be nice to feel like I have a classmate while watching the videos on YouTube.

    I was trying to figure out how to make it more efficient and it seems like ProgrammingZero’s example is what I was looking for, needed some more ifs and elses.

    /*
    
     * File: StoneMasonKarel.java
    
     * --------------------------
    
     * The StoneMasonKarel subclass as it appears here does nothing.
    
     * When you finish writing it, it should solve the &quot;repair the quad&quot;
    
     * 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()) {
    
    			fixTower();
    
    			nextTower();
    
    		}
    
    		fixTower();
    
    		
    
    	}
    
    		
    
    	private void fixTower() {
    
    		turnLeft();
    
    		checkBlock();
    
    		while (frontIsClear()) {
    
    			checkBlock();
    
    			move();
    
    		}
    
    		turnAround();
    
    		while (frontIsClear()) {
    
    			checkBlock();
    
    			move();
    
    		}
    
    		turnLeft();
    
    	}
    
    	private void checkBlock() {
    
    		if (noBeepersPresent()) {
    
    			putBeeper();
    
    		}
    
    	}
    
    	
    
    	private void nextTower() {
    
    		for (int i = 0; i &lt; 4; i++) {
    
    			move();
    
    		}
    
    	}
    
    }
    
  • Jop

    I guess this no longer is a very hot topic, but as you seem like nice people, I just want to share my first Karel assignment solved (newspaper doesn’t count) with you. Here we go…

    import stanford.karel.*;

    public class StoneMasonKarel extends SuperKarel {

    //My concept contains two steps, very simple: fill tower with beepers and move to the next tower

    public void run() {

    fillTower();
    nextTower();

    }

    private void fillTower() {

    //get Karel in position looking to the north

    turnLeft();

    /*As long as Karel is facing north and there are no beepers present he should move
    * and put beepers…
    */

    while (facingNorth()) {

    move();

    if (noBeepersPresent()) {
    putBeeper();
    }

    /*…once the front is blocked, Karel turns around and, while front is clear, moves
    * back, simultaneously checking if there are still some beepers missing. At the end
    * he turns left and if front is clear, moves to the next tower…
    */

    if (frontIsBlocked()) {

    turnAround();

    while (frontIsClear()) {

    move();
    }

    if (noBeepersPresent()) {

    putBeeper();
    }

    turnLeft();

    if (frontIsClear()) {
    nextTower();
    }

    }

    }

    }

    /*The next tower is always four steps away. Once again, Karel checks if there are
    * still some beepers missing, and, if his left is clear, fills out one more tower.
    */

    private void nextTower() {

    for (int i = 0; i < 4; i++) {

    move();
    }

    if (noBeepersPresent()) {

    putBeeper();
    }

    • Jop

      THIS PART WAS MISSING UPTHERE (sorry…):

      if (leftIsClear()) {

      fillTower();

      }

      }

      }

  • Johnnyv

    This is the solution I came up with for this Assignment, works on any world so long as the columns are 4 spaces apart.

    * File: StoneMasonKarel.java

    import stanford.karel.*;

    public class StoneMasonKarel extends SuperKarel {

    /* Method: run()

    *

    * precondition: N/a

    *

    * postcondition: Karel will have placed a beeper where missing in each column

    * as to reapair the missing stones.

    *

    */

    public void run() {

    while (frontIsClear()) {

    turnLeft();

    repairColumns();

    }

    }

    /* Method: repairColumn()

    *

    * precondition: Karel will be facing up the column.

    *

    * postcondition: karel will be at the top of the column with beepers placed in missing

    * areas of column and return to bottom of column to face next column.

    */

    private void repairColumns() {

    while (facingNorth()) {

    while (frontIsClear()) {

    if (noBeepersPresent()) {

    putBeeper();

    } else {

    if (beepersPresent()) {

    move();

    }

    }

    }

    if (frontIsBlocked()) {

    if (noBeepersPresent()) {

    putBeeper();

    }

    turnAround();

    moveToBottomOfColumn();

    turnLeft();

    moveToNextColumn();

    }

    }

    }

    /* Method: moveToBottomOfColumn()

    *

    * precondition: Karel is at top of column facing South.

    *

    * postcondition: Karel is at bottom of column facing South.

    */

    private void moveToBottomOfColumn() {

    while (frontIsClear()) {

    move();

    }

    }

    /* Method: moveToNextColumn()

    *

    * precondition: Karel is at bottom of completed column facing South.

    *

    * postcondition: Karel will be standing at bottom of next column facing North.

    *

    */

    private void moveToNextColumn() {

    move();

    move();

    move();

    move();

    turnLeft();

    }

    }

  • Taha Ishfaq Bhutta

    /*

    * 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(){

    /*

    The First 3 line are to Start The Program

    */

    turnLeft();

    fillTheTower();

    turnRight();

    /*

    While The Front is Clear Repeat The Process

    */

    while(frontIsClear()){

    toTheNext(); // Move to Next Hill

    /*

    If We are At the Last Corner Use the First (If)

    Else Use (Else If)

    */

    if(frontIsBlocked()){

    turnRight();

    fillTheTower();

    }

    else if(frontIsClear()){

    fillTheTower();

    returnBack();

    }

    }

    }

    public void fillTheTower(){

    // Put Beepers Till You Find A Wall

    while(frontIsClear()){

    if(noBeepersPresent()){

    putBeeper();

    }

    move();

    }

    if(noBeepersPresent()){

    putBeeper();

    }

    }

    public void toTheNext(){

    // * Moving To The Next Hill *

    // Move Forward Till You Hit The Wall

    // But if the Left Side is Blocked it Means the We are

    // At a hill so Face Downwards

    move();

    while(frontIsClear()){

    if(leftIsBlocked()){

    turnRight();

    break;

    }

    else {

    move();

    }

    }

    }

    public void returnBack(){

    // While Front is Clear Turn Around and Move Back To the

    // Hill Top

    turnAround();

    while(frontIsClear()){

    move();

    }

    turnRight();

    }

    }

  • Taha Ishfaq Bhutta

    <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(){

    /*

    The First 3 line are to Start The Program

    */

    turnLeft();

    fillTheTower();

    turnRight();

    /*

    While The Front is Clear Repeat The Process

    */

    while(frontIsClear()){

    toTheNext(); // Move to Next Hill

    /*

    If We are At the Last Corner Use the First (If)

    Else Use (Else If)

    */

    if(frontIsBlocked()){

    turnRight();

    fillTheTower();

    }

    else if(frontIsClear()){

    fillTheTower();

    returnBack();

    }

    }

    }

    public void fillTheTower(){

    // Put Beepers Till You Find A Wall

    while(frontIsClear()){

    if(noBeepersPresent()){

    putBeeper();

    }

    move();

    }

    if(noBeepersPresent()){

    putBeeper();

    }

    }

    public void toTheNext(){

    // * Moving To The Next Hill *

    // Move Forward Till You Hit The Wall

    // But if the Left Side is Blocked it Means the We are

    // At a hill so Face Downwards

    move();

    while(frontIsClear()){

    if(leftIsBlocked()){

    turnRight();

    break;

    }

    else {

    move();

    }

    }

    }

    public void returnBack(){

    // While Front is Clear Turn Around and Move Back To the

    // Hill Top

    turnAround();

    while(frontIsClear()){

    move();

    }

    turnRight();

    }

    }

    </pre>

  • Jason Wigle

    Natasha, if you’re still out there, thanks for this. I’ve been taking the course while also tending to my 3 & 5 year old kids. I got super stumped on this problem so it was nice to find this and confirm that my first couple lines of code were on the right track. I didn’t want to look too deep as I wanted to struggle through and figure it out. Anyway after a few days here’s my approach for any who are looking to compare. (apologies for readability, can’t quite figure out how to put it into a code format and am out of problem solving gumption)

    [sourcecode language=&quot;&quot;css&quot;&quot;]

    //your code goes here

    [/sourcecode]
    import stanford.karel.*;

    //Program method follows the rules set forth in Assignment 1: StoneMasonKarel

    public class StoneMasonKarel extends SuperKarel {

    public void run () {

    BuildColumn();

    BuildNextColumn();

    }

    //This is the column builder. It assumes that Karel is facing east.

    private void BuildColumn() {

    turnLeft();

    while (frontIsClear()) {

    if (noBeepersPresent()) {

    putBeeper();

    move();

    } else {

    move();

    }

    if (noBeepersPresent()) {

    putBeeper();

    }

    if (frontIsBlocked()) {

    DescendColumn();

    BuildNextColumn();

    }

    }

    }

    //This will descend Karel down the column and orient Karel east upon finishing descent.

    private void DescendColumn() {

    turnAround();

    while (frontIsClear()) {

    move();

    }

    turnLeft();

    }

    //Moves Karel to next column and initiates column builder routine.

    private void BuildNextColumn() {

    while (frontIsClear()) {

    MoveToNextColumn();

    BuildColumn();

    }

    }

    //Assumes that all columns are 4 avenues apart per specifications in assignment 1:StoneMasonKarel

    private void MoveToNextColumn() {

    for (int i = 0; i < 4; i++){

    move();

    }

    }

    }

    • rvanzeist

      Jason, I finished this assignment a day ago myself and looking for some more solutions I found this thread.
      Maybe if you’re in the same stage of the course as i am and planning to go through it entirely we could benefit from eachother’s approaches and ideas?

  • Imran Ahmed

    Hello there

    Another very simple way ……

    /*
    * File: StoneMasonKarel.java
    * ————————–
    Karel does the job perfectly with both worlds.
    NO complex algorithm
    */

    import stanford.karel.*;

    public class StoneMasonKarel extends SuperKarel {

    public void run(){
    for(int i=0; i<4; i++){ //We need Karel to do the run method only 4 times.
    fixColumn();
    comeBack();
    nextColumn();

    }
    }

    // by_drgreen203
    private void fixColumn(){

    turnLeft();
    while(frontIsClear()){

    if(noBeepersPresent()){
    putBeeper();
    move();
    }
    else {
    move();

    }
    }
    if(frontIsBlocked()){
    if(noBeepersPresent()){
    putBeeper();
    }

    }
    }

    private void comeBack(){
    turnAround();
    while(frontIsClear()){
    move();
    }
    turnLeft();

    }

    private void nextColumn(){
    if(frontIsBlocked()){
    backHome(); //takes karel to the starting position.
    }
    else{
    move();
    move();
    move();
    move();
    }
    }
    private void backHome(){
    turnAround();
    while(frontIsClear()){
    move();
    }
    turnAround();
    }
    }
    //by_drgreen203