33-midterm-soln

33-midterm-soln - Mehran Sahami CS 106A Handout #33...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Handout #33 CS 106A November 7, 2011 Solutions to Midterm Exam Problem 1: Karel the Robot /* File: MountainKarel.java */ import stanford.karel.*; public class MountainKarel extends SuperKarel { public void run() { goToMountain(); climbMountain(); repositionOnMountainTop(); putBeeper(); // plant flag (beeper) at top of mountain } /* Mountain always starts between 4th and 5th avenue, so we need * * to take 3 steps forward, checking for beepers at each step. */ private void goToMountain() { for(int i = 0; i < 3; i++) { if (beepersPresent()) { pickBeeper(); } move(); } if (beepersPresent()) { pickBeeper(); } } /* Mountain is a series of steps, so to climb mountain we need * * to keep climbing steps until we get to the top (front is clear). */ private void climbMountain() { while (frontIsBlocked()) { climbStep(); } } /* Each step is guaranteed to be at most two avenues wide, but can * * be arbitrarily tall. This method causes Karel to climb the step * * it is currently facing and move to the base of the next step. */ private void climbStep() { turnLeft(); while (rightIsBlocked()) { // ascend the step move(); } turnRight(); // face the top of the step move(); // traverse top of step (up to 2 avenues) if (frontIsClear()) { move(); } } /* Solution continued on next page */
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 5

33-midterm-soln - Mehran Sahami CS 106A Handout #33...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online