I saw a post on Kirupa’s Flash 8 forum recently asking how to display x random unique images from an array of y images. It sounded like a good free-time exercise so I took it on.
Essentially, all we really need to do here is pick x unique random numbers between 0 and the image array length. We can then use the random number as the array index to the image element. Picking the random numbers is easily done using Math.random. The only slight challenge here was to make sure they were unique.
In my example I will be choosing 3 random numbers from 10 array elements.
Here’s what I came up with:
var myImages:Array = new Array("pic1.jpg","pic2.jpg","pic3.jpg","pic4.jpg","pic5.jpg","pic6.jpg","pic7.jpg","pic8.jpg","pic9.jpg","pic10.jpg");
var topThree:Array = new Array();
var randomNumber:Number;
var dupe:Boolean = false;
var i:Number;
var j:Number;
for (i=0;i<3;i++) {
dupe=false;
randomNum = Math.floor(Math.random() * (myImages.length - 1 + 1)) + 1;
if (topThree.length == 0) {
topThree.push(randomNum);
} else {
for(j=0;j
Have an easier way? Feel free to post it.
-rG