20S-CS106A-Practice-Key

20S-CS106A-Practice-Key - CS106A Handout 20S April 23rd,...

Info iconThis preview shows page 1. Sign up to view the full content.

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

Unformatted text preview: CS106A Handout 20S April 23rd, 2011 Spring 2011 CS106A Practice Midterm Solution Solution 1: Karel the Beeper Sweeper /** * Implements the program where Karel is initially facing east * and to the left of a 1 by n corridor littered with beepers (where * n >= 2). Karel runs the length of the corridor, collecting all * beepers and placing them where he started out. Assume that * Karel starts out at the corner of 1st and 1st. * * Initially, Karel has no beepers in his bag. */ public class BeeperSweeper extends SuperKarel { public void run() { while (frontIsClear()) { collectAllBeepers(); move(); } collectAllBeepers(); turnAround(); moveToWall(); turnAround(); unloadBeepers(); move(); } private void collectAllBeepers() { while (beepersPresent()) { pickBeeper(); } } private void moveToWall() { while (frontIsClear()) { move(); } } private void unloadBeepers() { while (beepersInBag()) { putBeeper(); } } } 2 Solution 2: Expressions and Methods (2a) 4 + 5.5 / 1.1 - 8 / 3 7.0 "BE" – "BA" error (4 > 6) && (4 / 0 == 8) false (2b) 380 Solution 3: Pythagorean Triples public class PythagoreanTriples extends ConsoleProgram { public void run() { for (int a = 1; a <= LIMIT; a++) { for (int b = a; b <= LIMIT; b++) { int csq = a * a + b * b; int c = GMath.round(Math.sqrt(csq)); if (c * c == csq) { println(a + ", " + b + ", " + c); } } } } /* Maximum value for a and b */ private static final int LIMIT = 25; } Solution 4: SuperHarmonic Numbers public class SuperHarmonics extends ConsoleProgram { public void run() { Rational harmonic = new Rational(0); Rational superHarmonic = new Rational(1); for (int n = 1; n <= LIMIT; n++) { harmonic = harmonic.add(new Rational(1, n)); superHarmonic = superHarmonic.multiply(harmonic); println(n + ".) " + superHarmonic); } } } ...
View Full Document

Ask a homework question - tutors are online