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.
Related posts:
I seem to remember this as one of my standard coding exercises for A level…..
Hi Phill,
Gosh, my high school computing teacher just commented on my blog. Blush!
Anyway, it probably was. As I was writing it I was reminded of 1st year university programming exam questions.
Hi Marcus,
Sorry to make you blush I am sure you can cope with it though.
And did you remember the drawback of this method?
* Entries may be swapped back to original position. Which can incur a processing time for no benefit.
True. This is better:
GetFileList>c:\users\user\documents\*.*,file_list Separate>file_list,;,files_array If>files_array_count>0 //randomize the array Let>k=files_array_count Repeat>k //get random number less than k Random>{%k%-1},random_index Let>random_index=random_index+1 Let>Temp=files_array_%k% Let>files_array_%k%=files_array_%random_index% Let>files_array_%random_index%=Temp Let>k=k-1 Until>k=0 EndifAnother approach would be to add a dimension to the array (or create a second temporary array) with a random number or GUID assigned to each element. Then sort on that element.
What’s wrong with the possibility of elements being put back in their original positions? Isn’t that what a part of randomness? Just like rolling 12 twice in a row with dice, or shuffling and then cutting and reverse stacking a deck of cards several times to ensure randomness and still have the same card float to the top as was there before. Shuffling and saying that NONE of the items in a set can EVER be in the same position they were in before isn’t truly random.
@Michael, nothing if that’s what you want. It is inefficient because items could be swapped back, wasting processing time. If you want the possibility of some elements to stay put then they may as well be skipped, rather than swapped and swapped again as that is processing overhead for no gain. You could also end up with no change at all – the smaller the list the likelier that is to happen. But it’s up to you. Choose the method that suits you best. You might prefer the suggested method of applying a random value to each element and sorting the list based on that value.