2004. február 4., szerda

Generating random numbers


Problem/Question/Abstract:

How can I make Delphi 2 pick me any number within a range I specify (for example, between 0 and 100)? I'm guessing this is a fairly easy thing to do, but I couldn't find it in the manual...

Answer:

To get Delphi to pick any number within a specific range, you use the built-in random number generator. Here's a quick function to get you on your way:

function GetRandomInt(UpperRange: Integer): Integer;
begin
  Randomize;
  Result := Random(UpperRange);
end;

To get any number between 0 and 100, you'd call GetRandomInt, like so:

RandInteger := GetRandomInt(100);

So what's going on in the code? The first line, Randomize, initializes Delphi's random number generator. Then the second call, using the Random function, sets the function's result to a number between 0 and the UpperRange specified.

A quick note about the Random function: It's one of the very few functions in Delphi that can be overloaded; that is, you can have a variable number of parameters. With Random, it's either no parameters or an upper range. If you don't specify any parameters with Random (i.e. just declare Random;) the function will return a Real number between 0 and 1. If you specify an upper-range parameter, Random will return an integer between 0 and the upper range.

You might be thinking, "Wait a minute! I thought Delphi didn't support variable parameters other than open arrays."

It doesn't. But there are certain functions built into the Delphi engine that can take variable numbers of parameters. Random is one of them, and off the top of my head, I can't name others. In any case, play around with this. For another reference, look up Random in the help file.

Nincsenek megjegyzések:

Megjegyzés küldése