Patrick Ward words, code, and music

Randomizing Javascript Arrays

I needed to randomize a list of images the other day using Coffeescript. So, I investigated a few techniques for doing that. Apparently, the Fisher Yates algorithm (or Knuth shuffle) is one of the most efficient methods to randomize an array of values, because each roll of the dice is just as likely as another.

The following methods perform an in-place shuffle of the contents of an array. Original javascript algorithm can be found here.

randomizeArray = (arr) ->
  i = arr.length
  if i == 0 then return false
  while --i
    j = Math.floor(Math.random() * (i+1))
    [arr[i], arr[j]] = [arr[j], arr[i]]
  arr
function randomizeArray(arr) {
  var i = arr.length;
  if (i == 0) return false;
  while (--i) {
    var j = Math.floor(Math.random() * (i + 1) );
    var tempi = arr[i];
    var tempj = arr[j];
    arr[i] = tempj;
    arr[j] = tempi;
  }
  return arr;
}