fork(1) download
  1. #include <iostream>
  2. #include <random>
  3. #include <string>
  4. #include <vector>
  5. #include <algorithm>
  6. #include <cstdint>
  7. #include <cstdlib>
  8. #include <ctime>
  9.  
  10. int main(void)
  11. {
  12. int max = 10000000;
  13. std::srand(static_cast<unsigned>(std::time(0)));
  14. // std::random_device rnd; // random_device not working properly under Windows MinGW
  15. std::vector<std::uint32_t> v(10);
  16. // std::generate(v.begin(), v.end(), std::ref(rnd));
  17. std::generate(std::begin(v), std::end(v), std::rand);
  18. auto seed = std::seed_seq(std::begin(v), std::end(v));
  19. auto rand = std::bind(std::uniform_int_distribution<>(1, max - 1), std::mt19937(seed));
  20. int ans = rand();
  21. int iter = 0, tmp = 0, dis = 0;
  22. std::string str = "", gt = "greater than ans", lt = "less than ans";
  23.  
  24. while (true) {
  25. iter++;
  26. if (iter == 1) {
  27. tmp = max / 2;
  28. dis = tmp / 2;
  29. str = (tmp > ans) ? gt : lt;
  30. } else if (tmp > ans) {
  31. tmp -= dis;
  32. if (dis > 1)
  33. dis /= 2;
  34. str = gt;
  35. } else if (tmp < ans) {
  36. tmp += dis;
  37. if (dis > 1)
  38. dis /= 2;
  39. str = lt;
  40. }
  41. if (tmp == ans)
  42. str = "hit!";
  43. std::cout << "iter = " << iter << ", tmp = " << tmp << " " << str << std::endl;
  44. if (tmp == ans)
  45. break;
  46. }
  47. }
  48.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
iter = 1, tmp = 5000000 greater than ans
iter = 2, tmp = 2500000 greater than ans
iter = 3, tmp = 1250000 greater than ans
iter = 4, tmp = 1875000 less than ans
iter = 5, tmp = 2187500 less than ans
iter = 6, tmp = 2343750 less than ans
iter = 7, tmp = 2421875 less than ans
iter = 8, tmp = 2460937 less than ans
iter = 9, tmp = 2441406 greater than ans
iter = 10, tmp = 2451171 less than ans
iter = 11, tmp = 2456053 less than ans
iter = 12, tmp = 2458494 less than ans
iter = 13, tmp = 2457274 greater than ans
iter = 14, tmp = 2456664 greater than ans
iter = 15, tmp = 2456359 greater than ans
iter = 16, tmp = 2456511 less than ans
iter = 17, tmp = 2456587 less than ans
iter = 18, tmp = 2456625 less than ans
iter = 19, tmp = 2456644 less than ans
iter = 20, tmp = 2456653 less than ans
iter = 21, tmp = 2456657 less than ans
iter = 22, tmp = 2456659 less than ans
iter = 23, tmp = 2456660 less than ans
iter = 24, tmp = 2456661 less than ans
iter = 25, tmp = 2456662 hit!