Random Permutation Generation
Given an array A of items, come up with an algorithm that produces a random permutation of A on every run
Approach 1
for (i from 1 to n) do
j = random(1,n)
swap(A, i, j)Approach 2
randomPermutation(A)
create new array B[] of size = A.length;
for (i = 0 to i = n-1)
do
choose j = random(1,n)
while A[j] is picked // keep trying to find a j such that A[j] has not been picked yet
// once you have found your A[j],
B[i] = A[j]
mark A[j] as picked
// for every value of i from 0 to n-1, you are essentially picking a random element from A and assigning it to B[i]
// you need to mark as picked to make sure that B is ultimately a permutation of A (and you have not added the same
// element multiple times or forgotten to add some element)Best Random Permutation Algorithm
Checking Randomness?
Application Question
Last updated