JavaScript的随机排列无起始位置有元素 [英] Javascript randomize array without having element in starting position

查看:137
本文介绍了JavaScript的随机排列无起始位置有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript的问题。我有一个用户输入姓名,然后我放入一个数组列表。长话短说,我编程以随机的方式为人们找出谁,他们会买圣诞礼物了。例如,原来的阵列由下列名称:

I have a javascript problem. I have a user enter a list of names, which I then place into an array. Long story short, I am programming a random way for people to figure out who they will buy Christmas gifts for. For instance, the original array consists of the following names:

Alex
Joel
Lindsay
Cori

我要那么随机的名字,让我得到一个随机列表,类似以下内容:

I want to then randomize the names so that I get a random list, similar to the following:

Lindsay
Cori
Joel
Alex

我随后将来自第一阵列显示的名称,并与在相同的位置的随机名称对齐。例如,在这个例子中,亚历克斯与林赛相关联的Joel与科里相关联,林赛与乔尔相关联,并且柯里与亚历相关联。我目前使用下面的方法随机化:

I would then display the names from the first array and align them with the randomized name in the same location. For instance, in this example, Alex is associated with Lindsay, Joel is associated with Cori, Lindsay is associated with Joel, and Cori is associated with Alex. I am currently using the following randomize method:

function shuffle(array){
    var m = array.length, t, i;
    while(m){
        i = Math.floor(Math.random() * m--);
        t = array[m];
        array[m] = array[i];
        array[i] = t;
    }
    return array;
};

具有这种功能的问题是,该阵列不随机到一个新的位置。例如,用这种方法,我可以有以下初始阵列

The problem with this function is that the array does not randomize into a new location. For instance, with this method, I can have the following initial array:

Alex
Joel
Lindsay
Cori

和我的数组,与上面的函数随机化的话,会导致这样的事情:

And my array, with the above function to randomize it, will result in something like this:

Cori
Alex
Lindsay
Joel

这意味着,亚历克斯与柯里相关,乔尔与亚历克斯相关,林赛与林赛相关,柯里是assocated乔尔。这就是问题所在。如果这是一个程序,看看谁买对他们来说,圣诞礼物,林赛可以不买礼物送给林赛。

This means that Alex is associated with Cori, Joel is associated with Alex, Lindsay is associated with Lindsay, and Cori is assocated with Joel. This is where the problem lies. If this is a program to see who buys a Christmas gift for whom, Lindsay can NOT buy a gift for Lindsay.

什么是一个合适的阵列随机函数来解决这个问题?

What would be an appropriate array randomizing function to fix this issue?

感谢您的帮助!

推荐答案

尝试 - 米,而不是米 -

function shuffle(array){
    var m = array.length, t, i;
    while(m){
        i = Math.floor(Math.random() * --m);
        t = array[m];
        array[m] = array[i];
        array[i] = t;
    }
    return array;
};

由于如果你使用米 - 你所能获得我==米和交换阵列本身的元素

Because if you use m-- you can possibly get i == m and swap array element with itself.

这篇关于JavaScript的随机排列无起始位置有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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