Fisher-Yates shuffle

This is what you need for card games! The Fisher-Yates (or Knuth) shuffle ensures that all permutations of the set are equally likely (it’s unbiased).

Here’s the code in JavaScript, using a function that has an array a passed to it. When it comes to swapping the array elements there are various tricky ways of doing it, but I prefer to just do it in the most obvious way.

function shuffle(a) {
  for (var i = a.length - 1; i >= 1; i--) {
    var j = Math.floor(Math.random()*(i + 1));
    var tmp = a[i];
    a[i] = a[j];
    a[j] = tmp;