Sicherman.java


Below is the syntax highlighted version of Sicherman.java from §2.2 Libraries.


/******************************************************************************
 *  Compilation:  javac Sicherman.java
 *  Execution:    java Sicherman trials
 *  Dependencies: StdOut.java StdRandom.java
 *
 *  Roll a pair of Sichermann dice the specified number of times and pritn
 *  the fraction of times that you get each possible sum.
 *
 *  % java Sicherman 10000000
 *  2: 0.027919
 *  3: 0.0555154
 *  4: 0.083341
 *  5: 0.110863
 *  6: 0.138917
 *  7: 0.1665992
 *  8: 0.1388638
 *  9: 0.1111983
 *  10: 0.0832959
 *  11: 0.0556597
 *  12: 0.0278277
 *  
 ******************************************************************************/


public class Sicherman { 

    public static void main(String[] args) { 
        int SIDES_PER_DIE = 6;
        int NUMBER_OF_DICE = 2;

        //  number of trials
        int trials = Integer.parseInt(args[0]);

        //  count[i] = number of times sum = i appers
        int[] count  = new int[NUMBER_OF_DICE * SIDES_PER_DIE + 1];

        int[] die1 = { 1, 2, 2, 3, 3, 4 };
        int[] die2 = { 1, 3, 4, 5, 6, 8 };

        // roll Sicherman dice, trials times
        for (int t = 0; t < trials; t++) {
            int roll1 = die1[StdRandom.uniform(SIDES_PER_DIE)];
            int roll2 = die2[StdRandom.uniform(SIDES_PER_DIE)];
            int sum = roll1 + roll2;
            count[sum]++;
        }

        // print results
        for (int i = 2; i <= NUMBER_OF_DICE * SIDES_PER_DIE; i++) {
            System.out.println(i + ": " + (double) count[i] / trials);
        }
    }
}


Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne.
Last updated: Fri Oct 20 14:12:12 EDT 2017.