Random Thoughts

The idea of randomness seems to be in the air. The difficulty human beings have in achieving true randomness is an important clue in One Shot, the Lee Child thriller (”Reacher said nothing”) I listened to recently on a trip to Vermont. Probability, randomness’s opposite number, is the subject of The Drunkard’s Walk by Leonard Mlodinow, favorably reviewed this week in the New York Times. Probability was discussed in the In Our Time podcast I listened to this weekend. And I’d been thinking about randomness in connection with our website.

What I wanted to do on the website was to present our clients’ logos and testimonials in a different (random) order each time the home page is loaded. I didn’t have any bright ideas on how to do this, except that it was rather like shuffling cards. I’m glad I Googled the solution, because my notions of how to do it were far more naive than the naive solutions.

Turns out that the preferred solution represents the thought of some very deep thinkers indeed. It’s called the Fisher-Yates shuffle. Fisher is Ronald Fisher, the biologist who was Darwin’s greatest successor (according to Richard Dawkins). Frank Yates was an eminent statistician who worked with Fisher. It’s a variant of the Knuth shuffle, developed by Donald Knuth, the revered computer scientist.

Here are Perl and JavaScript versions. I adapted the latter for use with the jQuery library. It shuffles an array of DOM elements.

jQuery.fn.shuffle = function() { //jQuery Fisher-Yates shuffle
  var myArray = this;
  var i = myArray.size();
  if ( i == 0 ){
    return myArray;
  }
  while ( --i ) {
     var j = Math.floor( Math.random() * ( i + 1 ) );
     var tempi  = myArray[i];
     var tempj  = myArray[j];
     myArray[i] = tempj;
     myArray[j] = tempi;
  }
  return myArray;
}