package edu.bloomu.ch7a;

import java.util.concurrent.ThreadLocalRandom;

/**
 * Calculates the probability of each possible sum when rolling a pair of dice. 
 * 
 * @author Drue Coles
 */
public class DiceSums2 {

    public static void main(String[] args) {

        // declare counters for each possible sum
        final int maxSum = 12;
        int[] sums = new int[maxSum + 1];

        // The calculation is performed by Monte Carlo simulation.
        int rolls = 10_000_000;
        for (int i = 0; i < rolls; i++) {
            int k = rollDice();            
            sums[k]++;
        }

        // Format and display results.
        System.out.println("SUM PROBABILITY");
         for (int i = 2; i <= maxSum; i++) {
            double prob = (double) sums[i] / rolls * 100;

            // sequence of stars for a bar chart
            String star = "\u2605";
            int numStars = (int) Math.round(prob);

            System.out.printf("%3d %4.1f%% %s %n", i, prob, star.repeat(numStars));
        }
    }
    
    /**
     * Rolls a pair of dice.
     * 
     * @return the sum of the numbers rolled
     */
    private static int rollDice() {
        ThreadLocalRandom rand = ThreadLocalRandom.current();
        int die1 = rand.nextInt(1, 7);
        int die2 = rand.nextInt(1, 7);
        return die1 + die2;
    }
}