fork download
  1. #include <iostream>
  2. #include <stdlib.h>
  3.  
  4. unsigned throw_dice_mod6()
  5. {
  6. return rand() % 6;
  7. }
  8.  
  9. unsigned throw_dice_fred()
  10. {
  11. static const unsigned divisor = static_cast<unsigned>((RAND_MAX + 1.0) / 6);
  12. static const unsigned safe_bound = divisor * 6;
  13. unsigned x;
  14. do x = rand(); while (x >= safe_bound);
  15. return x / divisor;
  16. }
  17.  
  18. void test(const char* description, unsigned throw_function())
  19. {
  20. std::cout << description << '\n';
  21. int count[6] = {0};
  22. for (int i = 0; i < 60000; ++i)
  23. {
  24. ++count[throw_function()];
  25. }
  26. for (int i = 0; i < 6; ++i)
  27. {
  28. std::cout << (i + 1) << ": " << count[i] << '\n';
  29. }
  30. }
  31.  
  32. int main()
  33. {
  34. test("mod6", throw_dice_mod6);
  35. test("fred", throw_dice_fred);
  36. }
  37.  
Success #stdin #stdout 0s 2896KB
stdin
Standard input is empty
stdout
mod6
1: 10014
2: 9912
3: 10289
4: 10041
5: 9875
6: 9869
fred
1: 9788
2: 10152
3: 9874
4: 10053
5: 10029
6: 10104