• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // 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 //[die
11 /*`
12     For the source of this example see
13     [@boost://libs/random/example/die.cpp die.cpp].
14     First we include the headers we need for __mt19937
15     and __uniform_int_distribution.
16 */
17 #include <boost/random/mersenne_twister.hpp>
18 #include <boost/random/uniform_int_distribution.hpp>
19 
20 /*`
21   We use __mt19937 with the default seed as a source of
22   randomness.  The numbers produced will be the same
23   every time the program is run.  One common method to
24   change this is to seed with the current time (`std::time(0)`
25   defined in ctime).
26 */
27 boost::random::mt19937 gen;
28 /*`
29   [note We are using a /global/ generator object here.  This
30   is important because we don't want to create a new [prng
31   pseudo-random number generator] at every call]
32 */
33 /*`
34   Now we can define a function that simulates an ordinary
35   six-sided die.
36 */
roll_die()37 int roll_die() {
38     /*<< __mt19937 produces integers in the range [0, 2[sup 32]-1].
39         However, we want numbers in the range [1, 6].  The distribution
40         __uniform_int_distribution performs this transformation.
41         [warning Contrary to common C++ usage __uniform_int_distribution
42         does not take a /half-open range/.  Instead it takes a /closed range/.
43         Given the parameters 1 and 6, __uniform_int_distribution
44         can produce any of the values 1, 2, 3, 4, 5, or 6.]
45     >>*/
46     boost::random::uniform_int_distribution<> dist(1, 6);
47     /*<< A distribution is a function object.  We generate a random
48         number by calling `dist` with the generator.
49     >>*/
50     return dist(gen);
51 }
52 //]
53 
54 #include <iostream>
55 
main()56 int main() {
57     for(int i = 0; i < 10; ++i) {
58         std::cout << roll_die() << std::endl;
59     }
60 }
61