weighted_die.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. //[weighted_die
  10. /*`
  11. For the source of this example see
  12. [@boost://libs/random/example/weighted_die.cpp weighted_die.cpp].
  13. */
  14. #include <boost/random/mersenne_twister.hpp>
  15. #include <boost/random/discrete_distribution.hpp>
  16. boost::mt19937 gen;
  17. /*`
  18. This time, instead of a fair die, the probability of
  19. rolling a 1 is 50% (!). The other five faces are all
  20. equally likely.
  21. __discrete_distribution works nicely here by allowing
  22. us to assign weights to each of the possible outcomes.
  23. [tip If your compiler supports `std::initializer_list`,
  24. you can initialize __discrete_distribution directly with
  25. the weights.]
  26. */
  27. double probabilities[] = {
  28. 0.5, 0.1, 0.1, 0.1, 0.1, 0.1
  29. };
  30. boost::random::discrete_distribution<> dist(probabilities);
  31. /*`
  32. Now define a function that simulates rolling this die.
  33. */
  34. int roll_weighted_die() {
  35. /*<< Add 1 to make sure that the result is in the range [1,6]
  36. instead of [0,5].
  37. >>*/
  38. return dist(gen) + 1;
  39. }
  40. //]
  41. #include <iostream>
  42. int main() {
  43. for(int i = 0; i < 10; ++i) {
  44. std::cout << roll_weighted_die() << std::endl;
  45. }
  46. }