Untitled
unknown
java
a year ago
2.0 kB
8
Indexable
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 * @param numExperiments * @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 throws = throwUntilMax(numDice); totalThrows += throws; } return (double) totalThrows / numExperiments; } /** * Throw the dice until the maximal result (only sixes) is achieved * @param numDice * @return number of throws until max result */ private int throwUntilMax(int numDice) { int throws = 0; while (true) { throws++; boolean allSixes = true; for (int i = 0; i < numDice; i++) { if (throwOneDie() != 6) { allSixes = false; break; } } if (allSixes) { break; } } return throws; } /** * Throw one die * @return result of die throw */ private int throwOneDie() { return rGen.nextInt(1, 6); } }
Editor is loading...
Leave a Comment