创建随机数 [英] Create random numbers
问题描述
这是我的第一个问题在这里,我正在做一个小游戏,并分配角色,我需要随机数。我有这个code,但可能是数字不重复?谢谢你。
无效giveroles(){
函数srand(时间(NULL));
INT R =兰特()%I + 1;
开关(R){/ * ... * /}
}
如果你想随机地分配小组数字,而不是随机生成它们,创造你想要的号码列表,然后随机化的顺序列表(遍历列表,随机交换条目)。
例如:
INT卡[52];
的for(int i = 0; I< 52;我++)
{
卡[我] =我;
}
的for(int i = 0; I< 1000;我++)
{
INT R1 =兰特()%52;
INT R2 =兰特()%52;
INT T =卡(R1);
卡[R1] =卡[R2];
卡[R2] = T;
}
的for(int i = 0; I< 52;我++)
{
的printf(%d个\\ N,卡[I]);
}
有关完整性,已经指出,在这种方式洗牌是偏置。下面是这应该是不偏不倚的变化:
卡[0] = 0;
的for(int i = 1; I< 52;我++)
{
INT R =兰特()%(I + 1);
卡[I] =卡[R]。
卡[R] =我;
}
(应当进一步指出,服用)兰特的模块(也可能有偏差,作为兰特(范围内)不会是偶数倍)
this is my first question here, i'm making a little game, and for assigning the roles, i need random numbers. I have this code, but is possible that the numbers don't be repeated? Thanks.
void giveroles() {
srand(time(NULL));
int r = rand() % i + 1;
switch ( r ) { /* ... */ }
}
If you want to randomly assign a small set of numbers, rather than generate them at random, create a list of the numbers you want, and then randomise the order of the list (iterate over the list, randomly swapping entries).
For example:
int cards[52];
for(int i = 0 ; i < 52 ; i++)
{
cards[i] = i;
}
for(int i = 0 ; i < 1000 ; i++)
{
int r1 = rand()%52;
int r2 = rand()%52;
int t = cards[r1];
cards[r1] = cards[r2];
cards[r2] = t;
}
for(int i = 0 ; i < 52 ; i++)
{
printf("%d\n", cards[i]);
}
For completeness, it has been pointed out that shuffling in this fashion is biased. Here's a variation which should be unbiased:
cards[0] = 0;
for(int i = 1 ; i < 52 ; i++)
{
int r = rand() % (i+1);
cards[i] = cards[r];
cards[r] = i;
}
(it should be further noted that taking the module of rand() is also likely to be biased, as the range of rand() will not be an even multiple)
这篇关于创建随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!