views:

37

answers:

2

i have an array in as3 which has elements like MyArray2[0] = 25;
MyArray2[1] = 31;
MyArray2[2] = 45;
MyArray2[3] = 50;
MyArray2[4] = 81; MyArray2[5] = 90;
MyArray2[6] = 94;

i want to randmize this array and array may contain more values ... what should i do?? i have made the dirty alogrithm for it... i need some good optimize way??

A: 

Put all the possible numbers in a linked list. Then, create a destination array which will contain your results. For each element in the result array, select a random number between 0 and the length of your linked list. Take that item in the linked list, remove it from the list (so that you won't pick it in the future), and place its value in the result array. Repeat.

When you're done, all the original numbers will be randomly distributed in the result array, and you won't have had to do any comparisons along the way.

Curtis
but i do not see any built-in library functions for linked list so do i have to use third party library??
Muhammad Irfan
I'm a Java developer, not AS3, so I can really only speak to the algorithm itself. But a linked list is a pretty simple structure - maybe this will help?: http://blog.alanklement.com/2009/11/27/data-structors-with-as3-linked-list/
Curtis
A: 

Haven't looked at AS3 in a long while, but here's some basic code that you should be able to use pretty easily.

var tmpVal, tmpInd, len;

len = MyArray.length;
for(var i=0; i < len; i++) {
    tmpInd = random(0,len);//grab a random index
    tmpVal = MyArray[tmpInd];//store the value
    //swap the values
    MyArray[tmpInd] = MyArray[i];
    MyArray[i] = tmpVal;
}

Basically, you're just iterating over the array and swapping each element with a random element.

blazeprogrammer