2015-12-30 84 views
0

我想生成一个遵循均匀分布而不重复的随机整数。例如,我将通过此代码生成6个统一编号如何在C++中生成一致的随机整数而不重复

vector<int> container; 
container.reserve(lossNum); 
std::vector<unsigned int>::iterator it; 
// Our Random Generator 
std::mt19937 eng{ std::random_device{}() }; 
int max_num=6 
for (int i = 0; i<max_num; i++) { 
    unsigned int q = std::uniform_int_distribution<unsigned int>{ 0, max_num }(eng); 

    do { 
     q = std::uniform_int_distribution<unsigned int>{ 0, max_num }(eng); 
     it = std::find(container.begin(), container.end(), q); 
    } while (it != container.end()); 

    container.push_back(q); 
} 

而且我在120.000以上的代码上面运行并画出图。但是这个数字并没有显示出统一的分布。我的代码中有什么问题?我正在使用visual studio 2015来运行它。

另外,如果我在linux(Ubuntu)环境下运行。我如何修改标准C++的上述代码?由于

enter image description here

这是我的代码

+0

既然你没有这个词在你的文字 “随机”,'container.push_back(I);'会做的伎俩。 –

+0

对不起,它必须是随机的 – Jame

+0

@ user8430我不知道这可以提供什么帮助,但是你需要连续两次请求一个随机数 - 在循环前和循环中。尝试声明'unsigned int q;'而不将它初始化为一个随机数。 – LogicStuff

回答

4
  1. 代码示例

看你的代码,它看起来像你重新发明轮子。 2015年MSVC应该支持std::shuffle这样你就可以做同样的:

int max_num = 6; 
// Create vector 
std::vector<int> container(max_num); 
// Fill it with numbers 0, 1, ..., max_num - 1) 
std::iota(container.begin(), container.end(), 0) 
// Create random engine generator 
std::mt19937 eng{ std::random_device{}() }; 
// shuffle it!! 
std::shuffle(container.begin(), container.end(), eng); 

所有讨厌的东西是你做,而不是!

  • 随机性
  • 你真的要在生成6号[0,6]? 为什么不是7号码全部都有?

    我120 000重复测试代码我的电脑上与我有: 0缺少17335倍 1缺少16947倍 2缺少17054倍 3缺少17116倍 4缺少17330倍 5失踪17114次 6失踪17105次

    看起来这里统一,但我使用g ++。也许这是msvc std库的问题,但我不能给你更多的信息,因为我不使用它。

    +0

    你可以把上面的代码展示给g ++。我想在Ubuntu中构建它 – Jame

    +0

    我认为所有代码已经存在。如果你想使用'std :: shuffle',上面的代码应该可以完成这项工作。否则,我用do ... while循环测试了你的代码。 –

    +0

    我认为你的代码与我的问题看起来不一样。我只想生成x数(x可能是3或2 ....)但小于6.所以容器必须由x调整。你可以编辑你的代码作为我的要求 – Jame

    1

    从未做到这一点:

    do { 
        q = std::uniform_int_distribution<unsigned int>{ 0, max_num }(eng); 
        it = std::find(container.begin(), container.end(), q); 
    } while (it != container.end()); 
    

    您选择一个元素,然后如果你已经选择了它先前拒绝。从计算角度来看,这是一个禁忌。

    你想要什么叫做Knuth shuffle(又名Fisher-Yates shuffle)。 这样的算法允许您随机选取一个矢量的元素(这里是一个包含6个数字[0; 6 [)的矢量,无需替换。 “Fisher-Yates洗牌类似于从没有替换的帽子中随机挑选编号的门票(combinatorics:可区别的对象),直到没有剩下任何东西。”在Knuth Shuffle wikipedia article

    代码suffle:

    #include <stdlib.h> 
    
    /* Arrange the N elements of ARRAY in random order. 
    Only effective if N is much smaller than RAND_MAX; 
    if this may not be the case, use a better random 
    number generator. */ 
    void shuffle(int *array, size_t n) 
    { 
        if (n > 1) { 
         size_t i; 
         for (i = 0; i < n - 1; i++) { 
          size_t j = i + rand()/(RAND_MAX/(n - i) + 1); 
          int t = array[j]; 
          array[j] = array[i]; 
          array[i] = t; 
         } 
        } 
    } 
    
    +0

    是的。但我会在Ubuntu上工作。所以Visual studio 2015中的一些API函数不能使用,比如std :: shuffle – Jame

    +0

    是的,它可以跨平台(windows和Ubuntu)工作。我刚刚将代码添加到前一个响应中。 –

    相关问题