Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate an uniform random permutation

Tags:

algorithm

I am not sure whether the following pseudo-code can generate an uniformly random permutation:

PERMUTATE(A): 
    n = A.length
    for i = 1 to n
        swap A[i] and A[random(1,n)]

It seems to be right, but can anyone give me a rigorous proof to verify its correctness or wrongness ?

like image 973
Flybywind Avatar asked Oct 26 '11 12:10

Flybywind


1 Answers

This solution is biased, you want the Fisher Yates algorithm [which is similar] for non biased permutation. [basically, you need to swap with random(i,n) instead of with random(1,n)]

This thread discusses how and why your solution is biased.

like image 83
amit Avatar answered Nov 19 '22 18:11

amit