Advertisement
TheToby

Untitled

Aug 4th, 2015
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. /*
  2. * Q1.cpp
  3.  
  4. *
  5. * Created on: 4 Aug 2015
  6. * Author: toby
  7. * Grab a stick. Break it in two. Now randomly break another piece in two. Carry out
  8. * this process a total of n times.
  9. * Write a program that takes n as input and outputs the probability that a triangle can
  10. * be formed out of any three of the resulting pieces.
  11. * This solution takes a stick breaks it, takes a random stick breaks it etc etc
  12. * Gets an answer of roughy 19-20% for 2 breaks
  13. */
  14. #include <iostream>
  15. #include <random>
  16. #include <set>
  17. #include <algorithm>
  18.  
  19. int trianglechecker(std::vector<double> & newsticks, int breaks){
  20. //checks to see if it makes a triangle
  21. for (auto it = newsticks.cbegin(); it != newsticks.cend()-2; it++){
  22. if ((*(it)+*(it+1))>(*(it+2)))return 1;
  23. }
  24. return 0;
  25. }
  26.  
  27. int main(){
  28. const int times = 1000000;
  29. int count = 0;
  30. const int breaks = 2;
  31. double stick1 = 1.0;
  32. std::random_device rd;
  33. std::mt19937 mt(rd());
  34.  
  35. for(int i =0;i<times;i++){
  36. std::set<double> breakset;
  37. //picks n number of random points to break at and puts them in a set.
  38. while(breakset.size()<breaks){
  39. std::uniform_real_distribution<double> dist(0,1);
  40. double stick2 = 0;
  41. while(stick2==0){
  42. stick2 = dist(mt);
  43. }
  44. breakset.insert(stick2);
  45. }
  46. std::vector<double> newsticks;
  47. double count1 = 0;
  48. //breaks the stick at set points into an array.
  49. for (auto it = breakset.cbegin(); it != breakset.cend(); it++){
  50. newsticks.push_back((*it) - count1);
  51. count1=(*it);
  52. }
  53. newsticks.push_back(1-count1);
  54.  
  55. std::sort(newsticks.begin(), newsticks.end());
  56. count+=trianglechecker(newsticks, breaks);
  57. }
  58. std::cout << "With " << breaks << " breaks the chance of making a triangle is " << (count/(double)times)*100 << "%" << std::endl;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement