Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
1.4 kB
6
Indexable
Never
import acm.program.ConsoleProgram;
import de.ur.mi.util.RandomGenerator;

public class StartDiceExperiment extends ConsoleProgram {

    private RandomGenerator rGen = RandomGenerator.getInstance();

    public void run() {
        int numDice = readInt("Anzahl der Würfel: ");
        int numExperiments = readInt("Wie oft soll das Experiment wiederholt werden? ");
        double avgThrows = calculateAverageThrowsUntilMax(numDice, numExperiments);
        println("Es braucht im Durchschnitt " + avgThrows + " Würfe um die höchste Zahl zu würfeln.");
    }

    private double calculateAverageThrowsUntilMax(int numDice, int numExperiments) {
        int totalThrows = 0;

        for (int i = 0; i < numExperiments; i++) {
            int tries = tryUntilMax(numDice);
            totalThrows += tries;
        }

        return (double) totalThrows / numExperiments;
    }

    private int tryUntilMax(int numDice) {
        int tries = 0;

        while (true) {
            tries++;
            boolean allSixes = true;

            for (int i = 0; i < numDice; i++) {
                if (rollOneDie() != 6) {
                    allSixes = false;
                    break;
                }
            }

            if (allSixes) {
                break;
            }
        }

        return tries;
    }

    private int rollOneDie() {
        return rGen.nextInt(1, 6);
    }
}
Leave a Comment