Quick Tip #1 – Randomize an ActionScript 3 Array

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.

7 thoughts on “Quick Tip #1 – Randomize an ActionScript 3 Array

  1. 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

    • I found the same results. Typically the last few would be more or less in the same position and same with the first few. I tried this at least 30 times. However, if i run this 3x or 4x in a row, THEN look at the results, it’s far more random.

      Maybe I’m not understanding what is actually going on…Is this just going through the array in order, saying “value 1 is before value 2″, “value 2 is after value 3″, etc? If so, then isn’t there an inherent flaw in it, as its most likely that the first few will stay in the beginning of the choices?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">