【问题标题】:Fill an array with 4 unique random numbers in C用C中的4个唯一随机数填充数组
【发布时间】:2020-04-05 15:22:17
【问题描述】:

对于一个学校项目,我需要做 MasterMind,并且所有 4 个密码的数字都必须不同。

如何创建一个包含 4 个唯一随机数的数组?

到目前为止,这是我的代码:

srand(time(NULL));

for (j = 0; j <= 4; j++) { rand(); } 

for (i = 0; i < 4; i++) { vetor[i] = (1 + rand() % 8); }

【问题讨论】:

  • 有哪些可用颜色(数字范围)?也许,您可以提供您的颜色的enum 的定义?此外,Mastermind 不要求代码的各个颜色不同。向我们展示您到目前为止所做的尝试。
  • 我不需要颜色,只需要从 1 到 8 的 4 个数字,问题是我不能有两个相等的数字,比如 1 1 2 3,它们需要不同。这是我现在拥有的代码:srand(time(NULL)); for (j = 0; j &lt;= 4; j++) { rand(); } for (i = 0; i &lt; 4; i++) { vetor[i] = (1 + rand() % 8); }
  • 我明白了,你的 j-loop 是为了什么而运行的?无论如何,我会添加一个答案。我会将此作为参考:vetor[i] = (1 + rand() % 8) 来自您的评论。

标签: c arrays random


【解决方案1】:

代码中的问题:

  1. j-loop 运行无效

  2. 您没有检查重复项

解决方案:

这是一个工作代码,在代码 cmets 中有解释:

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

int main()
{
    // Going to be filled with 4 unique random numbers
    int arr[4];

    // Set the seed
    srand(time(NULL));

    // Get 4 random numbers
    for (int i = 0; i < 4; i++)
    {
        // Fill arr[i] with a random number from your specified range
        arr[i] = 1 + rand() % 8;

        // Try again if it is a duplicate
        for (int j = 0; j < i; ++j)
        {
            if (arr[i] == arr[j])
            {
                --i;
                break;
            }
        }
    }

    // Print the array and see the results
    for (int i = 0; i < 4; ++i) printf(" %d", arr[i]);
    return 0;
}

【讨论】:

    【解决方案2】:

    使用 rand() 函数它给出随机值 前任- A[i] =rand()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-23
      • 2012-08-21
      • 2017-06-04
      • 2018-02-14
      相关资源
      最近更新 更多