This program will introduce you to the concept of "probability" or
"chance".
When you roll a die, the chance of rolling a 1 is 1/6 or 0.166666666666.
How about when you use 2 dice ?
What is the chance of rolling 1's on both dice ?
We will write a computer program to try to figure this out.
The chance that you roll 1's using 2 dice can be approximated by
the average number of times that you roll 1's with 2 dice.
You will be writing a program to simulate 100000 rolls of a pair of dice
and compute the average number of times that two ones are rolled
in those 100000 rolls.
- First, two variables, dice1 and dice2,
are declared and initialized
to store a pair of random dice values.
Additionally, two more variables, count and
total, are declared
to store the number of times that two ones are rolled
and the total number of rolls respectively.
- Next, use a while-loop to simulate the 100000 rolls of a pair of dice.
Inside the loop, two random integer numbers in the range of
1 to 6 are generated using the Math.random() method and
stored in the dice1 and dice2 variables
respectively.
-
Then, check if the two dice values are both equal to 1.
If so, the count variable is incremented by 1.
- Lastly, the total variable is incremented by 1 at
each iteration of the loop.
After the loop finishes executing, the average number of times that
two ones are rolled is computed by dividing the
count variable
by the
total variable.
Finally, you prints out the average to the console.
If your program is correct, the average should be
approximately 1/36 or 0.027777777.
If you want to get a better approximation, change the while loop to
run 1,000,000 or even 10,000,000 times.
The more times you simulate, the more accuracy you will get - try it !