生成 9 个随机数而不重复

Generating 9 random numbers without repeating

本文关键字:随机数 生成      更新时间:2023-10-16

我有一个作业,希望 ne 制作一个魔方程序,您可以在其中生成随机数 1-9 并将它们分配给 2D 数组,我不知道如何生成不重复的随机数,我想知道是否有人可以帮助我它是 c++。

提前谢谢!

#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
// Returns true if the item is in the list, otherwise false
bool checkInList(std::vector<int> &list, int value)
{
    for (int i = 0; i < list.size(); ++i)
    {
        if (list.at(i) == value)
        {
            return true;
        }
    }
    return false;
}
// min inclusive, max exclusive
// make sure to set a new seed before using to help make results more random. (std::srand)
int randomInt(int min, int max) 
{
    return rand() % (max - min) + min;
}
int main() 
{
    std::vector<int> list;
    std::srand(std::time(0));
    while (list.size() < 9)
    {
        int num = randomInt(1, 10); 
        if (!checkInList(list, num))
        {
            list.push_back(num);
        }
    }
    for (int i = 0; i < list.size(); ++i)
    {
        std::cout << list.at(i) << std::endl;
    }
    return 0;
}

我喜欢 sabreitweiser的简单答案,但它并没有完全满足您的要求。

我发布的代码应该与您正在寻找的代码一致。

看看算法标头中的 std::random_shuffle。它应该适用于几乎所有的 stl 容器,假设这已经足够了。例如,您可以在整数为 1 到 9 的向量上使用它,然后将其转换回数组。这不是最有效的方法,但它可以节省大部分编码工作。

希望这有帮助!