使用给定的随机生成器函数生成从1到7的随机数

时间:2017-08-01 08:32:46

标签: math random probability

使用以相等概率随机生成数字1到5的函数,创建一个以相等概率生成数字1到7的函数。

我修改了之前的答案之一。这是对的吗?

#include <bits/stdc++.h>
#define ran rand()%5
using namespace std;
int main(){
    int a[2][5] = {{1, 2, 3, 4, 5}, {6, 7, 0, 0, 0}};
    int ct[8] = {0};
    for(int i = 0; i<50000000; i++){
        int j = ran;
        while(j>1){
            j = ran;
        }
        int k = ran;
        if(a[j][k]>0)
            ct[a[j][k]]++;
    }

    for(int i = 1; i<=7; i++){
        cout<<ct[i]<<endl;
    }
    return 0;
}

我有以下输出:

4997165
4998128
4997312
5002487
5000661
4998637
4999720

请告诉它是否有任何问题。

1 个答案:

答案 0 :(得分:0)

这是一个现代的C ++解决方案:

#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <ostream>
#include <random>

template <unsigned int Min, unsigned int Max>
class imbued_urng
{
public:
    using result_type = unsigned int;

    static constexpr result_type min() { return Min; }
    static constexpr result_type max() { return Max; }

    imbued_urng(const std::function<result_type()>& source) : random{ source } {}
    imbued_urng(const imbued_urng& rhs) = delete;
    imbued_urng& operator=(const imbued_urng& rhs) = delete;

    result_type operator()() { return random(); }

private:
    const std::function<result_type()>& random;
};

int main()
{
    // Create a random number engine
    std::mt19937::result_type seed = std::random_device{}();
    std::cout << "seed = " << seed << std::endl;
    auto engine = std::mt19937{ seed };

    // Create the rand5 distribution
    auto const dist5{ std::uniform_int_distribution<> {1, 5} };
    auto const rand5{ std::function<unsigned int()>{ [&engine, &dist5] { return dist5(engine); } } };

    auto const n = 32;
    std::generate_n(std::ostream_iterator<unsigned int>(std::cout, " "), n, rand5);
    std::cout << std::endl;

    // Create a uniform random number generator based on rand5
    imbued_urng<1, 5> urng { rand5 };

    // Create the rand7 distribution
    auto const dist7{ std::uniform_int_distribution<> {1, 7} };
    auto const rand7{ std::function<unsigned int()>{ [&urng, &dist7] { return dist7(urng); } } };

    std::generate_n(std::ostream_iterator<unsigned int>(std::cout, " "), n, rand7);
    std::cout << std::endl;

    return 0;
}