Posted on Leave a comment

My MidpointFindingKarel Algorithm

I am trying to solve the MidpointFindingKarel problem in the assignment 1 of Stanford’s CS106a. As of now, It is in my head but it still is not working perfectly.

I can lay down the beepers and have Karel move and pick them up one by one from one end to the other but I can’t have him stop at the middle.

  • lay down the beepers
  • move to the starting position
  • pick the beepers one at a time from one end to the other
  1. Lay down the beepers is easy.  It is just a “while” loop with the put beeper command in the body
  2. move to the starting position is just a “turnAround” and “movetowall” method
  3. This is the tough one which probably needs more decomposition. Still a work in progress.
Posted on Leave a comment

CheckerBoardKarel – CS106a,Assignment 1,Problem 3

Eureka! I solved it! Works in all worlds. I didn’t put any comments because the code is self explanatory.

[code lang=”java”]
/*
* File: CheckerboardKarel.java
* —————————-
* When you finish writing it, the CheckerboardKarel class should draw
* a checkerboard using beepers, as described in Assignment 1. You
* should make sure that your program works for all of the sample
* worlds supplied in the starter folder.
*/

import stanford.karel.*;

public class CheckerboardKarel extends SuperKarel {

public void run(){
turnLeft();
for(int i=0;i<32;i++){
putBeeper();
skip();
}
}

private void skip(){
if(frontIsClear()){
move();
//doubleskip();
}

if(frontIsBlocked()){
if(facingNorth()){
if(beepersPresent()){
skipright();
} else {
movedown();
}

} else {
if(facingSouth()){
if(beepersPresent()){
skipleft();
} else {
moveup();
}
}
}

} else {
move();
}
}

private void moveup(){
turnLeft();
move();
turnLeft();
}

private void movedown(){
turnRight();
move();
turnRight();
}

private void doubleskip(){
move();
move();
}

private void skipright(){
moveright();
moveright();
}

private void skipleft(){
moveleft();
moveleft();
}

private void moveright(){
turnRight();
if(frontIsBlocked()){
moveleft();
} else {
move();
}
}

private void moveleft(){
turnLeft();
if(frontIsBlocked()){
moveright();
} else {
move();
}
}

}
[/code]