【问题标题】:Generating random 1's and 0's生成随机 1 和 0
【发布时间】:2013-09-12 03:00:50
【问题描述】:

下面的代码会随机产生相等数量的 1 和 0,这是它应该做的。

但是,我想知道如何获得 1 的年龄百分比,而其余的是 0。我需要在代码中进行哪些更改。敬请期待您的热情回复!

int random_gen::uniformI(int low, int high)
{
    int i;

    if (low >= high)
        i = low;
    else {
        i = (int) (randomperc() * (high - low + 1)) + low;
        if(i > high) 
            i = high;
    }
    return(i);
}

//main
for (int l=0; l<NUM_NODES;l++) { 
    wkey = nodes[i].WitnessKey;
}
cout<<wkey

;

【问题讨论】:

  • 之前在 SO 上多次提出类似问题。请尝试搜索...

标签: visual-c++ random generator


【解决方案1】:

在使用给定百分比 1 初始化的数组上使用 Knuth Shuffle。以下实现了 25%:

#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include <iterator>

void shuffle(double percentage,std::vector<int> &l) {
    if (l.empty()) return;

    std::mt19937 gen;
    unsigned int N_Ones = static_cast<unsigned int>(floor(percentage*l.size()));

    l[0] = (N_Ones > 0)?1:0;
    for(unsigned int i = 1; i < l.size() - 1; ++i) {
        std::uniform_int_distribution<unsigned int> ui(0,i);
        unsigned int j = ui(gen);
        l[i] = l[j];
        l[j] = (N_Ones > 0)?1:0;
    }
}

int main(int argc, char* argv[])
{
    unsigned int N = 10;
    if (argc >= 1) N = atoi(argv[1]);
    std::vector<int> l(N,0);
    shuffle(0.25,l);
    std::copy(l.begin(),l.end(),std::ostream_iterator<int>(std::cout,""));
    std::cout << std::endl;
    return 0;
}    

请注意,shuffle() 使用数组的隐式定义,其中第一个 N_Ones 条目为 1,其余为 0。对于加密应用程序,您可能希望使用比标准 Mersenne Twister @ 更好的随机源987654325@.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 2017-05-28
    • 2012-11-21
    • 1970-01-01
    • 2011-06-11
    • 2020-02-12
    相关资源
    最近更新 更多