2017-08-01 396 views
-1

使用函数以相等的概率随机生成数字1到5,并以相同的概率创建一个函数,该函数以相等的概率生成数字1到7。使用给定的随机生成器函数从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 

请告诉我们,如果有什么不对的地方。

+0

这不建议使用宏来“模拟”功能('ran'),但如果你_must_这样做,学会正确保护扩展:'#定义ran(rand()%5)'否则如果在表达式中使用宏,可能会得到意想不到的结果。在这种情况下,按照使用它的方式,它可能并不重要,但对于以不同方式使用的其他宏,它将会如此。 – TripeHound

+0

您将1-5映射到1-7的方式并不理想:我没有研究过它是否预计分发是否统一,但主要问题是您“询问” 5000万的数字,只有3500万。 – TripeHound

+0

@TripeHound的问题是以相等的概率生成所有数字1到7。剩下的一千五百万是我忽略的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; 
} 
+1

这实际上是一个面试问题。我不认为这是预期的答案。这可能是正确的,但预计会更简单一些。如果您在执行过程中发现错误,我将不胜感激。 –

+0

@SurajTripathi你的解决方案肯定不是_best_,主要是因为所有的循环。另外,你还没有创建一个_function_,它产生一个从1到7的数字(这是我怀疑他们想要的)......并且你的for循环的“内部”并不真的这样做,因为有时它赢了根本不会生成(有效)号码。在_minimum_,你可以将'for'的内部包装在“有效性测试”循环中,并将其粘贴在一个函数中 - 理想情况下,您可以考虑使用多个1-5选项来生成更有效的方法范围为1-7 – TripeHound