Back to DFS's Pascal Page


Generating Random Values

One of the major uses for computers is to simulate what happens in the real world. It is up to the programmer to write the programs that mimic what is happening around us. Fundamental to this is the ability to generate random values and take action based on these values.

Turbo Pascal provides a procedure called Randomize and a function called Random so you can use random values in your programs.

Randomize

Randomize establishes a table of pseudo-random values. It should be called only once in your program, and this should be before your first call to Random. The best place in your program to call Randomize is in the set-up section (either at the beginning of the Main Line or in a procedure) where you initialize variables and prepare the screen for output.

If you do not call Randomize, Random will always return the same sequence of values. This is useful when you are testing/debugging your program.

Random

Random is a function -- it returns a value from a default table or one set up by Randomize. There are two ways that Random can be used.

Generating Non-Sequential Values

To generate one of the odd Natural numbers less than 10 (i.e., one of the set 1, 3, 5, 7, 9), we would need to generate one of five values and then proceed to select a corresponding member of the set. This can be done by setting up a table of the correspondences and determining a mathematical relationship.

Random(5)Ran
01
13
25
37
49

If the columns are treated as the traditional x and y, the relationship could be expressed as

y = 2x + 1
resulting, by simple substitution in the Pascal statement:
Ran := 2 * Random(5) + 1

Generating Alphabetic Characters

For some situations, you may want to generate one of the letters of the alphabet. Since Random returns integer values, you would need to convert the value into data of type Char.

ranletter : Char;

ranletter := chr( ord('a') + random(26) )
The above statement uses the value returned by Random as an offset into the set of values used to represent the lowercase letters in the ASCII character set. First it gets the ordinal value of the character 'a' (which is 97) from the function Ord and then it adds the value returned by Random (which is in the range 0 to 25). The resultant integer value is then passed to the function Chr which returns the corresponding character, which is finally stored in the variable ranletter. N.B. This will not work if the system is using EBCDIC.

Or you may want to generate just one of the lowercase vowels. This can be accomplished in a number of ways, one of which follows.

ranvowel : Char;

case Random(5) of
  0: ranvowel := 'a';
  1: ranvowel := 'e';
  2: ranvowel := 'i';
  3: ranvowel := 'o';
  4: ranvowel := 'u'
end

Back to Top


© 2000 DFStermole
Created 12 Jan 00