开发者

Can i random an array with no reptition of same number at any index?

i have an arr开发者_C百科ay 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??


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜