33-midterm-soln

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

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

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 */

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 02/09/2012 for the course CS 106A taught by Professor Sahami,m during the Fall '08 term at Stanford.

### Page1 / 5

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

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

View Full Document
Ask a homework question - tutors are online