September 16, 2005

Pulling random elements from an array

A handy bit of action script to pull random elements from an array, I recently used this function for a flash piece where I needed 3 random images from a pool of 9 images given from an XML file:

The ActionScript:

var tstArray:Array = new Array(1,2,3,4,5,6,7,8,9);
trace(tstArray)
for(var i:Number = 0; i<3; i++){
          var x:Number = Math.floor((Math.random()*tstArray.length));
          trace("X :: " + x);
          trace("ARRAY VALUE :: " + tstArray[x]);
          tstArray.splice(x,1);          
     }
delete tstArray;
trace("----------------------------------");

Hope someone finds use for this!

-DesDev    

5 comments:

Unknown said...

Hey DesDev!

This came in really handy for a random letter generator I made. Its on my developing project at the myspace derive

DesDev said...

Glad it helped! Looks like an interesting app you're creating there.

Unknown said...

Hi just wondering how much more complicated it would be to pull randomly from the array without repeating the object until all of the objects have been picked? I hope I am making sense - could the objects be moved to a new array so they are not picked twice and then once, all have been displayed, the program would pick from the second array again?

Jibestream said...

Very helpful, how do i turn it back to display the array like this:

1,2,3,4 rather than:

1
2
3
4

Thanks :)

Billoo said...

Thank you DesDev your script really helped me in one of my very big project :)