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.