# Tutorial :Can i random an array with no reptition of same number at any index? ### Question:

i have an array in as3 which has elements like MyArray2 = 25;
MyArray2 = 31;
MyArray2 = 45;
MyArray2 = 50;
MyArray2 = 81; MyArray2 = 90;
MyArray2 = 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??

### Solution:1

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.

### Solution:2

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.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »