Determining the Range – Selected API Classes

Determining the Range

We are often interested in generating random numbers in a particular range. For example, the following code will return a random number in the interval [0, 10]:

Click here to view code image

number = generator.nextInt(11);      // Random integer in the interval [0, 10]

If the bound value is n, the integer returned is in the interval [0, n-1]. By supplying a new bound value to the nextInt() method, we can change the upper bound of the original interval.

If we want to shift the interval, we can add (or subtract) an offset from the value returned by the nextInt() method. In the code below, values generated in the original interval [0, 10] will now lie in the interval [2, 12]—that is, the offset 2 maps the interval [0, 10] onto the interval [2, 12]:

Click here to view code image

number = 2 + generator.nextInt(11);  // Random integer in the interval [2, 12]

If we want the values in the interval to have a distance greater than 1, we can multiply the value generated by a distance value:

Click here to view code image

number = 2 + 3*generator.nextInt(5); // Random integer in the set {2, 5, 8, 11, 14}

With a distance value of 3, the expression 3*generator.nextInt(5) always returns a value in the set {0, 3, 6, 9, 12}, and an offset of 2 ensures that the variable number is assigned a value from the set {2, 5, 8, 11, 14}.

We can simulate a dice roll as follows:

Click here to view code image

int diceValue = 1 + generator.nextInt(6);  // A dice value in the interval [1, 6]

The expression generator.nextInt(6) always returns a value in the set {0, 1, 2, 3, 4, 5}, and an offset of 1 ensures that the variable diceValue is assigned a value from the set {1, 2, 3, 4, 5, 6}.

Leave a Reply

Your email address will not be published. Required fields are marked *