Okay, finally getting down to what I wanted to do when I jumped into WordPress this morning!
I’ve often wanted to randomize an Array. You know, take an Array and shuffle it up. Maybe I’ve got a list of images to show in a slideshow but don’t want to show them in order. Whatever… there are tons of reasons to mix up an array.
Here’s the code to do it:
1 2 3 4 5 6 7 8 9 10 11 | // create the Array var a:Array = [1,2,3,4,5,6,7,8,9,0] // create a comparison function that will be passed // to the Array.sort() method function randomSort(objA:Object, objB:Object):int { return Math.round(Math.random() * 2) - 1 } // randomize the Array! a.sort(randomSort); |
Basically, the Array.sort method compares two elements at a time to determine which should be first, objA or objB. In this example, the sort() method uses the function that’s passed in as its sole argument. In this case our sorting function doesn’t actually have any logic built into it to compare the elements. It simply returns either -1, 0, or 1. Taken from the official ActionScript 3 reference:
A comparison function used to determine the sorting order of elements in an array. This argument is optional. A comparison function should take two arguments to compare. Given the elements A and B, the result of compareFunction can have a negative, 0, or positive value:
- A negative return value specifies that A appears before B in the sorted sequence.
- A return value of 0 specifies that A and B have the same sort order.
- A positive return value specifies that A appears after B in the sorted sequence.
4 Comments
Dudes, your hard effort has saved me a lot of time and hair-pulling for this urgent assignment i need to get done in like 1 day!!!
THANKS MAN!! God bless you!! :D
Works great!
the shuffling is not happening properly
3 9 1 4 5 6 7 8 2 0
3 2 5 4 6 1 7 8 9 0
Sometimes random isn’t as random as you want it to be. Those results look pretty typical to me.