Description |
The Randomize procedure is used in conjunction with the Random function. It repositions the random number generator in its sequence of 232 pseudo random numbers.
Randomize uses the time of day as the seed for this repositioning, so should provide a reliable method of creating an unpredictable sequence of numbers, even if they are a part of a predetermined sequence.
|
|
Related commands |
Random |
|
Generate a random floating point or integer number |
RandomRange |
|
Generate a random integer number within a supplied range |
RandSeed |
|
Reposition the Random number generator next value |
|
|
|
Example code : Run this code twice to see the effect of Randomize |
// Full Unit code. // ----------------------------------------------------------- // You must store this code in a unit called Unit1 with a form // called Form1 that has an OnCreate event called FormCreate. unit Unit1; interface uses // The System unit does not need to be defined SysUtils, Forms, Dialogs; type TForm1 = class(TForm) procedure FormCreate(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} // Include form definitions procedure TForm1.FormCreate(Sender: TObject); var
int : Integer;
i : Integer;
begin // If you run this program twice, only the first 5 values // will be guaranteed to be the same each time - randomize // repositions into a different part of the pseudo sequence // of random numbers.
// Get an integer random number in the range 1..100
ShowMessage('Fixed first 5 random numbers');
for i := 1 to 5 do
begin int := 1 + Random(100); // The 100 value gives a range 0..99
ShowMessage('int = '+IntToStr(int));
end;
// Now randomize to reposition
Randomize;
ShowMessage('');
// Get an integer random number in the range 1..100
ShowMessage('Random next 5 numbers');
for i := 1 to 5 do
begin int := 1 + Random(100); // The 100 value gives a range 0..99
ShowMessage('int = '+IntToStr(int));
end;
end; end.
|
Hide full unit code |
Fixed first 5 random numbers
int = 1
int = 4
int = 87
int = 21
int = 28
Random next 5 numbers
int = 35
int = 74
int = 45
int = 50
int = 31
|
|