C语言 C 生成不重复的随机数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23176467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:01:45  来源:igfitidea点击:

C Generate random numbers without repetition

c

提问by user3552818

I want to generate random numbers between 1 and 13 without repetition I used this method, but it doesn't make sure there is no reputation.

我想在不重复的情况下生成 1 到 13 之间的随机数我使用了这种方法,但它并不能确保没有声誉。

for ( i = 0; i < 13; i++)
{
      array[i] = 1 + (rand() % 13);
}

Please help me. C language

请帮我。C语言

回答by Brian Tracy

As a comment said, Fill an array with numbers 1 through 13 then shuffle the array.

正如评论所说, Fill an array with numbers 1 through 13 then shuffle the array.

int array[13];

for (int i = 0; i < 13; i++) {     // fill array
    array[i] = i;
    printf("%d,", array[i]);
}
printf("\n done with population \n");
printf("here is the final array\n");

for (int i = 0; i < 13; i++) {    // shuffle array
    int temp = array[i];
    int randomIndex = rand() % 13;

    array[i]           = array[randomIndex];
    array[randomIndex] = temp;
}


for (int i = 0; i < 13; i++) {    // print array
    printf("%d,",array[i]);
}

Here is the sample output.

这是示例输出。

0,1,2,3,4,5,6,7,8,9,10,11,12,
 done with population 
here is the final array
11,4,5,6,10,8,7,1,0,9,2,12,3,

Note: I used the most basic sort I could. Use a better one if you want.

注意:我尽可能使用了最基本的排序。如果需要,请使用更好的。