Download Karel the Robot - Section Handout - Programming Methodology- 10 and more Exercises Programming Methodologies in PDF only on Docsity!
Mehran Sahami Handout
CS 106A October 1, 2007
Section Handout #1—Karel the Robot
Based on a handout by Eric Roberts
This week in section, your first priority is to meet your section leader and discover what
sections in CS 106A are all about. Your section leader will therefore spend the first part
of this week’s session on introductions and telling you the things you need to know, such
as where to get help and how to sign up for interactive grading. After the introductory
material, the section will move on to cover some of the important material from class in a
setting that is small enough for you to ask questions and thereby find out what you need
to know. Make sure that you get your section leaders email address in section, so
that you can complete the Email portion of Assignment #1. This week, your goal is to
solve a Karel problem that involves stepwise refinement.
Section problem. Karel defends democracy
After all the problems in the 2000 presidential election in Florida, most states eliminated
the punch-card ballot problems that made hanging chad a household phrase at the end of
2000. The most common replacement is electronic voting machines—which have
problems of their own, as we saw in several districts in the 2006 elections—largely
because they do not generate any sort of voter-verifiable paper trail, making it impossible
to conduct recounts or determine whether fraud has occurred.
Another possible (if fanciful) strategy for securing elections would be to retain the punch
cards but to have a miniaturized robot—Karel, of course—check each of the ballots
before it is counted to ensure that no unwanted chad remains. Karel’s job is to move
across the punch card ballot and make sure that no stray bits of the card remain in any of
the ballot spaces in which the user has attempted to cast a vote.
To make this task more concrete, imagine that Karel is sitting at the extreme left edge of a
punch-card ballot that looks like this:
1 2 3 4 5 6 7 8 9 10 11
1
2
3
4
5
2
The partially enclosed rectangles in the interior of the card represent the areas of the
ballot that voters must punch out to record their preferences. On the original ballot, these
rectangles are completely filled with beepers, as shown in the ballot rectangles on 2nd^ and
8 th^ avenues. Ideally, the voter will punch out all the beepers when casting a vote, leading
to an empty rectangle of the sort shown on 4th^ avenue. Unfortunately, some bits of the
card—the chad—sometimes end up remaining in the hole, as shown on 6th^ avenue, where
the beeper at the top of the rectangle is still attached to the ballot. The situation on 10th
avenue, however, is even worse in that the punched out beeper from the middle of the
rectangle has ended up in the bottom of the rectangle, leaving two beepers on that square.
Suppose that your state legislature has determined that the voter’s intent is indicated by
the status of the square in the middle of the rectangle, which is where the stylus makes
contact with the card. If there is a beeper in that position, Karel must assume that the
voter did not intend to cast a vote in that column and move on to the next. If there is no
beeper in the center square, Karel must check the other two squares in the ballot and
remove any and all beepers so that the ballot can be counted correctly. Thus, the final
configuration of the ballot after Karel completes the processing should look like this:
1 2 3 4 5 6 7 8 9 10 11
1
2
3
4
5
Karel may count on the following facts about the world:
- The world consists of a single row of ballot rectangles that appear on every even
intersection, as shown in the sample world. The size of the ballot, however, may be
different from the one shown in the example in the sense that it may contain any
number of ballot rectangles. In any case, the card will begin one square to the left of
the first rectangle and end one square to the right of the last rectangle.
- Every ballot rectangle is exactly one space wide and three spaces high, as shown in the
diagram.
- Karel always begins immediately to the left of the first ballot rectangle, facing the hole
that gives Karel access to the voting area along the center line of the rectangles.
- Karel must finish execution facing east at the rightmost edge of the ballot.
Write a Karel program to clean the chad from a ballot. Remember that your program
should not work only for the example shown in the diagram, but for any ballot that meets
these conditions.
Mehran Sahami Handout
CS 106A October 8, 2007
Section Handout #2—Simple Java
Based on a handout by Eric Roberts
1. The Fibonacci sequence
In the 13th century, the Italian mathematician Leonardo Fibonacci—as a way to explain
the geometic growth of a population of rabbits—devised a mathematical sequence that
now bears his name. The first two terms in this sequence, Fib (0) and Fib (1), are 0 and 1,
and every subsequent term is the sum of the preceding two. Thus, the first several terms
in the Fibonacci sequence look like this:
Fib (0) = 0
Fib (1) = 1
Fib (2) = 1 (0 + 1)
Fib (3) = 2 (1 + 1)
Fib (4) = 3 (1 + 2)
Fib (5) = 5 (2 + 3)
Write a program that displays the terms in the Fibonacci sequence, starting with Fib (0)
and continuing as long as the terms are less than 10,000. Thus, your program should
produce the following sample run:
This program continues as long as the value of the term is less than the maximum value,
so that the loop construct you need is a while , presumably with a header line that looks
like this:
while (term < MAX_TERM_VALUE)
Note that the maximum term value is specified using a named constant.
2. Drawing a face
Your job is to draw a robot-looking face like the one shown in the following sample run:
This simple face consists of four parts—a head, two eyes, and a mouth—which are
arranged as follows:
- The head. The head is a big rectangle whose dimensions are given by the named
constants HEAD_WIDTH and HEAD_HEIGHT. The interior of the head is gray, although it
should be framed in black.
- The eyes. The eyes should be cricles whose radius in pixels is given by the named
constant EYE_RADIUS. The centers of the eyes should be set horizontally a quarter of
the width of the head in from either edge, and one quarter of the distance down from
the top of the head. The eyes are yellow.
- The mouth. The mouth should be centered with respect to the head in the x -dimension
and one quarter of the distance up from the bottom of the head in the y -dimension.
The dimensions of the mouth are given by the named constants MOUTH_WIDTH and
MOUTH_HEIGHT. The mouth is white.
Finally, the robot face should be centered in the graphics window.
2. Drawing a robot face
/ File: RobotFace.java / / This program draws a robot face. / import acm.graphics.; import acm.program.; import java.awt.; public class RobotFace extends GraphicsProgram { / Parameters for the drawing / private static final int HEAD_WIDTH = 100; private static final int HEAD_HEIGHT = 150; private static final int EYE_RADIUS = 10; private static final int MOUTH_WIDTH = 60; private static final int MOUTH_HEIGHT = 20; public void run() { addFace(getWidth() / 2, getHeight() / 2); } / Adds the entire face centered at (cx, cy) / private void addFace(double cx, double cy) { addHead(cx, cy); addEye(cx - HEAD_WIDTH / 4, cy - HEAD_HEIGHT / 4); addEye(cx + HEAD_WIDTH / 4, cy - HEAD_HEIGHT / 4); addMouth(cx, cy + HEAD_HEIGHT / 4); } / Adds the head centered at (cx, cy) / private void addHead(double cx, double cy) { double x = cx - HEAD_WIDTH / 2; double y = cy - HEAD_HEIGHT / 2; GRect head = new GRect(x, y, HEAD_WIDTH, HEAD_HEIGHT); head.setFilled(true); head.setFillColor(Color.GRAY); add(head); } / Adds an eye centered at (cx, cy) / private void addEye(double cx, double cy) { double x = cx - EYE_RADIUS; double y = cy - EYE_RADIUS; GOval eye = new GOval(x, y, 2 * EYE_RADIUS, 2 * EYE_RADIUS); eye.setFilled(true); eye.setColor(Color.YELLOW); add(eye); } / Adds a mouth centered at (cx, cy) / private void addMouth(double cx, double cy) { double x = cx - MOUTH_WIDTH / 2; double y = cy - MOUTH_HEIGHT / 2; GRect mouth = new GRect(x, y, MOUTH_WIDTH, MOUTH_HEIGHT); mouth.setFilled(true); mouth.setColor(Color.WHITE); add(mouth); } }*
Mehran Sahami Handout
CS 106A October 15, 2007
Section Handout
Parameters, Random Numbers, and Simple Graphics
Portions of this handout by Eric Roberts and Patrick Young.
1. True/False questions
For each of the following statements below, indicate whether it is true or false in Java:
a) The value of a local variable named i has no direct relationship with that of a
variable named i in its caller.
b) The value of a parameter named x has no direct relationship with that of a variable
named x in its caller.
2. Tracing method execution
For the program below, trace through its execution by hand to show what output is
produced when it runs.
- File: Hogwarts.java
- This program is just testing your understanding of parameter passing. */
import acm.program.*;
public class Hogwarts extends ConsoleProgram {
public void run() { bludger(2001); }
private void bludger(int y) { int x = y / 1000; int z = (x + y); x = quaffle(z, y); println("bludger: x = " + x + ", y = " + y + ", z = " + z); }
private int quaffle(int x, int y) { int z = snitch(x + y, y); y /= z; println("quaffle: x = " + x + ", y = " + y + ", z = " + z); return z; }
private int snitch(int x, int y) { y = x / (x % 10); println("snitch: x = " + x + ", y = " + y); return y; } }
Mehran Sahami Handout #20A
CS 106A October 17, 2007
Solution to Section
Portions of this handout by Eric Roberts and Patrick Young.
1. True/False questions
a) The value of a local variable named i has no direct relationship with that of a
variable named i in its caller.
Answer: True
b) The value of a parameter named x has no direct relationship with that of a variable
named x in its caller.
Answer: True
2. Tracing method execution
The output of Hogwarts.java is:
snitch: x = 4004, y = 1001 quaffle: x = 2003, y = 1, z = 1001 bludger: x = 1001, y = 2001, z = 2003
3. Random circles
- File: RandomCircles.java
- This program draws a set of 10 circles with different sizes,
- positions, and colors. Each circle has a randomly chosen
- color, a randomly chosen radius between 5 and 50 pixels,
- and a randomly chosen position on the canvas, subject to
- the condition that the entire circle must fit inside the
- canvas without extending past the edge. */
import acm.program.; import acm.graphics.; import acm.util.*;
public class RandomCircles extends GraphicsProgram {
/** Number of circles */ private static final int NCIRCLES = 10;
/** Minimum radius */ private static final double MIN_RADIUS = 5;
/** Maximum radius */ private static final double MAX_RADIUS = 50;
public void run() { for (int i = 0; i < NCIRCLES; i++) { double r = rgen.nextDouble(MIN_RADIUS, MAX_RADIUS); double x = rgen.nextDouble(0, getWidth() - 2 * r); double y = rgen.nextDouble(0, getHeight() - 2 * r); GOval circle = new GOval(x, y, 2 * r, 2 * r); circle.setFilled(true); circle.setColor(rgen.nextColor()); add(circle); } }
/* Private instance variable */ private RandomGenerator rgen = RandomGenerator.getInstance();
}
Mehran Sahami Handout
CS 106A October 22, 2007
Section Handout #4: String Processing
Portions of this handout by Eric Roberts and Patrick Young
1. Adding commas to numeric strings (Chapter 8, Exercise 13, page 290)
When large numbers are written out on paper, it is traditional—at least in the United
States—to use commas to separate the digits into groups of three. For example, the
number one million is usually written in the following form:
To make it easier for programmers to display numbers in this fashion, implement a
method
private String addCommasToNumericString(String digits)
that takes a string of decimal digits representing a number and returns the string formed
by inserting commas at every third position, starting on the right. For example, if you
were to execute the main program
public void run() { while (true) { String digits = readLine("Enter a numeric string: "); if (digits.length() == 0) break; println(addCommasToNumericString(digits)); } }
your implementation of the addCommasToNumericString method should be able to
produce the following sample run:
2. Deleting characters from a string
Write a method
public String removeAllOccurrences(String str, char ch)
that removes all occurrences of the character ch from the string str. For example, your
method should return the values shown:
removeAllOccurrences("This is a test", 't') returns "This is a es" removeAllOccurrences("Summer is here!", 'e') returns "Summr is hr" removeAllOccurrences("---0---", '-') returns "0"
3. Heap/stack diagrams
Using the style of heap/stack diagram introduced in Chapter 7, show the state of both the
heap and the stack at the point in the computation indicated by the arrow in the following
code, where the Rationale class is the one defined in Chapter 6.
public void run() { Rational r = new Rational(1, 2); r = raiseToPower(r, 3); println("r ^ 3 = " + r); }
private Rational raiseToPower(Rational x, int n) Rational result = new Rational(1); for (int i = 0; i < n; i++) { result = result.multiply(x); } return result; }
Diagram at this point
Indicate which values in the heap are garbage at this point in the calculation.
Mehran Sahami Handout #24A
CS 106A October 24, 2007
Solution to Section
Portions of this handout by Eric Roberts and Patrick Young
1. Adding commas to numeric strings
private String addCommasToNumericString(String digits) { String result = ""; int len = digits.length(); int nDigits = 0; for (int i = len - 1; i >= 0; i--) { result = digits.charAt(i) + result; nDigits++; if (((nDigits % 3) == 0) && (i > 0)) { result = "," + result; } } return result; }
2. Deleting characters from a string
private String removeAllOccurrences(String str, char ch) { String result = ""; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) != ch) { result += str.charAt(i); } } return result; }
A slightly different approach that involves a while loop instead of a for loop:
**private String removeAllOccurrences(String str, char ch) { while (true) { int pos = str.indexOf(ch); if (pos >= 0) { str = str.substring(0, pos)
- str.substring(pos + 1); } else break; } return str; }**
Could you generalize these functions to remove substrings? For instance,
removeAllSubstrings("Mississippi", 'si') returns "Missppi". Would these two
functions ever return different values for the same input?
3. Heap/Stack diagrams
1000 1 2
nu m den 1020 1 1
nu m den 1040 1 2
nu m den
r 1000^ FFC
heap
3^ FFB
1080^ FFB
n
1060 1 4
nu m den
stack i 3^ FFB result
1080 1 8
nu m den
x 1000^ FFB
garbage
4. Tracing method execution
2. Histograms
Write a program that reads a list of exam scores from the file
MidtermScores.txt (which contains one score per line) and
then displays a histogram of those numbers, divided into the
ranges 0–9, 10–19, 20–29, and so forth, up to the range
containing only the value 100. If, for example,
MidtermScores.txt contains the data shown in the right
margin, your program should then be able to generate a
histogram that looks as much as possible like the following
sample run:
MidtermScores.txt 73 58 73 93 82 62 80 53 93 52 92 75 65 95 23 100 75 38 80 77 92 60 98 95 62 87 97 73 78 72 55 58 42 31 78 70 78 74 70 60 72 75 84 87 62 17 92 78 74 65 90
3. Unique Names
Write a program that asks the user for a list of names (one per line) until the user enters a
blank line (i.e., just hits return when asked for a name). At that point the program should
print out the list of names entered, where each name is listed only once (i.e., uniquely) no
matter how many times the user entered the name in the program. You may find that
using an ArrayList to keep track of the names entered by user may greatly simplify this
problem.
A sample run of this program is shown below.