32-midterm-soln

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

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

View Full Document Right Arrow Icon
Mehran Sahami Handout #32 CS 106A November 2, 2009 Solutions to Midterm Exam Problem 1: Karel the Robot (25 points) /* File: FillRectangleKarel.java * ----------------------------- * This program has Karel fill a rectangular region marked * by beepers on its four corners. Karel starts on the * lower left-hand corner, facing East. */ import stanford.karel.*; public class FillRectangleKarel extends SuperKarel { /* Creates a box around the region and then fills the * region, one row at a time. After each row is filled, * Karel returns to the start of that row, then Karel * repositions to the start of the next row to fill. */ public void run() { createBox(); startNextRow(); // Note the "off-by-one" issue here while (beepersPresent()) { fillRow(); returnToStart(); startNextRow(); } } /* Draws a box around the region marked by four beepers */ private void createBox() { for(int i = 0; i < 4; i++) { fillRow(); turnLeft(); } } /* Repositions Karel up one row */ private void startNextRow() { turnLeft(); move(); turnRight(); } /* Fills a row with beepers, skipping the position Karel starts on */ private void fillRow() { move(); while (noBeepersPresent()) { putBeeper(); move(); } }
Background image of page 1

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

View Full DocumentRight Arrow Icon
/* Returns Karel to the beginning of a row of beepers */ private void returnToStart() { turnAround(); while (beepersPresent()) {
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 12/01/2009 for the course CS 106A taught by Professor Sahami,m during the Fall '08 term at Stanford.

Page1 / 5

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

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

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