【问题标题】:array of non repeating numbers in C?C中的非重复数字数组?
【发布时间】:2014-03-19 18:05:57
【问题描述】:

到目前为止,我有一个包含 1-49 的六个随机数的数组,但有些重复,例如 12 15 43 43 22 15 有没有办法解决这个问题?

目前为止……

int* get_numbers()
{
        int Array[6], i;
        printf("\n\n Your numbers are : ");
        for (i = 0; i < 6; i++)
        {
               Array[i] = ((rand() % 49) + 1);
               printf("%d ",Array[i]);
        }
}

任何反馈都会很棒,谢谢

【问题讨论】:

  • 您要解决的问题是什么?你需要 6 个唯一的数字吗?

标签: c arrays random unique


【解决方案1】:

您可以简单地丢弃重复项。

另一种选择是创建一个由 1-49 组成的数组,shuffle them,并取前 6 个。

【讨论】:

    【解决方案2】:

    您需要添加一个单独的循环,该循环从 0(含)到 i(不含),将候选编号与之前添加到数组中的编号进行对比。如果检查发现重复,请不要增加i,并尝试再次生成随机数:

    int i = 0;
    while (i != 6) {
       int candidate = ((rand() % 49) + 1);
       int ok = 1; // ok will become 0 if a duplicate is found
       for (int j = 0 ; ok && j != i ; j++) {
           ok &= (candidate != Array[j]);
       }
       if (ok) {
           Array[i++] = candidate;
           printf("%d ", candidate);
       }
    }
    

    Demo on ideone.

    【讨论】:

      【解决方案3】:

      rand 函数不知道其先前的输出,因此您可以在将其保存到数组之前进行检查

      【讨论】:

        【解决方案4】:

        如果你得到第一个随机数为x,则找到第二个随机数为random(1 to x-1)random(x+1 to n) 的随机数。以这种方式继续。

        【讨论】:

          猜你喜欢
          • 2014-11-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-08
          • 2013-12-24
          • 2016-02-24
          • 2013-12-07
          • 1970-01-01
          相关资源
          最近更新 更多