Glen Morse
Glen Morse

Reputation: 2593

Random File Name

i have a folder called MAPS. I would like when a menu item is selected , in this case its Maps->Random. That it will randomly select one of the file names in the folder map. how can i make it random?

Upvotes: 2

Views: 1160

Answers (1)

David Heffernan
David Heffernan

Reputation: 612804

Get the list of file names in the folder:

uses
  System.Types, System.IOUtils;

var
  FileNames: TStringDynArray;
....
FileNames := TDirectory.GetFiles(DirectoryName);

And then pick an index at random.

var
  Index: Integer;
.....
Index := Random(Length(FileNames));

So, your random filename is given by

FileNames[Index];

Call Randomize on startup to ensure that the user doesn't get the same sequence of random numbers each time they run the program.

This isn't the most efficient approach since it allocates strings for each file in the directory, and then you use only one. However, it's probably the most convenient and simple approach.

Upvotes: 4

Related Questions