Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is fisher yates the most useful shuffling algorithm?

Would you say modern version of fisher yates is the most unbiased shuffling algorithm? How would you explain that each element in the array has a probability of 1/n being in its original spot?

like image 297
Phoenix Avatar asked Mar 17 '10 00:03

Phoenix


People also ask

Is Fisher-Yates efficient?

The modern version of the algorithm is efficient: it takes time proportional to the number of items being shuffled and shuffles them in place.

What is the shuffle algorithm used in music player?

Most music players uses a minimal randomization algorithm known as Fisher-Yates algorithm. Fisher–Yates shuffling is similar to randomly picking numbered tickets out of a hat without replacement until there are none left.

Is there an algorithm for Shuffle?

Fisher-Yates shuffle is one such algorithm for achieving a perfect shuffle using random number generator. Algorithm is named after Ronald Fisher and Frank Yates who first described this algorithm in their book in 1938. Later Donal Knuth and Richard Durstenfeld introduced improved version of the algorithm in 1964.

What is Fisher-Yates method in Javascript?

The Fisher-Yates algorithm is named after Ronald Fisher and Frank Yates. It's an algorithm used to shuffle a sequence of finite items, like an array for instance. The algorithm works by swapping a random element from your array with the last element in that array repeatedly.


1 Answers

Given a perfect pseudo-random number generator (the Mersenne Twister is very close), the Fisher-Yates algorithm is perfectly unbiased in that every permutation has an equal probability of occurring. This is easy to prove using induction. The Fisher-Yates algorithm can be written recursively as follows (in Python syntax pseudocode):

def fisherYatesShuffle(array):
    if len(array) < 2:
        return

    firstElementIndex = uniform(0, len(array))
    swap(array[0], array[firstElementIndex])
    fisherYatesShuffle(array[1:])

Each index has an equal probability of being selected as firstElementIndex. When you recurse, you now have an equal probability of choosing any of the elements that are still left.

Edit: The algorithm has been mathematically proven to be unbiased. Since the algorithm is non-deterministic, the best way to test whether an implementation works properly is statistically. I would take an array of some arbitrary but small size, shuffle it a bunch of times (starting with the same permutation as input each time) and count the number of times each output permutation occurs. Then, I'd use Pearson's Chi-square Test to test this distribution for uniformity.

like image 50
dsimcha Avatar answered Sep 20 '22 16:09

dsimcha