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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With