»  The Delphi Column 

Random numbers, strings and words

In today's column, we have a detailed look at the function random.

Delphi provides a random number generator, that generates pseudo-random numbers.
Random numbers are often used in games, but also can be very useful for testing purposes. For example, you could use a generator of random words to populate a database.

Random numbers

The function random(n) returns a random integer number within the range 0 <= X < n.
If a range is not specified, the result is a floating type random number within the range 0 <= X < 1.

To initialize the random number generator, add a call to randomize before making any calls to random().

Random strings

For a random string, we start from a "seed" string, containing all the possible characters that we want to appear in our random string. Next, we generate some random numbers N, and for each of them we add character number N:

SeedString := 'abcdefghijklmnopqrstuvwxyz';
S = '';
for (i := 1 to 6 do begin   // string of 6 characters
  N := Random(Length(SeedString)) + 1;
  S := S + SeedString[N];

Random words

For a random word, we start from a "seed" array of strings, containing all the possible syllables (parts of words) that we want to appear in your random word. Next, we generate some random numbers N, from 1 to the number of desired syllables, and we add syllable number N:

Syllabs: array[1..8] of string = 
  ('bin', 'cla', 'del', 'for', 'lon', 'pre', 'sta', 'try');
S = '';
for i:= 1 to 3 do begin  // word of 3 syllables
  N := random(8) + 1;
  S := S + Syllabs[N];


  • Don't call randomize before each call to random(), once is enough (at the start of the program).
  • Delphi uses a pseudo random number generator (PRNG) that always returns the same sequence of 232 values each time the program runs. To avoid this predictability, use the Randomize procedure. It repositions into this random number sequence using the time of day as a pseudo random seed.
  • Don't use Delphi's function random() for cryptographically secure random numbers, you need something much stronger.
  • RANDOM.ORG is a true random number service that generates randomness via atmospheric noise.

Database Tutorials  FAQ  Crash Course Delphi  Tips  Source Code  Downloads  Links

Copyright 1999-2022