Everyone who has studied computer science has come across sorting algorithms, but how do you unsort? In programs involving randomizing the order of a known group of items — shuffling a pack of cards for instance — this is crucial. Now, you may think the best way to randomly pick values from an array of N elements is to generate random indices between 0 and N-1 to reference the array at random. However, you need some mechanism to prevent picking the same element twice. The best thing to do is to randomize the whole array using the following algorithm, which was invented in the 1950’s by two computer scientists called Fisher and Yates.
The Fisher-Yates Shuffle
To shuffle an array a of n elements: for i from n−1 to 1 j ← random integer with 0 ≤ j ≤ i exchange a[j] and a[i]