Topic: How to Array.shuffle() in ActionScript 2.0?
What method do people use to randomise/shuffle (an array) on the Chumby?
Thanks,
matt
You are not logged in. Please login or register.
chumbysphere forum → Flash/Widget → How to Array.shuffle() in ActionScript 2.0?
What method do people use to randomise/shuffle (an array) on the Chumby?
Thanks,
matt
Just pick two random indices and swap their contents a bunch of times.
var numSwaps:Number = 20;
var max:Number = myArray.length;
var i:Number;
var temp:Object;
var alpha:Number;
var beta:Number;
for (i=0; i<numSwaps; ++i) {
alpha = random(max);
beta = random(max);
temp = myArray[alpha];
myArray[alpha] = myArray[beta];
myArray[beta] = temp;
}
I eventually went with the code below, making sure the function is declared before using it:
// Array.shuffle() capability
Array.prototype.shuffle = function() {
var len = this.length;
var rand, temp, i;
for (i=0; i<len; i++) {
rand = random(len);
temp = this[i];
this[i] = this[rand];
this[rand] = temp;
}
};
Thanks to a quick Google
The problem with that function is that it only runs through the array once - you may want to shuffle a bit more than that to help ensure randomness (particularly on short arrays).
The problem with that function is that it only runs through the array once - you may want to shuffle a bit more than that to help ensure randomness (particularly on short arrays).
Actually, that's not necessary - mathematically, you won't be any more random by doing more than this single loop.
Another slight variation is Fisher-Yates:
Array.prototype.shuffleFY = function(o){
for (var j, x, i = this.length; i; j = int(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
return this;
};
Nice and compact, I like it.
chumbysphere forum → Flash/Widget → How to Array.shuffle() in ActionScript 2.0?
Powered by PunBB, supported by Informer Technologies, Inc.