Skip to content

Instantly share code, notes, and snippets.

@NatashaTheRobot
Created October 28, 2011 04:18
Show Gist options
  • Save NatashaTheRobot/1321608 to your computer and use it in GitHub Desktop.
Save NatashaTheRobot/1321608 to your computer and use it in GitHub Desktop.
This is the solution the MidpointFindingKarel problem in the online Stanford CS 106A class
/*
* File: MidpointFindingKarel.java
* -------------------------------
* When you finish writing it, the MidpointFindingKarel class should
* leave a beeper on the corner closest to the center of 1st Street
* (or either of the two central corners if 1st Street has an even
* number of corners). Karel can put down additional beepers as it
* looks for the midpoint, but must pick them up again before it
* stops. The world may be of any size, but you are allowed to
* assume that it is at least as tall as it is wide.
*/
import stanford.karel.*;
public class MidpointFindingKarel extends SuperKarel {
public void run () {
putEndBeepers();
while (frontIsClear()) {
takeLastBeeperWest();
takeLastBeeperEast();
}
}
private void putEndBeepers() {
move();
putBeeper();
while (frontIsClear()) {
move();
}
turnAround();
move();
putBeeper();
}
private void takeLastBeeperWest() {
if (facingWest()) {
move();
if (noBeepersPresent()) {
putBeeper();
}
turnAround();
move();
pickBeeper();
turnAround();
move();
move();
}
detectBeeper();
turnAround();
}
private void takeLastBeeperEast() {
if (facingEast()) {
pickBeeper();
move();
if(noBeepersPresent()) {
putBeeper();
}
move();
detectBeeper();
turnAround();
}
}
private void detectBeeper() {
while (noBeepersPresent()) {
if(frontIsClear()) {
move();
}
if(frontIsBlocked()) {
turnAround();
while(frontIsClear()) {
if(noBeepersPresent()) {
move();
}
}
}
}
}
}
@Silverclaw17
Copy link

Silverclaw17 commented Sep 23, 2022

Screenshot 2022-09-23 9 43 07 AM

I repurposed the for loops to technically not use variables

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment