生成9个不重复的随机数

Generating 9 random numbers without repeating

我有一个任务想要 ne 制作一个幻方程序,在其中生成随机数 1-9 并将它们分配给二维数组,我不知道如何生成不重复的随机数,我想知道是否有人可以帮助我它是 c++。

提前谢谢!

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

希望对您有所帮助!

#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 的简单回答,但它并不完全符合您的要求。

我发布的代码应该符合您的要求。