创建一些随机数而不重复 [英] Create some random numbers without repeat

查看:103
本文介绍了创建一些随机数而不重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好我想制作一些随机的数字。我的数字是 0 1 2 3

我想要返回只是一个数字这是非常重要的。

如果你可以帮我拆分(我的随机播放功能)或其他方式解决我的问题,例如只需打印 1 2 谢谢:)



我有什么尝试过:



在我提出这个问题之前,我测试了这个功能但是返回了多个。

Hi guys I want create some numbers that are random. My numbers are 0,1,2 and 3.
I want return just one number and this is very important.
If you can help me split it (my shuffle function) or other way solve my problem for example just print 1 or 2 Thank You :)

What I have tried:

Before I ask this question I test this function but return more than one.

function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
}

推荐答案

非重复和随机数字并非无足轻重:非常随机性的本质使得重复不仅允许,而且与非重复一样可能。随着生成的值的增加,随机重复的可能性也会增加



有两种方法可以实现:

1)非确定性的。生成你的随机值,看看它是否已经在你已经完成的数字集合中,如果是这样的话就扔掉它并获得另一个。

2)确定性。在开始生成序列之前,先收集所有可能的随机数。对于序列中的每个数字,生成一个介于0和序列中剩余值的数量之间的随机数。使用它作为索引来获取随机值。从序列中删除随机数并将长度减少一个。



1)编码简单,但生成数字可能需要很长时间,特别是生成的随机数超过了值范围的一半(即,您已经生成了100个数中的50个),因为重复的可能性超过1:2并继续上升。

2)更多编码很复杂,但总是花费相同的时间来生成一个值。
"Non-repeating" and "random" numbers are not trivial: the very nature of randomness makes repetition not only allowed but just as likely as non-repetition. And as the number of values generated increases, the chances of a random repetition goes way up

There are two ways to do it:
1) Non-deterministic. Generate your random value, see if it's in the set of numbers you have already done, throw it away if it is and get another.
2) Deterministic. Make a collection of all possible random numbers before starting to generate a sequence. For each number in the sequence, generate a random number which is between 0 and the number of values left in the sequence. Use that as an index to get the random value. Remove the random number from the sequence and reduce the length by one.

1) Simple to code, but can take an extremely long time to generate numbers, particularly once the number of random numbers generated exceeds half the value range (ie, you have generated 50 out of 100 numbers) as the chances of a repetition get above 1:2 and continue to rise).
2) More complicated to code, but always takes the same time to generate a value.


这篇关于创建一些随机数而不重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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