Randomize or shuffle an array
说我有一个数组:
1 2 3 4 5 6 7 8 9 | 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中看到了一种将数组改组的方法
1 2 3 4 5 6 7 | 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; } |
但是,有没有办法将其重写为函数?
}
标题说的是对数组进行混洗,因此,如果您要寻找理想的混洗,则可能希望使用无偏Fisher-Yates算法。
因此,如果您想使用/保留原件,则可以初始化
1 | var myRandomList: Array = new Array( myList.length ); |
然后创建一个随机数,范围为a
然后将
1 2 3 4 5 6 7 | // 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 |
我没有做太多的动作脚本,但是如果有可调整大小的数组类,则可以随机传输数据...例如:
来自的数组
数组到
使用迭代器j进行for循环。预先生成此数字,因为它将更改
i =从中获取随机索引
到[j] =来自[i]
从[i]中删除
如果没有大小可变数组类,则可以随时进行随机交换
数组theArray
rand =一个随机数
兰特
idx1,idx2->设置为随机数
temp = theArray [idx1]
theArray [idx1] = theArray [idx2]
theArray [idx2] =临时
这样的东西
那只是伪代码。