【问题标题】:Generating unequal random numbers in C在 C 中生成不相等的随机数
【发布时间】:2016-02-20 22:11:20
【问题描述】:

我编写了一个程序,它生成 4 个随机数字,它应该像这样出现在屏幕上:从 0000 到 9999(当然不一定是升序!)。

问题是我遇到了彼此相等的数字。我该如何解决?我只想生成 10.000 个数字,范围从 0000 到 9999,但不按任何顺序:只是“随机”。

这是我目前所写的:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#define SIZE 10000

int main(){

    srand(time(NULL));

    int a[SIZE], b[SIZE], c[SIZE], d[SIZE], i;
    FILE *fd = fopen("combinations_rand.txt", "w");
    assert(fd);

    for(i=0; i<SIZE; i++){      
        a[i] = rand()%10; //array of first digits
        b[i] = rand()%10; //array of second digits, etc...
        c[i] = rand()%10;
        d[i] = rand()%10;
        fprintf(fd, "%d%d%d%d\n", a[i], b[i], c[i], d[i]);
     }
     fclose(fd);
}

【问题讨论】:

  • 你有答案,你说不按任何顺序...只是重新排序。
  • 如果您不想重复,那么您就不需要随机数,您需要在数>随机顺序.
  • 当我运行程序时,我得到了两次数字 0844。而且我不认为只有这个数字出现了两次。假设我以这种方式生成数字:0000、0001、...、9999,而不是随机生成的。我怎样才能重新排列它们以显得随机? (对您的评论有疑问。)
  • @J... 这怎么可能?
  • @George 见下文 ;)

标签: c random numbers


【解决方案1】:

取一个长度为 10000 的数组并将 0 到 9999 的元素存储在其中。 然后洗牌数组Shuffle array in C

然后在需要时用前导零打印答案Printing leading 0's in C?

【讨论】:

  • 这是一个很好的答案。我已经准备好了,所以我还是发布了它。
【解决方案2】:

你应该做的是用从09999的数字生成一个数组,然后把它混合起来,像这样

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

#define SIZE 10000

int main()
{
    int numbers[SIZE];

    srand(time(NULL));
    /* Fill the array */
    for (int i = 0 ; i < SIZE ; ++i)
        numbers[i] = i;
    /* Mix it */
    for (int i = 0, j = rand() % SIZE ; i < SIZE ; ++i, j = rand() % SIZE)
    {
        int swap;
        swap = numbers[i];
        numbers[i] = numbers[j];
        numbers[j] = swap;
    }
    /* Display it */
    for (int i = 0 ; i < SIZE ; ++i)
        fprintf(stdout, "%04d\n", numbers[i]);
    return 0;
}

【讨论】:

  • 除非我认为这会引入偏见:请参阅 Fisher-Yates shuffle。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-15
  • 1970-01-01
相关资源
最近更新 更多