October 28, 2009

Randomly Shuffle an Array

Filed under: Scripting — Marcus Tettmar @ 9:00 am

I was recently asked how to get a list of files from a folder, and then randomly shuffle that list. The following code retrieves the list of files to an array using GetFileList and Separate and then loops through the array shuffling it randomly:

GetFileList>c:\docs\*.*,file_list
Separate>file_list,;,files_array
If>files_array_count>0
  //randomize the array
  Let>k=0
  Repeat>k
    Let>k=k+1
    Random>{%files_array_count%-1},random_index
    Let>random_index=random_index+1
    If>random_index<>k
        Let>Temp=files_array_%k%
        Let>files_array_%k%=files_array_%random_index%
        Let>files_array_%random_index%=Temp
    Endif
  Until>k=files_array_count
Endif

Edit: As pointed out in the comments this is somewhat naive and could cause an element to be swapped back to its original position. A better method is given in the comments.