**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:

```
/**
* Shuffles array with Fisher-Yates shuffling
* using com.gskinner.utils.Rndm class
* @param arr
* example: ArrayUtils.shuffleArray(myArray);
*/
public static function shuffleArray(arr:Array):void{
if (arr.length > 1){
var i:int = arr.length - 1;
while (i > 0) {
var s:Number = Rndm.integer(0, arr.length);
var temp:* = arr[s];
arr[s] = arr[i];
arr[i] = temp;
i--;
}
}
}
```

But what I really needed was a function to shuffle any kind of Vector. So I took the function above and changed it into this:

```
/**
* Shuffles Vector with Fisher-Yates shuffling
* using com.gskinner.utils.Rndm class
* @param vec
* example: VectorUtils.shuffleVector(myVector as Vector.<*>);
*/
public static function shuffleVector(vec:Vector.<*>):void{
if (vec.length > 1){
var i:int = vec.length - 1;
while (i > 0) {
var s:Number = Rndm.integer(0, vec.length);
var temp:* = vec[s];
vec[s] = vec[i];
vec[i] = temp;
i--;
}
}
}
```

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 11
*

`var s:Number = Rndm.integer(0, vec.length);`

into
`var s:Number = Math.round(Rndm.random()*(inVector.length-1));`

`var s:Number = Math.round(Math.random()*(vec.length));`

## Leave a Reply