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

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

问题描述

说我有一个数组:

  myList上:阵列=新的Array();
myList上= [1,2,3,4,5,6,7,8,9]

myRandomList:阵列=新的Array();

对于(VAR我:UINT = 0; I< myList中,我++){
            VAR项目:数= Math.floor(的Math.random()* myList.length-1)+ 1;
            myRandomList.push(项目);
      }
 

唯一的一点是,我想myRandomList到没有任何重复的数字......是有办法从第一个列表中选择一个随机数,然后减去它,所以我不选择这个数字两倍的<? / P>

更新:

我刚刚看到的洗牌从shadetyler.blogspot.com/2008/12/array-shuffle-as3.html

数组的这种方法

  Array.prototype.shuffle =功能(){
对于(VAR I = 0; I&LT; this.length;我++){
VAR一个=这[一]
变种B = Math.floor(的Math.random()* this.length);
这个[我] =此[B]。
该[B] = A;
}
 

然而,有没有办法重写这是一个功能呢?     }

解决方案

的标题说,洗牌数组,所以如果你正在寻找一个理想的洗牌,您可能希望的费雪耶茨算法是公正的。

所以,如果你想用/保留原来的,你会初始化 myRandomList

  VAR myRandomList:阵列=新阵列(myList.length);
 

然后创建一个随机数的范围内说 然后交换 myRandomList [A] myRandomList [I] 其中i是当前元素。

  //随机数
VAR一个= Math.floor(的Math.random()* myList.length);
// A掉
myRandomList [I] = myRandomList并[a];
//放无论是在指数中的第i个位置
myRandomList并[a] = myList中[I];
//恢复无论是在第i个位置索引
 

Say I have an array:

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);
      }

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?

UPDATE:

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? }

解决方案

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.

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

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

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天全站免登陆