# Math.random() exercise solutions

Try the Math.random() exercises before viewing the solutions.

Practice using `Math.random()` with AP CS Tutor Brandon Horn.

## Exercise solutions

### Exercise 1

#### Step 1

``````double r = Math.random();
have: 0.0 <= r < 1.0
want: a <= r < b
``````

#### Step 2

``````double r = Math.random() * (b - a);
have: 0.0 <= r < b - a
want: a <= r < b
``````

#### Step 3

``````double r = Math.random() * (b - a) + a;
have: a <= r < b
want: a <= r < b
``````

The high end would be
`(b - a) + a`

which simplifies to
`b`

### Exercise 2

#### Step 1

``````int r = Math.random();
have: 0.0 <= r < 1.0
want: c <= r <= d
``````

#### Step 2

``````int r = Math.random() * (d - c + 1);
have: 0.0 <= r < d - c + 1
want: c <= r <= d
``````

Don’t worry about memorizing the exact formula here. The intent of this exercise is that you try, check the resulting range, and start over if the range isn’t what you want. This is one of the few situations in computer science where it’s advantageous to take a (reasonable) guess and check that it works.

#### Step 3

``````int r = (int) (Math.random() * (d - c + 1));
have: 0 <= r <= d - c
want: c <= r <= d
``````

The high end would be
`<= d - c + 1 - 1`

which simplifies to
`d - c`

#### Step 4

``````int r = (int) (Math.random() * (d - c + 1)) + c;
have: c <= r <= d
want: c <= r <= d
``````

The high end would be
`d - c + c`

which simplifies to
`d`

### Exercise 3

#### Step 1

``````int index = Math.random();
have: 0.0 <= index < 1.0
want: 0 <= index <= names.size() - 1
``````

We must determine the numeric range for our random index.

#### Step 2

``````int index = Math.random() * names.size();
have: 0.0 <= index < names.size()
want: 0 <= index <= names.size() - 1
``````

#### Step 3

``````int index = (int) (Math.random() * names.size());
have: 0.0 <= index <= names.size() - 1
want: 0 <= index <= names.size() - 1
``````

#### Step 4

``````int index = (int) (Math.random() * names.size());
System.out.println(names.remove(index));
``````

We use our random index to perform the requested operations. These could be performed using a call to `get` followed by a call to `remove`. The `remove` method already returns the element it removes, so the call to `get` is unnecessary.

### Exercise 4

``````Case I:   int sum = (int) (Math.random() * 8) + 1 + (int) (Math.random() * 8) + 1;

Case II:  int sum = 2 + (int) (Math.random() * 8) + (int) (Math.random() * 8);

Case III: int sum = ((int) (Math.random() * 8) + 1) * 2;
``````

(D) `I` and `II` only

Cases `I` and `II` are mathematically equivalent to each other. Both generate 2 random numbers in the correct range and add them together.

Case `III` generates numbers in the same range, but with different probabilities than Cases `I` and `II`. In Case `III`, every number in the range is equally likely. In Cases `I` and `II`, some numbers are considerably more likely than others.

Learn more about `Math.random()` with AP CS Tutor Brandon Horn.