Generalizing the Random Number Calculations

The preceding statement always assigns to variable face an integer in the range 1face6. The width of this range (i.e., the number of consecutive integers in the range) is 6, and the starting number in the range is 1. The width of the range is determined by the number 6 that’s passed as an argument to Random method nextInt, and the starting number of the range is the number 1 that’s added to the result of calling nextInt. We can generalize this result as

number = shiftingValue + randomNumbers.nextInt( scalingFactor );

where shiftingValue specifies the first number in the desired range of consecutive integers and scalingFactor specifies how many numbers are in the range.

It’s also possible to choose integers at random from sets of values other than ranges of consecutive integers. For example, to obtain a random value from the sequence 2, 5, 8, 11 and 14, you could use the statement

number = 2 + 3 * randomNumbers.nextInt( 5 );

In this case, randomNumbers.nextInt(5) produces values in the range 0–4. Each value produced is multiplied by 3 to produce a number in the sequence 0, 3, 6, 9 and 12. We add 2 to that value to shift the range of values and obtain a value from the sequence 2, 5, 8, 11 and 14. We can generalize this result as

number = shiftingValue +
   differenceBetweenValues * random Numbers.nextInt( scalingFactor );

where shifting Value specifies the first number in the desired range of values, differenceBetweenValues represents the constant difference between consecutive numbers in the sequence and scalingFactor specifies how many numbers are in the range.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset