CS 1063, Fall 2005
Dice statistics

The Java program below just adds a little code to the previous DiceTest class so that we can gather statistics about rolling two dice a large number of time (in the case below, 36 000 000 times). The new code is in red. (A few extra spaces were inserted into the output.)

On my obsolete 800 mHz machine at home, this took about 5 minutes to run. So 1 000 000 000 rolls would take about 3 hours, and 10 000 000 000 rolls about a day, on my slow machine.

Notice the output below. On the average, we would expect to roll a 2 about 1 000 000 times, a 3 about 2 000 000 times, and so forth, up to a 7 about 6 000 000 times. You can see that these were the approximate totals.

public class Dice {
    private int mySides;
    private int myLastRoll;

    //constructor
    public Dice (int sides) {
       mySides = sides;
       myLastRoll = 1;
    }

    //accessors
    public int getSides() {
       return mySides;
    }

    public int getLastRoll() {
       return myLastRoll;
    }

    public String toString(){
       return "sides: " + mySides +
          ", Last Roll: " + myLastRoll;
    }

    //modifier
    public int roll() {
       myLastRoll = (int)(Math.random()*
           mySides) + 1;
       return myLastRoll;
    }
}
public class DiceStat {

   public static void main(String[] args) {
      Dice d1 = new Dice(6);
      Dice d2 = new Dice(6);
      int[] diceStat = new int[13];
      for (int i = 0; i < 36000000; i++) {
         int roll1 = d1.roll();
         int roll2 = d2.roll();
         int sum = roll1 + roll2;
         diceStat[sum]++;
      }
      for (int i = 2; i < 13; i++)
         System.out.println(" Total: " + i
            + ", Number: " + diceStat[i]);
   }
}

Output (36000000 rolls):

  Total:  2, Number:  998889
  Total:  3, Number: 2000328
  Total:  4, Number: 2999662
  Total:  5, Number: 4003232
  Total:  6, Number: 5000122
  Total:  7, Number: 6000272
  Total:  8, Number: 4999601
  Total:  9, Number: 3999312
  Total: 10, Number: 2999034
  Total: 11, Number: 1999552
  Total: 12, Number:  999996