【问题标题】:Generating 9 random numbers without repeating [closed]生成9个随机数而不重复[关闭]
【发布时间】:2015-04-29 02:03:11
【问题描述】:

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

提前谢谢!

【问题讨论】:

  • 您是否已经尝试过?你究竟被困在哪里?
  • 好吧,我生成了随机数并将它们放入 for 循环中以获得 9 个数字
  • 欢迎来到stackoverflow。如果您确实证明您曾尝试自己解决问题,那么您获得帮助的机会就更大。这是关于如何提出问题的页面stackoverflow.com/help/how-to-ask
  • 你能把你有问题的代码显示出来吗?
  • @user3745910 你可能应该看看这个问答:stackoverflow.com/questions/4926622/…

标签: c++ random helpers


【解决方案1】:
#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 的简单回答,但它并不完全符合您的要求。

我发布的代码应该与您要查找的内容一致。

【讨论】:

    【解决方案2】:

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

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      • 2020-07-09
      • 2018-07-03
      • 2012-12-10
      • 1970-01-01
      相关资源
      最近更新 更多