Jose Martinez
Jose Martinez

Reputation: 313

Random value in array with Delphi

I have the following code.

const
   dimensions: array [1 .. 5] of string = ('100 ', '200', '300 ', '400', '500 ');

What I do is pick a random value in that array to display on ShowMessage ();

But how to do that, someone might say as you chose a random value from an array?

Upvotes: 1

Views: 5619

Answers (2)

Xander Blackstar
Xander Blackstar

Reputation: 15

The easiest solution is this

    myString := dimensions[Random(Length(dimensions))];

Remember to initialize the random seed before using Random, otherwise you will not be getting a "true" random value.

    Randomize;
    myString := dimensions[Random(Length(dimensions))];
    Showmessage(myString);

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 612834

You can use RandomRange to pick a value between 1 and 5. Do so like this:

Index := RandomRange(1, 6);

It may seem a little counter-intuitive, but the lower limit is inclusive, and the upper limit is non-inclusive.

Another way would be to use Random directly:

Index := 1 + Random(5);

You could even do away with your array and write:

IntToStr(100*RandomRange(1, 6))

Upvotes: 3

Related Questions