Solution to random number generation with Math.random()

Complete the Random number generation practice problem before reviewing the solution.

Review the Random number generation solution with AP CS Tutor Brandon Horn.

Part (a)

names.get( (int) (Math.random() * names.size()) ) will select a random value from names with each value in names having an equal probability of being selected.

Math.random() generates a double in the range of [0.0, 1). Multiplying that value by names.size() and casting the result to an int results in a value in the range of [0, names.size) which spans the range of valid indexes in names.

Part (b)

double r = Math.random(); results in r being assigned a value such that 0 <= r < 1.

Multiplying the result of Math.random by b – a would change the assignment statement to

double r = Math.random() * (b – a) and would result in values for r such that 0 <= r < b – a.

Adding a would change the statement to

double r = Math.random() * (b – a) + a and would result in values for r such that a <= r < b, which is the desired range.

Part (c)

The code to replace /* condition */ should be Math.random() < 0.25. The statement will be true 25% of the time.

This technique is particularly helpful in the GridWorld Case Study when a Bug or other Actor is supposed to perform an action with a specific probability.

Get AP CS Help

Leave a Reply