There is a short version using the Array.sort () function:
var arr : Array = [0,1,2,3,4,5,6,7,8,9]; function randomize ( a : *, b : * ) : int { return ( Math.random() > .5 ) ? 1 : -1; } trace( arr.sort( randomize ) );
If you don't get "enough" randomness, you can sort twice :)
EDIT - line by line explanation:
For the Array class sort() method, you can pass not only sorting parameters, such as Array.CASEINSENSITIVE, Array.DESCENDING , etc., but also your own reference to the comparison function (callback), which takes two parameters (two elements from an array for comparison), From the AS3 documentation:
The comparison function must take two arguments for comparison. Given the elements A and B, the result of compareFunction can have a negative, 0, or positive value:
- A negative return value indicates that A appears before B in a sorted sequence.
- A return value of 0 indicates that A and B have the same sort order.
- A positive return value indicates that A appears after B in a sorted sequence.
Note. The parameters of the comparison function can be printed (if your array is printed) and have whatever name you want, for example:
function compareElements ( elementA : SomeClass, elementB : SomeClass ) : int;
This method is very useful when you need to sort the elements of an array according to their special properties. In case of accident, compareFunction randomly returns -1, 0 or 1 and forces the elements of the array to switch to their places (indices). I found that the best randomization (in my subjective and mathematically untested opinion) is that the method returns only -1 and 1 . Also keep in mind that the sort function with a custom comparison function does not compare items sequentially , so in some special cases, the randomization results may differ from the expected ones.