Untitled

mail@pastecode.io avatar
unknown
java
2 months ago
2.1 kB
3
Indexable
Never
import acm.program.ConsoleProgram;
import de.ur.mi.util.RandomGenerator;

public class DiceExperimentStart extends ConsoleProgram {
    private RandomGenerator rGen = RandomGenerator.getInstance();

    public void run() {
        int numDice = readInt("Please enter the number of dice to throw: ");
        int numExperiments = readInt("Please enter the number of times the experiment should be repeated: ");
        double averageThrows = calculateAverageThrowsUntilMax(numDice, numExperiments);
        println("It took me " + averageThrows + " throws on average to throw the max number.");
    }

    /**
     * Calculate the average number of throws needed to reach the maximal dice roll result with numDice
     * in numExperiments
     *
     * @param numDice        number of dice
     * @param numExperiments number of experiments
     * @return average number of throws needed to reach the max dice roll result
     */
    private double calculateAverageThrowsUntilMax(int numDice, int numExperiments) {
        int totalThrows = 0;
        for (int i = 0; i < numExperiments; i++) {
            int throwsNeeded = simulateExperiment(numDice);
            totalThrows += throwsNeeded;
        }
        return (double) totalThrows / numExperiments;
    }

    /**
     * Simulate one experiment of rolling numDice until all dice show 6
     *
     * @param numDice number of dice
     * @return number of throws needed to reach all dice showing 6
     */
    private int simulateExperiment(int numDice) {
        int throwsNeeded = 0;
        boolean allSixes = false;
        while (!allSixes) {
            allSixes = true;
            for (int i = 0; i < numDice; i++) {
                int roll = throwOneDie();
                if (roll != 6) {
                    allSixes = false;
                    break;
                }
            }
            throwsNeeded++;
        }
        return throwsNeeded;
    }

    /**
     * Throw one die
     *
     * @return result of die throw
     */
    private int throwOneDie() {
        return rGen.nextInt(1, 6);
    }
}
Leave a Comment