I finally solved, the karel midpoint problem. This took me probably a total of 12 hours on and off to code over a few days. I found it much tougher than the checkerboard problem which I solved in a few hours. The fact that we’re limited from using variables makes it much harder but it was a fun challenge to solve it using only the allowed predefined Karel methods. I think my code’s pretty clean compared to some other people’s code I’ve looked at.
</span> <pre>/* * 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(){ layRow(); findMidpoint(); } private void findMidpoint(){ if (frontIsBlocked()){ //checks for case of street of 1 unit length turnAround(); //program will end } else{ //checks for every other case backandForthRemoval(); turnAround(); move(); } } private void backandForthRemoval() { //unfinished method, should decompose this further while (beepersPresent()){ move(); if (beepersPresent()){ //keep on removing beepers turnAround(); move(); turnAround(); pickBeeper(); moveToWall(); //goes to opposite wall and turns around moveToNearestBeeper(); } else { //does nothing, means there is only 1 beeper left and it is in the middle } } } //pre: karel is not standing on a beeper //post:karel is now standing on the nearest beeper private void moveToNearestBeeper(){ while (noBeepersPresent()){ move(); } } //pre: karel will be facing towards either wall //post: karel will move to the wall it was facing and turn around private void moveToWall() { while (frontIsClear()){ move(); } turnAround(); } //post: karel will have laid a row of beepers and will face west private void layRow() { while (frontIsClear()){ putBeeper(); move(); } putBeeper(); turnAround(); } }
Earlier, I didn’t know how to get the indentation to show up correctly in the source code. I googled for about 30 minutes to figure out how to make the source code look like it is in Eclipse. The tab to switch between visual and Text editor is near the upper right corner of the blog editing page. Clearly, I am not the only one with this problem as evidenced by the numerous identical questions. WordPress is starting to aggravate me. I probably should’ve gone over the wordpress tutorial.