Recipe 5.12. Randomizing the Elements of an Array


Problem

You want to randomize the elements of an array.

Solution

Use the sort( ) method with a compare function that randomly returns a positive or negative number.

Discussion

There are lots of scenarios in which you might plausibly want to randomize the elements of an array. For example, you may have a game in which you want to randomize the letters of a word. Since you already know how to split the letters into elements of an array using the split( ) method, you may need to randomize those elements. Or perhaps you are making a card game where each element in the array is a card, and you want to shuffle the deck.

There is more than one way to accomplish the task. However, one of the simplest ways is to create a compare function that randomly returns a positive or negative number, and use it in the sort( ) method. See Recipe 5.11 for more information on compare functions.

The following is probably the simplest possible compare function for the job:

function randomSort(elementA:Object, elementB:Object):Number {     return Math.random(  ) - .5 } 

Math.random( ) returns a number between 0.0 and 1.0. If you subtract 0.5 from that number, you'll get a random number between -0.5 and 0.5. Remember that in a compare function, returning a negative number means to order the first element first, and a positive number tells the sort( ) method to put the second element first. Since the odds you'll return are 50/50, the resulting order of the array is completely random.

The following is an example of randomizing an array:

var numbers:Array = new Array(  ); for(var i:int=0;i<20;i++) {     numbers[i] = i; } numbers.sort(randomSort); for(var i:int=0;i<numbers.length;i++) {     trace(numbers[i]); }

This creates an array of 20 sequential numbers, and then randomizes and displays them. You can verify that the order is now quite random.

See Also

Recipe 5.11 for more information on compare functions.




ActionScript 3. 0 Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2007
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net