1 // weighted_die.cpp
2 //
3 // Copyright (c) 2009
4 // Steven Watanabe
5 //
6 // Distributed under the Boost Software License, Version 1.0. (See
7 // accompanying file LICENSE_1_0.txt or copy at
8 // http://www.boost.org/LICENSE_1_0.txt)
9
10 //[weighted_die
11 /*`
12 For the source of this example see
13 [@boost://libs/random/example/weighted_die.cpp weighted_die.cpp].
14 */
15 #include <boost/random/mersenne_twister.hpp>
16 #include <boost/random/discrete_distribution.hpp>
17
18 boost::mt19937 gen;
19
20 /*`
21 This time, instead of a fair die, the probability of
22 rolling a 1 is 50% (!). The other five faces are all
23 equally likely.
24
25 __discrete_distribution works nicely here by allowing
26 us to assign weights to each of the possible outcomes.
27
28 [tip If your compiler supports `std::initializer_list`,
29 you can initialize __discrete_distribution directly with
30 the weights.]
31 */
32 double probabilities[] = {
33 0.5, 0.1, 0.1, 0.1, 0.1, 0.1
34 };
35 boost::random::discrete_distribution<> dist(probabilities);
36
37 /*`
38 Now define a function that simulates rolling this die.
39 */
roll_weighted_die()40 int roll_weighted_die() {
41 /*<< Add 1 to make sure that the result is in the range [1,6]
42 instead of [0,5].
43 >>*/
44 return dist(gen) + 1;
45 }
46
47 //]
48
49 #include <iostream>
50
main()51 int main() {
52 for(int i = 0; i < 10; ++i) {
53 std::cout << roll_weighted_die() << std::endl;
54 }
55 }
56