View Full Version : [AS] Shuffle Function
Yeldarb
07-01-2005, 09:45 PM
I was bored so I saw how fast I could write a shuffle function in actionScript (PHP has one built in, but actionScript apparently doesn't -- at least not that I could find). It should randomly rearrange an array that you pass to it and return it.
Time: About 6 Minutes
myArray = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
trace(shuffle(myArray));
function shuffle(arrayIn) {
arrayOut = new Array();
size = arrayIn.length;
var i = 0;
while(i < size) {
index = random(size);
while(arrayOut[index] != undefined) {
if(index == (size-1)) {
index = 0;
} else {
index++;
}
}
arrayOut[index] = arrayIn[i];
i++;
}
return arrayOut;
}
your bored today, aren't you.
Yeldarb
07-01-2005, 10:15 PM
Extremely. But I'm leaving for vacation in about 15 minutes, so I won't be bored any more :P
edit: Is "size" a keyword in actionscript? It highlights it... but I don't think it is.
That means you'll be gone in 3 minutes.
Have fun on vacation!
It's a keyword, actually.
Amish
07-02-2005, 06:17 AM
i would turn it into a protoype like
myArray.shuffle()
EDIT
Mehh i was bored. I made the prototype version. The codings shorter and a tiny bit different.
myArray = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Array.prototype.shuffle = function() {
var i = 0;
arrayOut = [];
while (i<this.length) {
index = random(this.length);
while (arrayOut[index] != undefined) {
index == (this.length-1) ? index=0 : index++;
}
arrayOut[index] = this[i];
i++;
}
return arrayOut;
};
trace(myArray.shuffle());
One very elegant way to do that:Array.prototype.shuffle = function () {
this.sort(function () {return random(2) ;}) ;
} ;:)
Hahhahaha, way to one-up everyone, pom. :P
ElectricGrandpa
07-02-2005, 07:29 PM
It's much faster to do this:
myArray = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
trace(myArray.sort(randomSort));
function randomSort(){
return random(2);
}
-Matt
ElectricGrandpa
07-02-2005, 07:30 PM
noooo! Pom beat me by 5 minutes! Serves me right for opening lots of threads at once! haha ;)
Haha ;) By the way, I'm not sure this is the fastest way to shuffle an array (I'm talking efficiency here). I seem to remember that sort function is quite slow.
Hence the keyword here is "elegant," not "most efficient."
Well, you could always write your own sort function.
Amish
07-04-2005, 02:03 PM
Ermm that dosnt work for me. It just traces out an undefined error.
Yeldarb
07-04-2005, 02:47 PM
Which one Amish, mine or Pom's?
Nice code Pom :P
Shouldn't you be on vacation, Yeld? :P
Yeldarb
07-04-2005, 04:07 PM
I am, we have high speed internet at my lake house :D
broadband at your lake house - jeez dude thought i was bad lol - nice code pom:)
vBulletin® v3.7.0, Copyright ©2000-2009, Jelsoft Enterprises Ltd.