This adds shuffle method to array prototype to randomize the order of it's elements
Array.prototype.shuffle = function() { var len = this.length; var i = len; while (i--) { var p = parseInt(Math.random()*len); var t = this[i]; this[i] = this[p]; this[p] = t; } };
Or just as a simple function:
function arrayShuffle(theArray) { var len = theArray.length; var i = len; while (i--) { var p = parseInt(Math.random()*len); var t = theArray[i]; theArray[i] = theArray[p]; theArray[p] = t; } };
function arrayShuffle(oldArray) { var newArray = oldArray.slice(); var len = newArray.length; var i = len; while (i--) { var p = parseInt(Math.random()*len); var t = newArray[i]; newArray[i] = newArray[p]; newArray[p] = t; } return newArray; };
Or as a function that returns a new shuffled array and leaves the original array alone:
Array.prototype.shuffle = function() {
var i=this.length,p,t;
while (i--) {
p = Math.floor(Math.random()*i);
t = this[i];
this[i]=this[p];
this[p]=t;
}
};
That way p is taken from a diminishing pool and can't be assigned a value that has already been assigned? Simpler too. Seems to work anyway.