Guest User

Untitled

a guest
Jul 22nd, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. /*Task 110. A hunter has to shoot at least K animals. He knows the probability of every animal been shot.
  2. Find the probability of the hunter's success.
  3.  
  4. The term "at least K animals been shot" is that the hunter can miss no more than (N-K) times.
  5. The task is being solved recursively by considering two situations:
  6. - the current animal is shot with probability of p[i], and we still have K rooms to fail for other animals;
  7. - the current animal is missed with probability of (1-p[i]), and we now have (K-1) rooms to fail for other animals.
  8. The task has two return conditions:
  9. - all animals have already been shot or missed: the probability to shoot 0 animals is 100%;
  10. - we've missed K times and now we have to become The Gunslinger and kill the rest of the animals: the probability is p[i+1]*p[i+2]*...
  11. */
  12.  
  13. #include <iostream>
  14. #include <vector>
  15. #include <numeric>
  16.  
  17. double task110_impl(std::vector<double> const& probs, int can_be_missed) {
  18. // An ideal hunt is when you shall not shoot at all:
  19. if (probs.size() == 0)
  20. return 1.;
  21.  
  22. // You have already got some misses. You have to shoot rest of the animals:
  23. if (can_be_missed == 0)
  24. return std::accumulate(probs.begin(), probs.end(), 1., std::multiplies<double>());
  25.  
  26. std::vector<double> psi(probs.begin() + 1, probs.end());
  27.  
  28. // Else you get two cases:
  29. // - you shoot the current animal with probability of `probs[0]` and then you have `can_be_missed` shots;
  30. // - you miss the current shot with probability of `1-probs[0]` and you have `can_be_missed-1` shots.
  31. return probs[0] * task110_impl(psi, can_be_missed) +
  32. (1. - probs[0]) * task110_impl(psi, can_be_missed - 1);
  33. }
  34.  
  35. double task110(std::vector<double> const& probs, int must_be_shot) {
  36. // The condition "at least K animals been shot" is like a hunter can miss no more than (N-K) times.
  37. return task110_impl(probs, probs.size() - must_be_shot);
  38. }
  39.  
  40.  
  41. int main(void) {
  42. std::cout << task110({ 0.5, 0.5, 0.5 }, 2) << '\n';
  43. std::cout << task110({ 0.3, 0.4, 0.7, 0.1 }, 3) << '\n';
  44. std::cout << task110({ 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 }, 8) << '\n';
  45.  
  46. system("pause");
  47. return 0;
  48. }
Add Comment
Please, Sign In to add comment