A Flash Developer Resource Site

# Thread: [F8] Randomly choose two unique values

1. ## [F8] Randomly choose two unique values

I'm trying to set two variables to random, UNIQUE values.
Currently I have something like this:
code:
```
var a:Number;
var b:Number;
a = getARandomNumber(min, max);

do{
b = getARandomNumber(min, max);
} while(b != a);

function getARandomNumber(min:Number, max:Number):Number {
var randomNum:Number = Math.floor(Math.random() * (max - min + 1)) + min;
return randomNum;
}
```

...which seems really sloppy (just repeatedly choosing a random number until it comes up with one that is not unique).
Also, it occasionally crashes the swf due to the script running too long.

Just curious if anyone has an elegant way of handling this. I'm sure there is a simple solution I am overlooking.
Thanks.

2. Is there any limits on the number?

3. Yes, the number will be an integer between a specified minimum and maximum (usually something like 0-6).

I've updated the code with the random number method.

4. Well, that seems sound, I've never messed with while statements though so I'm not sure about the syntax on that. But now that I've slept I notice a problem.

do{

b = getARandomNumber(min, max);

} while(b != a);

Is that not saying get a random number as long as b does not equal a? So every time it comes out with a number that is not equal to a it will start again.

So remove the ! and see if that works right.

5. Yeah, changing the != to == should fix the hanging, but if you'd still like to make it so that it will never have to come up with more than two random numbers, then reduce the max value for the second random number (b) by one, then if b>=a, add one to b.

6. You're absolutely right, it should be == . That should fix it, but it still seems a little wasteful.

Jibberuski's solution would work, except that it seems like it would favor a+1 as a result for b. Probably not a big deal though.

Thanks for your help spotting that.

7. No, it wouldn't because you increment b if it's equal to OR greater than a.

min:1
max:5

a=number between 1 and 5
a=3
b=number between 1 and 4
if b==1, b=1
if b==2, b=2
if b==3, b=4
if b==4, b=5

I had to do something like this for a random play on a DVD. There were 21 tracks and it has to choose between the remaining unplayed tracks. I had originally done it similar to a loop that keeps coming up with new numbers as long as it's one of the played tracks, but when it got to about 16 tracks played, some DVD players would get impatient and reboot.

But since you're only looking to exclude ONE number, you shouldn't have that problem.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 » Home » Movies » Tutorials » Submissions » Board » Links » Reviews » Feedback » Gallery » Fonts » The Lounge » Sound Loops » Sound FX » About FK » Sitemap