function prob = airplane_seat ( trial_num, n )

%*****************************************************************************80
%
%% airplane_seat() simulates the airplane seat problem.
%
%  Discussion:
%
%    Airline passengers 1 through N are assigned seats 1 through N.
%    But passenger 1 is clueless, and chooses a seat randomly.
%    The remaining passengers board in order, choosing their assigned seat
%    if possible, otherwise taking an empty seat at random.
%
%    What is the probability that the last passenger, N, will be able to 
%    sit in the correct assigned seat N?
%
%  Licensing:
%
%    This code is distributed under the MIT license. 
%
%  Modified:
%
%    30 January 2018
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Paul Nahin,
%    Will You Be Alive 10 Years From Now?,
%    Princeton, 2014,
%    ISBN: 978-0691156804,
%    LC: QA273.25.N344
%
%  Input:
%
%    integer trial_num: the number of simulations.
%
%    integer N, the number of passengers.
%
%  Output:
%
%    real PROB: the probability that the last passenger will be 
%    properly seated.
%
  prob = 0.0;

  for test = 1 : trial_num

    occupant = zeros ( n, 1 );
%
%  Passenger 1 chooses a seat at random.
%
    passenger = 1;
    seat = randi ( [ 1, n ] );

    occupant(seat) = passenger;
%
%  Passenger I will choose seat I if it is available,
%  otherwise a random available seat.
%
    for passenger = 2 : n

      seat = passenger;
      while ( occupant(seat) ~= 0 )
        seat = randi ( [ 1, n ] );
      end

      occupant(seat) = passenger;

    end
%
%  Did passenger N sit in seat N?
%
    if ( occupant(n) == n )
      prob = prob + 1;
    end

  end

  prob = prob / trial_num;

  return
end
