Simple Example of Randomizing the order of an array in ActionScript


Posted By : David
Related Categories: Action Script,Flex,Flash

Just got asked this by a work mate and after asking Mr Google and looking at the Array Documentation came up with this (Flex based) example, so thought I would share 🙂

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml&#8221; layout=”vertical”>
<mx:Script>
<![CDATA[
private function myExample() : void
{
//can be an array of anything you like, but using letters here
var myArray   : Array   = ( “a,b,c,d,e,f,g,h,j,k,l” ).split(“,”);
//sort the array using my function
myArray.sort( myFunction );
debug.text = myArray.toString() + “\n” + debug.text;
}

//This function takes in 2 args, but we never use them…
private function myFunction( a : Object , b : Object ) : int
{
return ( Math.round( Math.random() * 10 ) – 5);
// return a random value above, below or on 0
}
]]>
</mx:Script>
<mx:Button label=”Make me Random” click=”myExample();”/>
<mx:TextArea id = “debug” height=”100%”/>
</mx:Application>

Advertisements

~ by mjcprasad2000 on July 11, 2009.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

 
%d bloggers like this: