【问题标题】:How to generate 4 different random numbers in C++如何在 C++ 中生成 4 个不同的随机数
【发布时间】:2019-06-01 20:03:36
【问题描述】:

我正在 Bjarne Stroustrup 的“Programming Principles and Practice Using C++”一书(第 130 页,练习 13)中进行 Bulls and Cows 作业,我希望程序生成 0 到 9 范围内的四个不同整数(例如 1234 但不是 1122)

我创建了一个向量来存储数字和一个生成 4 个数字并将它们添加到向量中的函数,但是数字可能相同,我无法将数字返回给主函数

#include "../..//..//std_lib_facilities.h"

vector<int> gen4Nums(vector<int> secNum)
{
    random_device rd; // obtain a random number from hardware
    mt19937 eng(rd()); // seed the generator
    uniform_int_distribution<> distr(0, 9); // define the range 

    secNum.clear();
    for (int i = 0; i < 4; i++)
    {
        secNum.push_back(distr(eng));
        cout << secNum[i];
    }
    return secNum;
}

int main()
{
        vector<int> secNum;
        gen4Nums(secNum);   
}

我希望向主函数返回 4 个不同的随机数

【问题讨论】:

  • 你的函数签名没有多大意义,应该是vector&lt;int&gt; gen4Nums()或者void gen4Nums(vector&lt;int&gt;&amp; secNum)
  • 对于您的用例,std::set&lt;int&gt; 似乎是更合适的容器。无论如何,如果您发现它已经是结果的一部分,则必须重复确定随机值。
  • 我的意思是,如果你想生成随机数,有this question。不确定它是否重复,只是因为听起来您在寻求调试帮助,但这仍然可能会有所帮助。

标签: c++ random numbers


【解决方案1】:

如果您像这样更改代码,您可以确保在结果中获得不同的随机数:

#include <vector>
#include <random>
#include <algorithm>

using namespace std;

vector<int> gen4Nums()
{
    vector<int> result;
    random_device rd; // obtain a random number from hardware
    mt19937 eng(rd()); // seed the generator
    uniform_int_distribution<> distr(0, 9); // define the range 

    int i = 0;
    while(i < 4) { // loop until you have collected the sufficient number of results
        int randVal = distr(eng);
        if(std::find(std::begin(result),std::end(result),randVal) == std::end(result)) {
        // ^^^^^^^^^^^^ The above part is essential, only add random numbers to the result 
        // which aren't yet contained.
            result.push_back(randVal);
            cout << result[i];
            ++i;
        }
    }
    return result;
}

int main() {
    vector<int> secNum = gen4Nums();   
}

【讨论】:

    【解决方案2】:

    似乎您正在尝试生成 0...9 范围内的 4 个唯一随机整数。

    您可以通过生成包含值 0...9 的整数向量来实现此目的。然后打乱向量,因为您希望它是整数的随机选择。最后将向量修剪到所需的大小,因为您只需要 4 个唯一的随机整数:

    #include <vector>
    #include <random>
    #include <algorithm>
    #include <numeric>
    
    void gen4Nums(std::vector<int>& v) {
        //Generate initial vector with values 0...9:
        v.resize(10, 0);
        std::iota(v.begin(), v.end(), 0);
    
        //Shuffle the vector:
        std::random_device rd;
        std::mt19937 g(rd());
        std::shuffle(v.begin(), v.end(), g);
    
        //Trim the vector to contain only 4 integers:
        v.resize(4);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-11
      • 2011-06-23
      • 2014-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多