CS106A
Handout 16
Spring 2011
April 15
th
, 2011
Random Numbers, More Graphics
Random Values
Consider the following program, which simulates the experiment where one keeps flipping a fair
coin until she gets 6 heads in a row.
We’ll make use of the
RandomGenerator
class, which is
discussed in Section 6.1 of your reader.
Here’s the program:
public
class
ConsecutiveHeads
extends
ConsoleProgram {
/**
* Short, nontrivial program illustrating how a RandomGenerator
* object can be used to introduce probability into the execution
* of a program.
Our program simulates the probability experiment
* where a fair coin is repeatedly flipped
until six consecutive
* heads come up.
The chance that any sequence of six coin flips comes up
* all heads is very small, but it *will* happen eventually.
*/
public
void
run() {
println("Here's a program that simulates a probability experiment.");
println("It determines how many times you need to flip a fair coin");
println("before heads coming up " +
NUM_HEADS_NEEDED
+ " times in a row!");
println();
int
numFlips = 0;
int
numConsecutiveHeads = 0;
while
(numConsecutiveHeads <
NUM_HEADS_NEEDED
) {
boolean
isHeads = rgen.nextBoolean();
if
(isHeads) {
print("H");
numConsecutiveHeads++;
}
else
{
print("T");
numConsecutiveHeads = 0;
}
numFlips++;
if
(numFlips %
NUM_FLIPS_PER_LINE
== 0) println();
pause(
DELAY_BETWEEN_FLIPS
);
}
println("In this particular trial, we needed to flip a");
println("coin " + numFlips + " times before we got " +
NUM_HEADS_NEEDED
);
println("heads in a row.");
}
// instance variable shared through entire program
private
RandomGenerator rgen = RandomGenerator.
getInstance
();
// constants
private
static
final
int
NUM_HEADS_NEEDED
= 6;
private
static
final
int
NUM_FLIPS_PER_LINE
= 40;
private
static
final
int
DELAY_BETWEEN_FLIPS
= 10;
}
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThe program outputs something different virtually every time, because the execution is
heavily influenced by the outcome of the
RandomGenerator.nextBoolean
methods.
Here’s are three same outputs:
Sample Output 1:
Here's a program that simulates a probability experiment.
It determines how many times you need to flip a fair coin
before heads coming up 6 times in a row!
HHHTTTTHTHTHHHHTHHHHTTHTTTTHTTTHTHHHTHTT
THHTTTTTHTHTTTHTHTHTHHTHTTTHHHHHTTHTTHHT
HTTHTHHHTTTHTTTHHHHHH
In this particular trial, we needed to flip a
coin 101 times before we got 6 heads in a row.
Sample Output 2:
This is the end of the preview. Sign up
to
access the rest of the document.
 Spring '08
 SAHAMI,M

Click to edit the document details