Q9 College Board
Math.random()
for Simulating Dice Rolls
Introduction
Math.random()
is used in programming to generate a random decimal between 0 and 1.
Math.random()
Range
- Multiplying
Math.random()
by 6 gives us what range?
Adjusting the Die Range
- To get a die range of 1-6, we add 1 to the result of
Math.random() * 6
.
Simulating Two Dice
- Rolling two dice means adding two
Math.random()
results together.
Process of Elimination
- Incorrect options are eliminated based on the range and sum that do not match two dice rolls.
Conclusion
- The correct code to simulate rolling two dice is option E:
2 + (int)(Math.random() * 6) + (int)(Math.random() * 6)
.
Steps/Process for Q9
Math.random()
generates a number from 0 (inclusive) to 1 (exclusive).
- To simulate a die roll, we need a range of 1-6, not 0-5.
- Multiplying the
Math.random()
result by 6 gives a range of 0-5.
- To adjust for the correct range of a die, we add 1 to the result.
- We need to simulate rolling two dice and sum their values.
- Using
int
truncates the decimal, giving us a whole number as expected when rolling dice.
- Options A, B, and D were eliminated because they don’t meet the criteria above.
- Between options C and E, we choose E because it correctly adjusts the range from 0-5 to 1-6 by adding 1 to each die roll.
- The process of elimination helped narrow down the options to the correct answer.
Hacks
Code Q9 in java, where it rolls two dice, displays each dice and finds the sum of both of them, using Math.Random
public class DiceRollSimulator {
public static void main(String[] args) {
// finish the method
}
}
DiceRollSimulator.main(null)