Skip to content

Shuffling cards so all orders are equally likely

Question

Given a generator of uniform random numbers, how do you shuffle a deck of nn cards so that each of the n!n! orderings has the same probability?

Short answer

The Fisher-Yates shuffle, O(n)O(n) time. For i=ni=n down to 22, pick jj uniformly from 1,…,i1,\dots,i and swap cards ii and jj. The number of equally likely choice sequences is n⋅(n−1)⋯2=n!n\cdot(n-1)\cdots2=n!, one per permutation, so the result is uniform. Swapping each card with a position drawn from all nn is a common bug that biases the result.

Adapted from Zhou, A Practical Guide to Quantitative Finance Interviews, sec. 7.1 Algorithms, 'Random permutation A', p.175; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question

Start with a free lesson: Normal Distribution is part of a free topic. Create a free account, no card needed, to read it in full with worked solutions.

Read it free