Search code examples
javadice

Adding Two Dice 36 Million Times


The Question: Write a program that rolls two dice and adds their sum 36,000,000 times and prints how many times each sum was calculated.

So obviously I need to get a rand for 6 numbers twice and add them - in a loop for 36 million times, and then get a frequency counter for however many times each sum was found (which ranges from 2 to 12).

Now given the fact that I'm not very experienced in Java, I ran into a couple of problems. This is the code that I've got so far:

package twodice;

import java.util.Random;

public class TwoDice 
{
    public static void main(String[] args) 
    {
        int sum;

        Random randomNumbers = new Random();
        int[] frequency = new int[13];

        for (int roll = 2; roll <= 36000000; roll++)
        {
            ++frequency[(1 + randomNumbers.nextInt(6)) + (1 + randomNumbers.nextInt(6))];
        }

        System.out.printf("%s%10s\n", "Face", "Frequency");

        for(int face = 1; face < frequency.length; face++)
        {
            System.out.printf("%4d%10d\n", face, frequency[face]);
        }
    }
}

Output:

run:
Face Frequency
   1   6001537
   2   6003025
   3   5997753
   4   5997647
   5   6000769
   6   5999269
   7         0
   8         0
   9         0
  10         0
BUILD SUCCESSFUL (total time: 0 seconds)

The problems are that: 1. The sums that are displaying are not 2-12, they're 1-10 (The right number of sums, just not the right sums... 2. The frequencies are only being found for 1-6, not 1-6 + 1-6.

Thanks for all of your help!

EDIT: Solved by Oscar Lopez! Thanks so much man!


Solution

  • For the first problem, the array has the wrong size, this should fix it:

    int[] frequency = new int[13]; 
    

    Also the values at indexes 0 and 1 will always be 0, so the loop should start at face = 2. For the second problem, the program should simulate throwing two dice, not just one as it currently is. Try this:

    ++frequency[(1 + randomNumbers.nextInt(6)) + (1 + randomNumbers.nextInt(6))];