import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Random;
public class DiceRollSimulator {
public static String simulate(int numberOfDice, int numberOfTrials)
{
// return nothing if there are no dice and/or no trials
if (numberOfDice < 1 || numberOfTrials < 1) return "";
// number of trials
BigDecimal trials = new BigDecimal(String.valueOf(numberOfTrials));
// array to keep track of roll count
BigDecimal[] rolls = new BigDecimal[numberOfDice * 6 + 1];
for (int i = 0; i < rolls.length; i++) rolls[i] = BigDecimal.ZERO; // intialize BigDecimal array
for (int i = 0; i < trials.doubleValue(); i++)
{
// roll the die/dice and count the sum
int rollSum = 0;
for (int j = 0; j < numberOfDice; j++) rollSum += randomInt(1, 6);
// add 1 to the roll counter array for which sum was rolled
rolls[rollSum] = new BigDecimal(String.valueOf(rolls[rollSum].intValue() + 1));
}
DecimalFormat df = new DecimalFormat("#.#####");
String re = ""; // return string
// add the roll percentages to the return string
for (int i = numberOfDice; i < rolls.length; i++)
{
// number of spaces after showing what sum it is
String spacing = createStrings(" ", 5 - String.valueOf(i).length());
// number of times this sum was rolled
int rollNumber = rolls[i].intValue();
// roll percentage in respect to the number of trials
String percentage = df.format((rolls[i].divide(trials, 5, RoundingMode.HALF_EVEN)).multiply(new BigDecimal("100"))) + "%";
// spacing after the roll percentage
String spacing2 = createStrings(" ", 10 - percentage.length());
// if the percentage is less than 10 (align the percentage place values)
if (Double.parseDouble(percentage.substring(0, percentage.length() - 1)) < 10)
{
spacing += " "; // move the percentage over 1 space
spacing2 = spacing2.substring(0, spacing2.length() - 1); // move the roll count back one space
}
// put it all together and add it to the return string
re += (i + ":" + spacing + percentage + spacing2 + "--> (" + rollNumber + " rolls)\n");
}
return re;
}
/* returns a string repeated int number of times */
public static String createStrings(String str, int numberOfStrings)
{
String re = "";
for (int i = 0; i < numberOfStrings; i++) re += str;
return re;
}
/* returns random number between min (inclusive) and max (inclusive) */
public static int randomInt(int min, int max) {
return min + (int)(Math.random() * ((max - min) + 1));
}
public static int randInt(int min, int max) {
return new Random().nextInt((max - min) + 1) + min;
}
}
DOWNLOAD
Created: January 22, 2014
Completed in full by: Michael Yaworski