The Riser
The Riser

Reputation: 329

Select random elements from an array without repeat in AS2

I have an array containing 3 variables,i want to randomly pick 2 of them without picking the same element twice,I did find a question by someone trying to do the same thing except they were working with AS3,and their issue was entirely different:Select random elements from an array without repeats?

here's my attempt:

var ar:Array=[k,l,m];
var raar:* = ar[Math.floor(ar.length * Math.random())];

I'm still new to AS2 and I don't how to utilize certain data types,how do I get this to work?

Upvotes: 1

Views: 739

Answers (1)

akmozo
akmozo

Reputation: 9839

Instead of picking twice an element for your array, you can simply generate once a random index which will be the element that won't be used (picked), like this :

var a:Array = [10, 20, 30];
var n:Number = Math.floor(a.length * Math.random());

a.splice(n, 1);     // remove the element with the index n
trace(a);           // for n = 1, gives : 10, 30

Hope that can help.

Upvotes: 1

Related Questions