//我的意思可以通过我的例子来说明:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int i;
int a;
for (a = 0;a <10;a ++) {
i = (rand()%10)+1; // generates a number from 1-10
printf("%d\n", i);
}
//我希望循环生成一个数字,该数字给出之前未生成的数字。例如,输出如下:
1,3,6,2,8,9,4,10,5,7
而不是:
3,9,10,3,7,9,2,7,10,1
换句话说,我不想要任何副本。
最佳答案
您显然不只是想要没有副本,而是希望给定集合中的每个数字都只出现一次。正如罗伯特所评论的,这类似于洗一副牌。 C 中没有“甲板”,但您可以将其建模为数组:
int deck[] = {1,1,1,1,1,1,1,1,1,1};
这应该代表 10 张不同的“卡”(通过它们在数组中的索引来标识),每张都可用一次。现在,只需编写“抽”牌的代码即可:
int i = 0; // starting point for searching for the next card to draw
for (int n = 10; n > 0; --n) // how many cards are left
{
int skip = rand() % n; // randomly skip 0 .. n cards
while (1)
{
if (deck[i]) // card still available?
{
if (!skip) break; // none more to skip -> done
--skip; // else one less to skip
}
if (++i > 9) i = 0; // advance index, wrapping around to 0
}
deck[i] = 0; // draw the card
printf("%d\n", i+1); // and print it out
}
当然,首先要播种 PRNG(例如 srand(time(0))
),这样您就不会每次都得到相同的序列。
关于c - 如何使用 rand() 函数生成以前未生成过的不同数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51457357/