如何有效地从1到50中选择几个唯一的随机数(不包括x)? [英] How can I efficiently select several unique random numbers from 1 to 50, excluding x?
问题描述
我有2个数字,介于0和49之间.我们称它们为x
和y
.现在,我想获得几个其他的数字,它们不是x或y,但也都在0
和49
之间(我使用的是Objective C,但这更多是我认为的一般理论问题?).>
我想到的方法是:
int a;
int b;
int c;
do {
a = arc4random() % 49;
} while ((a == x) || (a == y));
do {
b = arc4random() % 49;
} while ((b == x) || (b == y) || (b == a));
do {
c = arc4random() % 49;
} while ((c == x) || (c == y) || (c == a) || (c == b));
但这对我来说似乎有点不好,我不知道,我只是想学习成为一个更好的程序员,对于最佳实践而言,最优雅的方法是什么?
您可以使用 Fisher-Yates洗牌.这是一种有效的算法,可以从某个集合中生成一个随机排序的值列表.您首先要从要获取随机值的值列表中排除N,然后执行随机播放.
I have 2 numbers which are between 0 and 49. Let's call them x
and y
. Now I want to get a couple of other numbers which are not x or y, but are also between 0
and 49
(I am using Objective C but this is more of a general theory question I think?).
Method I thought of is:
int a;
int b;
int c;
do {
a = arc4random() % 49;
} while ((a == x) || (a == y));
do {
b = arc4random() % 49;
} while ((b == x) || (b == y) || (b == a));
do {
c = arc4random() % 49;
} while ((c == x) || (c == y) || (c == a) || (c == b));
But it seem kind of bad to me, I don't know, I am just trying to learn to be a better programmer, what would be the most elegant way to do this for best practices?
You can use something called the Fisher-Yates shuffle. It's an efficient algorithm for producing a randomly ordered list of values from some set. You would first exclude N from the list of values from which to get random values, and then perform the shuffle.
这篇关于如何有效地从1到50中选择几个唯一的随机数(不包括x)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!