Shuffle

Created 2nd October, 2009 06:58 (UTC), last edited 8th October, 2009 04:49 (UTC)

This was something that I came across last week when I was doing a Flash training module for the Wimbledon Lawn Tennis Association.

In their final training module they wanted to ask random questions from various pools of questions. I.e. section 1 would have 6 question, 2 of which should be asked, section 2 might have 4 question 3 of which should be asked etc. A simple way of doing this is to shuffle the questions in each section and then take off the first n questions. JavaScript though doesn't have a shuffle function for arrays/lists, so how do you shuffle? Here are two alternative implementations:

Array.prototype.shuffle1 = function() {
    for ( var n = this.length; n > 1; ) {
        var k = Math.floor(Math.random()*(n--));
        var t = this[k];
        this[k] = this[n];
        this[n] = t;
    }
    return this;
}
Array.prototype.shuffle2 = function() {
    for ( var n = this.length; n > 1; --n) {
        var k = Math.floor(Math.random()*(n+1));
        var t = this[k];
        this[k] = this[n];
        this[n] = t;
    }
    return this;
}

Obviously we want the shuffle to be equally likely to produce any of the possible permutations. That is, it should produce an unbiased sample from all of the possibilities.

  1. Are these implementations capable of producing any of the permutations?
  2. Is there any difference (significant — in terms of output or bias — or maybe just stylistic etc.) between the two implementations?
  3. Is there a better alternative?
  4. What limits are there to the length of the array/list that is to be shuffled?

Categories:

Discussion for this page