J
Jose Durazo
Hello, I'm doing an exercise to simulate rolling a pair of dice 36,000
times, then count and display how many times the simulation rolls each
possible sum.
For some reason each time I run my simulation, one or more of my sums is
zero, which is highly unlikely. So I'm sure there's a bug in my code. But
I can't tell what it is, even after re-reading it several times. Can
someone give me a hint?
Here is my code:
static void SimulateDiceRolls()
{
// When you roll two dice, there are 11 possible sums:
// 2, 3, ..., 10, 11, 12. Define an array of 13 elements
// where the first two elements are unused, but the third element
// where index equals 2, corresponds to sum = 2, and so on.
// make sure they're initialized to 0, which C# does by default
int[] sum = new int[13];
// for 36,000 times, roll two dice, calculate the sum,
// and increment the index corresponding to that sum.
int currentResult = 0;
for (int numberOfRolls = 1; numberOfRolls <= 36000; ++numberOfRolls)
{
currentResult = RollTwoDice();
++sum[currentResult];
}
// print how many times each sum comes up and what percent of the time
// to a 3 decimal precision that sum comes up
for (int sumIndex = 2; sumIndex <= 12; ++sumIndex)
{
Console.WriteLine("{0,5} {1,5} {2:F3}", sumIndex, sum[sumIndex],
(double)sum[sumIndex] / 36000 * 100);
}
}
// return the sum of two randomly generated integers from 1 to 6
// inclusive
static int RollTwoDice()
{
Random r = new Random();
return r.Next(1, 7) + r.Next(1, 7);
}
Thanks in advance,
Jose
times, then count and display how many times the simulation rolls each
possible sum.
For some reason each time I run my simulation, one or more of my sums is
zero, which is highly unlikely. So I'm sure there's a bug in my code. But
I can't tell what it is, even after re-reading it several times. Can
someone give me a hint?
Here is my code:
static void SimulateDiceRolls()
{
// When you roll two dice, there are 11 possible sums:
// 2, 3, ..., 10, 11, 12. Define an array of 13 elements
// where the first two elements are unused, but the third element
// where index equals 2, corresponds to sum = 2, and so on.
// make sure they're initialized to 0, which C# does by default
int[] sum = new int[13];
// for 36,000 times, roll two dice, calculate the sum,
// and increment the index corresponding to that sum.
int currentResult = 0;
for (int numberOfRolls = 1; numberOfRolls <= 36000; ++numberOfRolls)
{
currentResult = RollTwoDice();
++sum[currentResult];
}
// print how many times each sum comes up and what percent of the time
// to a 3 decimal precision that sum comes up
for (int sumIndex = 2; sumIndex <= 12; ++sumIndex)
{
Console.WriteLine("{0,5} {1,5} {2:F3}", sumIndex, sum[sumIndex],
(double)sum[sumIndex] / 36000 * 100);
}
}
// return the sum of two randomly generated integers from 1 to 6
// inclusive
static int RollTwoDice()
{
Random r = new Random();
return r.Next(1, 7) + r.Next(1, 7);
}
Thanks in advance,
Jose