After I’ve post solution for shuffling an array with Array.sort method which purspose was to just show what a sort function can be used for I am now posting solution which is best for doing a shuffle of an array. There were few discussions about it on the web.
I’ve made a little test to demonstrate speed of testing
There are 4 methods
First one is Array.sort, second is using splice and last two are basiclly the same, one beign prototype for array and second is plain function which returns an array.
Speed test returned following results (could vary a little bit but not spectacular):
For 1500 elements
Sort – 2216 ms
Splice – 8300 ms
Prototype – 16 ms
Return Function -15 ms
You can take test file here
Prototype function and return function code is :
Array.prototype.mixElements = function() {
var _length:Number = this.length, rn:Number, it:Number, el:Object;
for (it = 0; it<_length; it++) {
el = this[it];
this[it] = this[rn = random(_length)];
this[rn] = el;
}
}
function mixArray(array:Array):Array {
var _length:Number = array.length, mixed:Array = array.slice(), rn:Number, it:Number, el:Object;
for (it = 0; it<_length; it++) {
el = mixed[it];
mixed[it] = mixed[rn = random(_length)];
mixed[rn] = el;
}
return mixed;
}
Code is only for AS2 but it can be easily turned into AS3 code
Pingback: ptolemy.co.uk » Blog Archive » Shuffling Arrays 2
Pingback: ptolemy.co.uk » Blog Archive » Shuffling Arrays 3
Pingback: Random array in AS2 & AS3 example using sort « Cyberspace Nova
Thanks! This was very helpful 🙂
I’m a novice when it comes to actionscript. I understand I can copy paste these examples, but I’m more interested in the logic behind what is going on. Is there anyone who has the time to write an explanation for at least one of the examples so I can apply this to anything I might need to do. Thank you!
AS3 version (sacrifying some millisecond to make it easier to read)
private function randomArraySort(_array:Array):Array {
var _length:Number = _array.length;
var mixed:Array = _array.slice();
var rn:Number;
var it:Number;
var el:Object;
for (it = 0; it<_length; it++) {
el = mixed[it];
rn = Math.floor(Math.random() * _length);
mixed[it] = mixed[rn];
mixed[rn] = el;
}
return mixed;
}
Thx its great:)
Slightly smaller AS3 version:
function randomizeArray(array:Array):Array {
var l:Number = array.length-1;
for (var it = 0; it<l; it++) {
var r = Math.round(Math.random()*l)
var tmp = array[it];
array[it] = array[r];
array[r] = tmp;
}
return array;
}
what is a arraY??? PLZ CAN U TELL ME PLZ I NEED TO KNOW FOR A TEST OR HOMEWORK RATHER!!!! by meggannn
excellent. many thanks to you.
@Tonypee: You code modifies the original array, and sometimes returns an extra empty element.
My version look like this:
private function randomizeArray($array:Array):Array {
var returnArray:Array = new Array();
var orgArray:Array = $array.slice();
while (orgArray.length > 0) {
var r:uint = Math.floor(Math.random()*orgArray.length);
returnArray.push(orgArray.splice(r, 1));
}
return returnArray;
}
It removes a random element from the array, and add it to another array. And keeps going until all elements have been randomized.
This is really useful thanks, i was also having problems with empty elements causing my array to have random errors though
I was making a randomized questions quiz with randomized answers (including the correct answer for each question and four random answers), and I kept seeing it repeat answers. It was mind-boggling, but I figured it out. I was checking for the value rather than the index in the splice function. Took me hours to figure out what I was doing wrong! XD
Pingback: Random Sort
@Anders : Your code creates a multi-dimensional array because you are pushing the return of the splice which itself is an array. Here’s the fix.
private function randomizeArray(srcArray : Array) : Array {
var returnArray : Array = new Array();
var orgArray : Array = srcArray.slice();
while (orgArray.length > 0) {
var r : uint = Math.floor(Math.random() * orgArray.length);
returnArray.push(orgArray.splice(r, 1)[0]);
}
return returnArray;
}
Actually, IMO, the Prototype function in the post above is not truly random, and is in fact what is called a poorly implemented Knuth shuffle…
http://en.wikipedia.org/wiki/Shuffle#Poorly_implemented_Knuth_shuffles
To achieve true randomness, the the cards must be randomly selected from the cards that have not yet been selected, rather than switching the card with any of the other cards, some of which have likely been switched already.
The correction to make is simple:
USE:
mixed[it] = mixed[rn = it + random(_length – it)];
NOT:
mixed[it] = mixed[rn = random(_length)];
Sorry for multiple posts, but I’m excited to be getting times of under 1 ms for 1500 value arrays…
Using “while” instead of “for”, as in the following function, reduces the processing time from 4 ms to 1 ms! So the stats are (Methods 1-4 are original, Method 5 is the while loop):
Method 1, time: 718
Method 2, time: 1957
Method 3, time: 3
Method 4, time: 4
Method 5 (while), time: 1, sometimes 0!
/////////////////////////
function mixArray(array:Array):Array {
var _length:Number = array.length, mixed:Array = array.slice(), rn:Number, it:Number, el:Object;
while (it < _length) {
el = mixed[it];
mixed[it] = mixed[rn = it + random(_length – it)];
mixed[rn] = el;
it++;
}
return mixed;
}
This is my own solution: http://www.daveoncode.com/2009/01/08/implementing-arrayshuffle-in-actionscript/
It’s only 3 lines of code and it works fine 🙂
@Tom Anderson: Yeah it gives you 0-1ms cause it is undefined, so the code doesn’t even run…
You need to change this line
var _length:Number = array.length, mixed:Array = array.slice(), rn:Number, it:Number = 0, el:Object;
Thank you Mr. Steel for the elegant prototype-based solution!
Pingback: how to make a square query « HKM Experimental Lab
Thanks for blog article & comments.
I thought I’d throw my hat into the ring. I took the shuffle function and have tried to optimise it. This is my effort and I get pretty good speed test results with it.
function Shuffle( array:Array ):Array{
var n:int = array.length, shuffled:Array = array.concat(), element:*, i:int = 0, r:int;
while( i < n ){
element = shuffled[ i ];
r = Math.floor( Math.random() * n );
shuffled[ i ] = shuffled[ r ];
shuffled[ r ] = element;
i++;
}
return shuffled;
}
//This is the best way of doing stuff.
function mixArray(array:Array):Void {
var i = array.length,el:Object,rn:Number;
while (i–) {
el = array[i];
array[i] = array[rn = random(i)];
array[rn] = el;
}
}
this is all just retyping variations of same method
Well, here it is again! But mine is the best I’m sure 😀
function shuffle(array) {
var n = array.length;
while (n > 1) {
n–;
var k = Math.floor(Math.random()*(n + 1));
var tmp = array[k];
array[k] = array[n];
array[n] = tmp;
}
return array;
}
Thanks! a fast code, and even better, fast to find on google 🙂
way faster than firing CS5’s help thing.
Pingback: 2010 in review « Cyberspace Nova
@Hai Phan
Why not:
function shuffle(array) {
var n = array.length;
while (n > 1) {
var k = Math.floor(Math.random()*(n));
n–;
var tmp = array[k];
array[k] = array[n];
array[n] = tmp;
}
return array;
}
But anyway – thi ain’t good shuffle at all – your entropy is decreasing with each step down.
This is good one:
function shuffle(array:Array):Array{
var n:uint = array.length;
var temp:Array = new Array();
while(n > 1){
temp.push(array[Math.floor(n * Math.random())]);
n–;
}
return temp;
}
Sorry, it should read:
function shuffle(array:Array):Array{
var n:uint = array.length;
var temp:Array = new Array();
while(n > 0){ // <- HERE WAS THE ERROR !!!
temp.push(array[Math.floor(n * Math.random())]);
n–;
}
return temp;
}
Oups – sorry – I see my there is a stuid flaw in my concept 🙂
This must be due to little sleep today – sorry again – the right code is this one:
function shuffle(array) {
var n = array.length;
while (n > 1) {
var k = Math.floor(Math.random()*(n));
n–-;
var tmp = array[k];
array[k] = array[n];
array[n] = tmp;
}
return array;
}
can i have some codes on how to random example a given 10 question.tnx..
greatest nude site.s baixar dominium men play blue highway ropa transparente sexy porn link on mediafire video amateur de sex francais indian overseas bank branches xiaolin showdown hentai
http://asses.sexblog.pw/?terry
photo plus belle blonde black download data structure throat c girls sucking dick on cam backstreet boys drowning bbw lesbian lezdom petgirls depositfiles kdv boys cms to feet conversion
Hey there, I think your blog might be having browser
compatibility issues. When I look at your blog in Opera, it looks fine but when opening in Internet Explorer, it has some overlapping.
I just wanted to give you a quick heads up!
Other then that, excellent blog!
but i think that Flash is no very good to google search optimization
i prefer only html on my site http://toplistapbf.toplista.eu/
This is very well composed. The article was informational to elocutionists who have a good value for articles. We look ahead for more of the same. He has described each and every little thing extremely beautifully and briefly.