Java Reference
In-Depth Information
We note, in passing, that we can assign any four numbers to sunny, any other three to rainy, and the remaining
two to overcast.
6.7.1 Collecting Bottle Caps
The maker of a popular beverage is running a contest in which you must collect bottle caps to spell the word MANGO .
It is known that in every 100 bottle caps, there are 40 A s, 25 O s, 15 N s, 15 M s, and 5 G s. We want to write a program
to perform 20 simulations of the collection of bottle caps until we have enough caps to spell MANGO . For each
simulation, we want to know how many caps were collected. We also want to know the average number of bottle caps
collected per simulation.
The collection of a bottle cap is an event with nonuniform distribution. It is easier to collect an A than a G .
To simulate the event, we can generate random numbers uniformly distributed in the range 1 to 100. To determine
which letter was collected, we can use this:
c = random(1, 100)
if (c <= 40) we have an A
else if (c <= 65) we have an O
else if (c <= 80) we have an N
else if (c <=95) we have an M
else we have a G
In this example, if we want, we can scale everything by a factor of 5 and use the following:
c = random(1, 20)
if (c <= 8) we have an A
else if (c <= 13) we have an O
else if (c <= 16) we have an N
else if (c <=19) we have an M
else we have a G
Either version will work fine for this problem.
The gist of the algorithm for solving this problem is as follows:
totalCaps = 0
for sim = 1 to 20
capsThisSim = perform one simulation
print capsThisSim
add capsThisSim to totalCaps
endfor
print totalCaps / 20
The logic for performing one simulation is as follows:
numCaps = 0
while (word not spelt) {
collect a cap and determine the letter
mark the letter collected
add 1 to numCaps
}
return numCaps
 
Search WWH ::




Custom Search