How to Pick Random Unique Elements out of an Array

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

Retrieving Records with Max Values using TOP

I know I know, it’s a horrible title. If anyone has a better suggestion please let me know!

Here’s what I’m talking about:

I have two tables; the first table contains unique records describing games and the second contains game ids, scores, and user ids. Game id is joining the first table to the second in a one to many, something like this:

Games
======
gameID
gameName

GameScores
=========
gameID
userID
score

MY MISSION: Retrieve the user with the high score for each game in one query.

After much trial, error, and gnashing of teeth, the solution, as usual, proved to be ridiculously simple:


SELECT (select top 1 userID from GameScores where gameID = Games.gameID order by score desc) as topScoreUser,
                Games.gameName,Games.gameID, s.score
FROM Games
JOIN   GameScores s on s.gameID = Games.gameID

What this does is return one record for each game. Since I’m only returning the top record in the query and I’m ordering by score in descending order, I’m getting the top score and player for each game.

I’ve run into quite a few instances now where TOP has proved invaluable. Unfortunately it always seems to take me an hour of futzing around before I remember to use it!

-rG