I have same problem as here Distributed probability random number generator but in c++. I know how to implement it but my question is - Is that functionaly build in current version of c++?
            Asked
            
        
        
            Active
            
        
            Viewed 2,447 times
        
    0
            
            
        - 
                    There ought to be something here for you: http://en.cppreference.com/w/cpp/numeric/random – jrok Feb 23 '13 at 10:54
- 
                    3http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution thats it! Why I haven't seen it for the first time? Ok, thanks. Your answer helped me. – Houp Feb 23 '13 at 10:58
- 
                    And unfortunatelly Visual Studio doesnt support constructor with iterators. ( dist(someVector.begin(), someVector.end() ) :( – Houp Feb 23 '13 at 11:19
- 
                    @user1483399 Does it support the constructor with an `initializer_list`? `dist({150, 40, 15, 3})`? – Joseph Mansfield Feb 23 '13 at 11:21
- 
                    No, it doesn't work. See http://msdn.microsoft.com/cs-cz/library/ee462326%28v=vs.100%29.aspx . Maybe piecewise_constant_distribution could be used instead discrete_distribution. – Houp Feb 23 '13 at 11:56
1 Answers
3
            
            
        For completeness, I'll answer the question.
This distribution can be produced using C++11's random number generation library. This first requires seeding a random number engine (here I use std::mt19937) and then using that engine with a std::discrete_distribution random number distribution.
std::discrete_dstribution's constructor takes either an iterator range over a sequence of weights or an initializer_list of weights. The generated numbers are then weighted according to the corresponding index in the sequence of weights. That is, if {10, 5, 1} are the weights, 0 will be produced with 10/(10 + 5 + 1) = 0.625 probability, and so on.
The following code demonstrates a solution to the other question:
std::random_device device;
std::mt19937 engine(device()); // Seed the random number engine
std::discrete_distribution<> dist({150, 40, 15, 3}); // Create the distribution
// Now generate values with:
std::cout << (dist(engine) + 1) << std::endl;
 
    
    
        Joseph Mansfield
        
- 108,238
- 20
- 242
- 324
 
    