Generate random numbers with Math.random() 1

On the AP Computer Science Exam, you will be expected to be familiar with Math.random. You may be asked to use it to generate a random value within a specific range, generate a random valid index in an array or list, or make a conditional statement true with a specific probability.

The AP CS Elevens Lab and the AP CS Magpie Lab feature random number generation.

Part (a)

ArrayList<String> names = new ArrayList<String>();
/* code to add many more names to names */

String randomName = /* select a random name from names */;

Give code to replace /* select a random name from names */. Each name in names must have an equal probability of being selected.

Part (b)

double a = /* a number > 0 */
double b = /* a number > a */

Modify the statement below such that a <= r < b and that each value in the range has an equal probability of being assigned to r.

double r = Math.random();

Part (c)

if(/* condition */)
  /* statement */

Give code to replace /* condition */ such that /* statement */ will have a 25% probability of being executed when the code is run.

See the Random number generation solution or review it with AP CS Tutor Brandon Horn.

Get AP CS Help

One comment on “Generate random numbers with Math.random()

  1. Robbie D'Amato Mar 9,2015 9:27 am

    Thank you so much, this is very helpful!

Comments are closed.