Home > Enterprise >  Randomize value from selected list of numbers
Randomize value from selected list of numbers

Time:10-21

I want to generate a random number from some non-sequential integers, pseudocode:

iNum := Randomrange(1,5,7,13,20);

would return either 1, 5, 7, 13, or 20. How can I do that?

CodePudding user response:

procedure TForm1.FormCreate(Sender: TObject);
begin
{You must call Randomize once to create a seed}
Randomize;
end;

function TForm1.RandomChoice:integer;
const Options_Count = 5;
      Options : array [0..Options_Count-1] of integer = (1,5,7,13,20);
begin
Result := Options[Random(Options_Count)];
end;

CodePudding user response:

This is not good when you use a function with these inflexible parameters.

It could be better if you use an array as input to the function.

By the way, the RandomRange function exists and it is better if you use another name.

I will name it here RandomRange_2, you change it later:

function Randomrange_2(Integers: array of const): Integer;
begin
  Result := Integers[RandomRange(0, Length(Integers) - 1)].VInteger;
end;

To use it:

  Randomize;
  iNum := Randomrange_2([1, 5, 7, 13, 20]);
  ShowMessage(IntToStr(iNum));
  • Related