Analysis of Algorithms : An Active Learning Approach

(Ron) #1

262 APPENDIX B


Because of the mod operation, the seed value will always be between zero and
m 1. The division of the seed by m means that this process will always return
a number in the range 0 ≤N < 1.
If the three constants of p,i, and m are relatively prime, meaning that they
have no factors in common, the resulting sequence will produce m different
values before it repeats. For example, if p is 25,173, i is 13,849, and m is
65,536, this function will generate a series of 65,536 different values before it
repeats. For testing purposes, the initial seed value can be set to zero, produc-
ing the same sequence each time. After testing, the initial seed value could be
set to the seconds or milliseconds portion of the system clock to give a more
random appearance to the sequence.

B.1 GENERATING NUMBERS IN A DIFFERENT RANGE
Frequently, an application of random numbers will need values in a range
different from that generated by RanNum( ). If we need a value in the range
Low ≤N < High, the following equation will create them:
(High - Low) * RanNum( ) + Low

B.2 EXAMPLE APPLICATION
Suppose that we need a list of the numbers between 1 and N in a random
order. There are a few ways that we could create this list.

■ B.2.1 Method 1
If we initialize the list locations to zero, as we place values in the list, “empty”
locations will still be zero. In this first method, we will place the numbers from
1 to N into random places in the list. If the random location we choose is zero,
it is available for the next number. If not, we just generate another random
location. This gives the algorithm
for i = 1 to N do
list[i] = 0
end for
for i = 1 to N do
Free download pdf