c - 如何使用 rand() 函数生成以前未生成过的不同数字?

标签 c random

//我的意思可以通过我的例子来说明:

#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/

相关文章:

c - 为什么我在使用 rb_funcall 调用 Hash#has_key 时会出现段错误?

无法摆脱夹板警告 "Field used before definition", "rvalue is used that may not be initialized to a value on some execution"

c - 在 C 中查看和使用 void 指针中的各个字节

java - % Chance,这段代码高效且正确吗?

c++ - 选择没有重复的随机坐标?

python - 类型错误 : randint() takes exactly 3 arguments (4 given)

C++ uniform_int_distribution 总是在第一次调用时返回 min()

c - 从 C 中的同一个文件中读取 int 和 char

对使用 ftell() 检查文件是否为空感到困惑

mysql程序 - 从五个数字中随机数