【问题标题】:C Generate random numbers without repetition [duplicate]C生成不重复的随机数[重复]
【发布时间】:2014-04-19 22:50:14
【问题描述】:

我想生成 1 到 13 之间的随机数而不重复 这个方法我用过,但不能确定没有名气。

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

请帮助我。 C语言

【问题讨论】:

标签: c


【解决方案1】:

正如评论所说,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]);
}

这是示例输出。

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,

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

【讨论】:

    猜你喜欢
    • 2015-07-12
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    • 2016-05-05
    • 1970-01-01
    • 2012-01-23
    相关资源
    最近更新 更多