I recently wrote a program about the crazy guy waiting airplane question, which says:
A line of 100 airline passengers is waiting to board a plane. They each hold a ticket to one of the 100 seats on that flight. (For convenience, let's say that the nth passenger in line has a ticket for the seat number n.) Unfortunately, the first person in line is crazy, and will ignore the seat number on their ticket, picking a random seat to occupy. All of the other passengers are quite normal, and will go to their proper seat unless it is already occupied. If it is occupied, they will then find a free seat to sit in, at random. What is the probability that the last (100th) person to board the plane will sit in their proper seat (#100)?
I did monte carlo to get the answer, but not very efficient, since for the passengers, whose seat is sited. I first get a random number, and then checked from the first seat, if it is sited, then skip that one.
By the way the answer should be 1/2 :)
anybody has a better idea to do this one?
#include <iostream>
#include <vector>
#include <random>
using namespace std;
mt19937 generator;
uniform_real_distribution<double> ranuni(0, 1);
bool test(){
vector<int> line(100, 0);
int remaining(100);
int temp = remaining * ranuni(generator);
if (temp == 99)
return 0;
line[temp] = 1;
--remaining;
for (int i = 1; i < 99; ++i){
temp = remaining * ranuni(generator);
auto itr = line.begin();
while (temp != 0){
++itr;
if (*itr == 0)
--temp;
}
if (itr == line.end()-1)
return 0;
else
*itr = 1;
--remaining;
}
return 1;
}
int main(){
cout << "please input number of simulations" << endl;
int num;
cin >> num;
int sum(0);
for (int i = 0; i < num; ++i)
sum += test();
cout << double(sum) / double(num) << endl;
return 0;
}