Second Summer 2002

Practical Exam Preparation: Practice Problems
 The practical exam is in lab this week. It's an open-book, open-notes exam.

 You will draw a random problem from QuizSite. And you will have 115 minutes to solve it.

 When you are done, use QuizSite to submit it. You are only allowed one submission.

 And the submission must be performed in class, under the supervision of your AI, to be accepted. You'll be OK...

 I include below a number of problems. They're very similar to what one might see on the exam. Are these problems really really similar?

 You bet they are. So solve them all.

 OK. Here we go loop de loop... Oh, how funny`!` Can we see the problems now?

 We sure can.

1. Write a program `Olympics.java` that simulates an Olympic track and field event, a race between Carl Lewis and Ben Johnson. In your simulation Ben Jonhson and Carl Lewis are implemented as `Runner`s. (A `Runner`, of course, is nothing but a `Tigger`, a `Robot`, ultimately a `BankAccount`). You should define class `Runner`, and in your program create two such objects (just like we did for Lab Four when we created `Student`s) then for at least 10 seconds you should randomly push them forward by 10-12 meters every second. Whoever gets to 100 meters first, wins. Feel free to include other athletes, although running your program for just a pair would be fine. Your program must declare a winner in the end.

Here's a running example of your program:

```frilled.cs.indiana.edu%javac Olympics.java
frilled.cs.indiana.edu%java Olympics
The contest starts, we will give you updates every second.
... Ben Johnson now at 10.17 meters.
... Carl Lewis now at 11.59 meters.
After 1 seconds, Carl Lewis is in front (by 1.42 meters).
... Ben Johnson now at 21.46 meters.
... Carl Lewis now at 22.18 meters.
After 2 seconds, Carl Lewis is in front (by 0.71 meters).
... Ben Johnson now at 32.4 meters.
... Carl Lewis now at 32.29 meters.
After 3 seconds, Ben Johnson is in front (by 0.1 meters).
... Ben Johnson now at 43.11 meters.
... Carl Lewis now at 43.8 meters.
After 4 seconds, Carl Lewis is in front (by 0.68 meters).
... Ben Johnson now at 53.54 meters.
... Carl Lewis now at 54.86 meters.
After 5 seconds, Carl Lewis is in front (by 1.32 meters).
... Ben Johnson now at 65.45 meters.
... Carl Lewis now at 65.93 meters.
After 6 seconds, Carl Lewis is in front (by 0.48 meters).
... Ben Johnson now at 76.54 meters.
... Carl Lewis now at 76.05 meters.
After 7 seconds, Ben Johnson is in front (by 0.49 meters).
... Ben Johnson now at 88.35 meters.
... Carl Lewis now at 87.06 meters.
After 8 seconds, Ben Johnson is in front (by 1.28 meters).
... Ben Johnson now at 99.63 meters.
... Carl Lewis now at 97.42 meters.
After 9 seconds, Ben Johnson is in front (by 2.2 meters).
... Ben Johnson now at 110.0 meters.
... Carl Lewis now at 108.61 meters.
After 10 seconds, Ben Johnson is in front (by 1.39 meters).
The contest is over, and the winner is: Ben Johnson
frilled.cs.indiana.edu%```
Here's a possible solution to this problem.

```class Runner {
double distance;
String name;
Runner(String name) {
this.name = name;
}
void run() {
this.distance += Math.random() * (12 - 10) + 10;
this.distance = (int) (this.distance * 100) / 100.0;
}
void report() {
System.out.println("                         ... " +
this.name + " now at " +
this.distance + " meters.");
}
}

class Olympics {
public static void main(String[] args) {
Runner a = new Runner("Ben Johnson");
Runner b = new Runner("Carl Lewis");
System.out.println("The contest starts, " +
"we will give you updates every second.");
for (int i = 1; a.distance < 100 && b.distance < 100; i++) {
a.run();
a.report();
b.run();
b.report();
System.out.println("After " + i + " seconds, " +
(a.distance > b.distance? a.name : b.name) +
" is in front (by " +
(int) (Math.abs(a.distance
- b.distance) * 100) / 100.0 +
" meters). ");

}
System.out.println("The contest is over, and the winner is: " +
(a.distance > b.distance? a.name : b.name));
}
}```
2. Write a program that simulates 100 such athletic events and then writes back the number of times Ben Johnson has won and the number of times Carl Lewis has won. To keep the output of reasonable size don't write in detail what happens in each contest. Here's a possible run of your program (in which I assume 19 (nineteen) contests):

```frilled.cs.indiana.edu%javac More.java
frilled.cs.indiana.edu%java More
Ben Johnson wins.
Ben Johnson wins.
Carl Lewis wins.
Carl Lewis wins.
Carl Lewis wins.
Ben Johnson wins.
Carl Lewis wins.
This contest is a tie.
Ben Johnson wins.
Ben Johnson wins.
Carl Lewis wins.
Ben Johnson wins.
Carl Lewis wins.
Ben Johnson wins.
Ben Johnson wins.
Ben Johnson wins.
Carl Lewis wins.
Carl Lewis wins.
Carl Lewis wins.
Ben Johnson has 9 wins.
Carl Lewis has 9 wins.
frilled.cs.indiana.edu%```
Here's a solution to this problem.

```class Runner {
double distance;
String name;
int wins;
Runner(String name) {
this.name = name;
}
void run() {
this.distance += Math.random() * (12 - 10) + 10;
this.distance = (int) (this.distance * 100) / 100.0;
}
void report() {
System.out.println("                         ... " +
this.name + " now at " +
this.distance + " meters.");
}

void reset() {
this.distance = 0;
}
}

class More {
public static void main(String[] args) {
Runner a = new Runner("Ben Johnson");
Runner b = new Runner("Carl Lewis");

for (int times = 1; times < 20; times++) {

for (int i = 1; a.distance < 100 && b.distance < 100; i++) {
a.run();
b.run();
}

if (a.distance > b.distance) {
a.wins += 1;
System.out.println(a.name + " wins.");
} else if (a.distance < b.distance) {
b.wins += 1;
System.out.println(b.name + " wins.");
} else {
System.out.println("This contest is a tie.");
}

a.reset();
b.reset();

}

System.out.println(a.name + " has " + a.wins + " wins.");
System.out.println(b.name + " has " + b.wins + " wins.");
}
}```
3. Write a program that calculates and reports averages. Your program might resemble the `Vendor` program you wrote for Lab Seven in that it should accept several numbers on the same line, then calculate and report their average. If the line is empty (not even a space) the program ends, otherwise it prints a prompt and waits for a new line of numbers.

Here's how my program runs:

```frilled.cs.indiana.edu%javac Averages.java
frilled.cs.indiana.edu%java Averages
Numbers> 1 2 3 4
4 numbers, average is: 2.5
Numbers> 3 4 3 4 3 3 3
7 numbers, average is: 3.2857142857142856
Numbers> 10
1 number, average is: 10.0
Numbers>
frilled.cs.indiana.edu%```
Here's a solution to this problem.

```import java.util.*;

class Averages {
public static void main(String[] args) {
while (true) {
System.out.print("Numbers> ");
String line = console.readLine();
if (line.equals("")) break;
StringTokenizer stapler = new StringTokenizer(line);
int sum = 0;
int count = 0;
while (stapler.hasMoreTokens()) {
int number = Integer.parseInt(stapler.nextToken());
sum += number;
count += 1;
}
System.out.println(count +
(count > 1 ? " numbers" : " number") +
", average is: "
+ (double)sum / count);
}
}
}```
4. Write a program that reads a line of numbers, represented as a `String`, then it calculates and prints the average of the numbers, and prints the numbers one per line with an indication whether the number is above or below the average. (A pair of asterisks printed after the numbers below the average would do just fine).

Here's how my program runs:

```frilled.cs.indiana.edu%javac Marking.java
frilled.cs.indiana.edu%java Marking
Numbers> 1 2 3 4 5
5 numbers, average is: 3.0
1 is below the average
2 is below the average
3 is equal to the average
4 is above the average
5 is above the average
Numbers> 1 2 2 8
4 numbers, average is: 3.25
1 is below the average
2 is below the average
2 is below the average
8 is above the average
Numbers> 5
1 number, average is: 5.0
5 is equal to the average
Numbers>
frilled.cs.indiana.edu%```
Here's a solution to this problem.

```import java.util.*;

class Marking {

public static void main(String[] args) {

while (true) {

System.out.print("Numbers> ");
String line = console.readLine();
if (line.equals("")) break;
StringTokenizer stapler = new StringTokenizer(line);
int sum = 0;
int count = 0;
while (stapler.hasMoreTokens()) {
int number = Integer.parseInt(stapler.nextToken());
sum += number;
count += 1;
}
System.out.println(count +
(count > 1 ? " numbers" : " number") +
", average is: "
+ (double)sum / count);

double average = (double)sum / count;

stapler = new StringTokenizer(line);
while (stapler.hasMoreTokens()) {
int number = Integer.parseInt(stapler.nextToken());
if (number > average) {
System.out.println(number + " is above the average ");
} else if (number < average) {
System.out.println(number + " is below the average ");
} else {
System.out.println(number + " is equal to the average ");
}
}

}
}
}```
5. Exercise R1.18 in your book (page 44).

Since the formula is an infinite series and an algorithm must stop after a finite number of steps, you should stop when you have the result determined up to six significant digits.

Here's my program running:

```frilled.cs.indiana.edu%javac Pie.java
frilled.cs.indiana.edu%java Pie
The value of pi is: 3.1415924535897797
frilled.cs.indiana.edu%```
My program is 13 (thirteen) lines long. So this is a short, interesting program.

I hope you enjoy working on it.

Here's a solution to this problem.

```class Pie {
public static void main(String[] args) {
double sum = 1;
int sign = -1;
double value = 3;
while (value < 10000000) {
sum += sign / value;
value += 2;
sign *= -1;
}

System.out.println("The value of pi is: " + 4 * sum);

}
}```
6. Write a program that calculates and reports averages and standard deviations. Your program might resemble the `Vendor` program you wrote for Lab Seven in that it should accept several numbers on the same line, then calculate and report their average and standard deviation. If the line is empty (not even a space) the program ends, otherwise it prints a prompt and waits for a new line of numbers. This obviously is the `Averages` program above, plus the ability to calculate the standard deviation (its formula appears in Exercise P6.9, p. 265)

Here's my program running:

```frilled.cs.indiana.edu%javac StdDev.java
frilled.cs.indiana.edu%java StdDev
Numbers> 1 2 3 4 5 6 7 8 9 10
10 numbers, average is: 5.5
Standard deviation is: 3.0276503540974917
Numbers> 9 9 9 9 10 9 9 10
8 numbers, average is: 9.25
Standard deviation is: 0.4629100498862757
Numbers> 1
1 number, average is: 1.0
Standard deviation is: NaN
Numbers> 1 1
2 numbers, average is: 1.0
Standard deviation is: 0.0
Numbers> 1 1 1 2
4 numbers, average is: 1.25
Standard deviation is: 0.5
Numbers>
frilled.cs.indiana.edu%java```
What's that `NaN`? Did you run into the same problem?

Why or why not?

Here's a solution to this problem.

```import java.util.*;

class StdDev {
public static void main(String[] args) {
while (true) {
System.out.print("Numbers> ");
String line = console.readLine();
if (line.equals("")) break;
StringTokenizer stapler = new StringTokenizer(line);
double sum = 0;
double squares = 0;
int count = 0;
while (stapler.hasMoreTokens()) {
int number = Integer.parseInt(stapler.nextToken());
sum += number;
squares += number * number;
count += 1;
}
System.out.println(count +
(count > 1 ? " numbers" : " number") +
", average is: "
+ sum / count);

System.out.println("Standard deviation is: " +
Math.sqrt((squares - sum * sum / count)
/ (count - 1))
);
}
}
}```
7. Solve Exercise P6.12 (p. 267) in your text. Mine works like this:
```frilled.cs.indiana.edu%javac Factors.java
frilled.cs.indiana.edu%java Factors
Please enter a number: 34
2
17
frilled.cs.indiana.edu%java Factors
Please enter a number: 81
3
3
3
3
frilled.cs.indiana.edu%java Factors
Please enter a number: 1001
7
11
13
frilled.cs.indiana.edu%java Factors
Please enter a number: 3
3
frilled.cs.indiana.edu%java Factors
Please enter a number: 5
5
frilled.cs.indiana.edu%java Factors
Please enter a number: 2
2
frilled.cs.indiana.edu%java Factors
Please enter a number: 1
frilled.cs.indiana.edu%java Factors
Please enter a number: 13
13
frilled.cs.indiana.edu%java Factors
Please enter a number: 28
2
2
7
frilled.cs.indiana.edu%java Factors
Please enter a number: 10000001
11
909091
frilled.cs.indiana.edu%java Factors
Please enter a number: 909091
909091
frilled.cs.indiana.edu%```
As you can see, `909091` is a prime number. My program is again only 13 lines long.

Here's a solution to this problem.

```class Factors {
public static void main(String[] args) {
System.out.print("Please enter a number: ");
int number = console.readInt();
for (int i = 2, temp = number; i <= number && i <= temp; i++) {
while (temp % i == 0 ) {
System.out.println(i);
temp = temp / i;
}
}
}
}```
8. Write a program that asks the user to enter a positive number. Then the program prints back whether the number is prime or not. (Recall that a number is prime if it is not divisible by any number except 1 and itself). After the program prints back whether the number is prime or not the user is given a chance to enter another number. If the user enters `quit` the program ends. If the user enters a number the program checks to see if it is prime or not, prints the result, and the loop continues. Here's how my program works:
```frilled.cs.indiana.edu%javac Prime.java
frilled.cs.indiana.edu%java Prime
Please enter the number you want to test: 909091
Yes, 909091 is prime.
Please enter the number you want to test: 909090
2
3
3
3
5
7
13
No, 909090 is not prime.
Please enter the number you want to test: 909092
2
2
17
29
No, 909092 is not prime.
Please enter the number you want to test: 81
3
3
3
3
No, 81 is not prime.
Please enter the number you want to test: 54
2
3
3
3
No, 54 is not prime.
Please enter the number you want to test: 6
2
No, 6 is not prime.
Please enter the number you want to test: quit
frilled.cs.indiana.edu%java Prime
Please enter the number you want to test: 1000001
101
No, 1000001 is not prime.
Please enter the number you want to test: 1000000000001
Exception in thread "main" java.lang.NumberFormatException: 1000000000001
at java.lang.Integer.parseInt(Integer.java:426)
at java.lang.Integer.parseInt(Integer.java:463)
at Prime.main(Prime.java:9)
frilled.cs.indiana.edu%```
Please explain what happens with my last example.

Is my program faulty or what?

What would your program do in a similar situation?

Here's a solution to this problem.

```class Prime {
public static void main(String[] args) {
Wizard charlie = new Wizard();
do {
System.out.print("Please enter the number you want to test: ");
String line = console.readLine();
if (line.equals("quit")) break;
int number = Integer.parseInt(line),
numberOfFactors = charlie.countFactors(number);
if (numberOfFactors == 0)
System.out.println("Yes, " + number + " is prime.");
else
System.out.println("No, " + number + " is not prime.");
} while (true);
}
}

class Wizard {
int countFactors(int number) {
int count = 0;
for (int i = 2; i < number; i++) {
while (number % i == 0 ) {
count += 1;
System.out.println(i);
number = number / i;
}
}
return count;
}
}
```
9. Take a look at Section 6.5.4 (page 251) in the book.

10. Take a look at Section 6.5.3 in the book (page 246).

11. Just like in your `Averages` program above write a program that allows the user to enter several numbers on the same line, and then reports the largest and the smallest of the numbers on the line. If the user enters `quit` instead of the numbers, the program ends.

Here's how my program works:

```frilled.cs.indiana.edu%javac Extremes.java
frilled.cs.indiana.edu%java Extremes
Numbers> 5 6 4 7 2 9 5
6 numbers, between 2 and 9
Numbers> 1 1 1 1 1
4 numbers, between 1 and 1
Numbers> 1 1 1 100 -100 1 1 1
7 numbers, between -100 and 100
Numbers> quit
frilled.cs.indiana.edu%```
Here's a solution to this problem.

```import java.util.*;

class Extremes {
public static void main(String[] args) {
while (true) {
System.out.print("Numbers> ");
String line = console.readLine();
if (line.equals("quit")) break;
StringTokenizer stapler = new StringTokenizer(line);
int max = Integer.parseInt(stapler.nextToken()),
min = max,
count = 1;
while (stapler.hasMoreTokens()) {
int number = Integer.parseInt(stapler.nextToken());
if (max < number) max = number;
if (min > number) min = number;
count += 1;
}
System.out.println(count + " numbers, between " +
min + " and " + max);
}
}
}```
12. Implement the following version of the guess the number game. The computer chooses a secret random number (an integer) between 1 and 100. The user is given 10 tries to guess the number. Every time the user guesses the computer writes back if the guess is above, below, or equal to the secret number. If the user does not guess in 10 attempts the computer wins. Here's how my program works (the secret number is shown for transparency).

```frilled.cs.indiana.edu%javac Guess.java
frilled.cs.indiana.edu%java Guess
Hello, and welcome to the Guessing Game.
(24)Guess[1]: 50
Too high. Please try lower.
(24)Guess[2]: 25
Too high. Please try lower.
(24)Guess[3]: 12
Too low. Please try higher.
(24)Guess[4]: 18
Too low. Please try higher.
(24)Guess[5]: 22
Too low. Please try higher.
(24)Guess[6]: 23
Too low. Please try higher.
(24)Guess[7]: 24
You won! Congratulations.
frilled.cs.indiana.edu%java Guess
Hello, and welcome to the Guessing Game.
(9)Guess[1]: 50
Too high. Please try lower.
(9)Guess[2]: 25
Too high. Please try lower.
(9)Guess[3]: 0
Too low. Please try higher.
(9)Guess[4]: 18
Too high. Please try lower.
(9)Guess[5]: 2
Too low. Please try higher.
(9)Guess[6]: 16
Too high. Please try lower.
(9)Guess[7]: 14
Too high. Please try lower.
(9)Guess[8]: 12
Too high. Please try lower.
(9)Guess[9]: 4
Too low. Please try higher.
(9)Guess[10]: 6
Too low. Please try higher.
You lost. Better luck next time.
frilled.cs.indiana.edu% ```
Here's a solution to this problem.

```class Guess {
public static void main(String[] args) {
System.out.println("Hello, and welcome to the Guessing Game.");
int number = (int)(Math.random() * 100);
int count = 0;
while (count < 10) {
count += 1;
System.out.print("(" + number + ")Guess[" + count + "]: ");
int guess = console.readInt();
if (guess == number) {
System.out.println("You won! Congratulations.");
break;
} else {
if (guess < number)
System.out.println("Too low. Please try higher.");
else System.out.println("Too high. Please try lower.");
}
}
if (count == 10)
System.out.println("You lost. Better luck next time.");
}
}
```
13. Write a program that produces patterns like the one below.

```frilled.cs.indiana.edu%javac Pattern.java
frilled.cs.indiana.edu%java Pattern
Please enter a size: 13
*           *           *
*       *   *       *
*   *       *   *
*           *
*               *
*                   *
*                       *
*                   *
*               *
*           *
*   *       *   *
*       *   *       *
*           *           *
frilled.cs.indiana.edu%java Pattern
Please enter a size: 19
*                 *                 *
*             *   *             *
*         *       *         *
*     *           *     *
* *               * *
*                   *
*                       *
*                           *
*                               *
*                                   *
*                               *
*                           *
*                       *
*                   *
* *               * *
*     *           *     *
*         *       *         *
*             *   *             *
*                 *                 *
frilled.cs.indiana.edu%```
Here's a solution to this problem.

```class Pattern {
public static void main(String[] args) {
System.out.print("Please enter a size: ");
int size = console.readInt() - 1;
for (int i = 0; i <= size; i++) {
for (int j = 0; j <= size; j++) {
if (

(i - j == 0 && (i <= size / 4 || i > 3 * size / 4)) ||

(i + j == size && (i <= size / 4 || j <= size / 4)) ||

(i - j == size / 2 && i >= size / 2) ||

(i - j == - size / 2 && i <= size / 2) ||

(i + j == size / 2 && i <= size / 2) ||

(i + j == 3 * size / 2 && i >= size / 2)

) {
System.out.print("* ");
} else {
System.out.print("  ");
}
}
System.out.println();
}
}
}
```
14. Write a program that encodes sentences using a simple cypher: every character in the message is to be replaced by the one that follows in the ASCII code table, which can be found in appendix A3 in your book, starting on page 731. Here's how my program works:

```frilled.cs.indiana.edu%javac Encode.java
frilled.cs.indiana.edu%java Encode
Encode> I am here and I am encoding.
J!bn!ifsf!boe!J!bn!fodpejoh/!
Encode> So far so good.
Tp!gbs!tp!hppe/!
Encode> Hey, this is hard to read!
Ifz-!uijt!jt!ibse!up!sfbe"
Encode> quit
rvju
Encode> frilled.cs.indiana.edu%```
Here's a solution to this problem.

```class Encode {
public static void main(String[] args) {
System.out.print("Encode> ");
String line;
do {
for (int i = 0; i < line.length(); i++) {
System.out.print((char)(line.charAt(i) + 1));
}
System.out.println();
System.out.print("Encode> ");
} while (! line.equals("quit"));
}
}
```
15. Write a `Decode`r that will help you decode messages.

```frilled.cs.indiana.edu%javac Decode.java
frilled.cs.indiana.edu%java Decode
Decode> J!bn!ifsf!boe!J!bn!fodpejoh/!
I am here and I am encoding.
Decode> Tp!gbs!tp!hppe/!
So far so good.
Decode> Ifz-!uijt!jt!ibse!up!sfbe"
Hey, this is hard to read!
Decode> rvju
quit
Decode> quit
pths
Decode> frilled.cs.indiana.edu%
frilled.cs.indiana.edu%```
Here's a solution to this problem.

```class Decode {
public static void main(String[] args) {
System.out.print("Decode> ");
String line;
do {
for (int i = 0; i < line.length(); i++) {
System.out.print((char)(line.charAt(i) - 1));
}
System.out.println();
System.out.print("Decode> ");
} while (! line.equals("quit"));
}
}
```

 Is that all? That's the list of recommended problems, yes.

 It is not long, it is not short. Solve them first, think about that later.

 Get started. Don't procrastinate. You just have to get a round toit.

 Round toits are extremely rare these days. Yes, that's the main (and only) difficulty.

Last updated: Jun 16, 2002 by Adrian German for A201