profile pic
⌘ '
raccourcis clavier

Produced an unbiased permutation: every permutation is equally likely.

Pseudocode:

"\\begin{algorithm}\n\\caption{Fisher-Yates shuffle}\n\\begin{algorithmic}\n\\REQUIRE An array $A$ of length $n$\n\\FOR{$i = n-1$ \\TO $1$}\n \\STATE $j \\gets$ random integer such that $0 \\leq j \\leq i$\n \\STATE swap $A[i]$ and $A[j]$\n\\ENDFOR\n\\end{algorithmic}\n\\end{algorithm}"

Algorithm 2 Fisher-Yates shuffle

Require: An array AA of length nn

1:for i=n1i = n-1 to 11 do

2:jj \gets random integer such that 0ji0 \leq j \leq i

3:swap A[i]A[i] and A[j]A[j]

4:end for

Implementation of modern Fisher-Yates algorithm

FisherYates.js
function sample(obj, n, guard) {
  if (n == null || guard) {
    if (!isArrayLike(obj)) obj = values(obj)
    return obj[random(obj.length - 1)]
  }
  var sample = toArray(obj)
  var length = getLength(sample)
  n = Math.max(Math.min(n, length), 0)
  var last = length - 1
  for (var index = 0; index < n; index++) {
    var rand = random(index, last)
    var temp = sample[index]
    sample[index] = sample[rand]
    sample[rand] = temp
  }
  return sample.slice(0, n)
}