die.cpp 1.9 KB

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