随机化或随机播放数组

时间:2011-01-20 01:52:00

标签: arrays actionscript

说我有一个数组:

myList:Array = new Array();
myList = [1,2,3,4,5,6,7,8,9];

myRandomList:Array = new Array();

for (var i:uint = 0; i < myList; i++) {
            var item:Number = Math.floor(Math.random() * myList.length-1) + 1;
            myRandomList.push(item);
      }

唯一的问题是,我希望myRandomList没有任何重复的数字...有没有办法从第一个列表中选择一个随机数,然后将其减去,这样我就不会选择那个数字两次?

更新

我刚刚看到这种方法从shadetyler.blogspot.com/2008/12/array-shuffle-as3.html洗牌一个数组

Array.prototype.shuffle = function(){
for(var i = 0; i < this.length; i++){
var a = this[i];
var b = Math.floor(Math.random() * this.length);
this[i] = this[b];
this[b] = a;
}

但是,有没有办法将其重写为函数?     }

2 个答案:

答案 0 :(得分:3)

标题说洗了一个数组,所以如果你正在寻找一个理想的洗牌,你可能需要一个没有偏见的Fisher–Yates算法。

因此,如果您想使用/保留原文,则需要初始化myRandomList

var myRandomList: Array = new Array( myList.length );

然后创建一个范围为a的随机数 然后将myRandomList[a]myRandomList[i]交换,其中i是当前元素。

// Random number
var a = Math.floor(Math.random() * myList.length);
// A swap
myRandomList[i] = myRandomList[a];
// put whatever is in index a in the ith position
myRandomList[a] = myList[i];
// restore whatever was in the ith position to index a

答案 1 :(得分:1)

我还没有完成很多动作,但是如果有可调整大小的数组类,你可以随机传输数据......例如:

数组来自 数组到

for for over over with iterator j。预先生成此数字,因为它会改变   i =从中获取随机索引   [j]时从= [I]   从[i]中删除

如果没有大小可变数组类,您可以随时进行随机交换

array theArray

rand =一个随机数 兰特     idx1,idx2 - &gt;设置为随机数     temp = theArray [idx1]     theArray [idx1] = theArray [idx2]     theArray [idx2] = temp

这样的事情 这只是psudo代码。

相关问题