随机化或洗牌数组 [英] Randomize or shuffle an array

查看:40
本文介绍了随机化或洗牌数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组:

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 没有任何重复的数字...有没有办法从第一个列表中选择一个随机数然后减去它,这样我就不会选择该数字两次?

The only thing is, I'd like myRandomList to not have any duplicate numbers...is there a way to select a random number from the first list and then SUBTRACT it so I don't select that number twice?

更新:

我刚刚从 shadetyler.blogspot.com/2008/12/array-shuffle-as3.html 看到了这种对数组进行改组的方法

I just saw this method of shuffling an array from 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;
}

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

However, is there a way to rewrite this as a function? }

推荐答案

标题说 shuffle an array 所以如果你正在寻找一个理想的 shuffle 你可能想要 Fisher-Yates 无偏算法.

The title says shuffle an array so if you are looking for an ideal shuffle you may want the Fisher–Yates algorithm that is unbiased.

所以如果你想使用/保留你的原件,你可以初始化 myRandomList

So if you wanted to use/keep your original, you would initialize myRandomList

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

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

Then create a random number with the range say a and then swap myRandomList[a] with myRandomList[i] where i is the current element.

// 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

这篇关于随机化或洗牌数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆