Update: my Vector shuffle function will not work with Vector.<int>. Please read AS3 Object shuffle or randomize for an improved and more generic shuffleObject function.

In almost all tools we develop for Gynzy and bord.nl the questions are randomized. When searching the net for a generic function to shuffle Actionscript Vectors, I couldn’t find any. That’s why I wrote this article and a shuffleVector function.

It all started with shuffling Arrays. My colleague Mathijs showed me this article about Fisher-Yates shuffling: it’s efficient both in runtime and space and the result is really random.
Mathijs translated the example Python code into Actionscript and I added some comments:

For me, it’s very convenient to have one function for shuffling all my Vectors. The only improvement I can think of is the “as Vector.<*>” part when calling the function: VectorUtils.shuffleVector(myVector as Vector.<*>);
If you have any suggestions to make this function call more elegant, please let me know.

Note:We use com.gskinner.utils.Rndm class because it generates random numbers based on a seed number: necessary if you have to reproduce a random output.
If you don’t have or want to use this class, change line 11var s:Number = Rndm.integer(0, vec.length);
intovar s:Number = Math.round(Rndm.random()*(inVector.length-1));var s:Number = Math.round(Math.random()*(vec.length));

7 responses to “AS3 Vector shuffle or randomize”

Note: We use com.gskinner.utils.Rndm class because it generates random numbers based on a seed number: necessary if you have to reproduce a random output.
If you don’t have or want to use this class, change line 11
var s:Number = Rndm.integer(0, vec.length);
into
var s:Number = Math.round(Rndm.random()*(inVector.length-1));