function bus ( n )

%*****************************************************************************80
%
%% BUS estimates the waiting time, given that there are N bus lines.
%
%  Discussion:
%
%    N bus lines are available at a bus stop.
%    In any hour, each bus line will come to the stop at a random time.
%    A passenger arrives at the bus stop at a random time.
%    What is the average wait for a bus?
%
%  Example:
%
%    N    Average wait
%
%    1    0.4996
%    2    0.3335
%    3    0.2503
%    4    0.2001
%    5    0.1667
%
%  Modified:
%
%    26 January 2018
%
%  Author:
%
%    Paul Nahin
%
%  Reference:
%
%    Paul Nahin,
%    Digital Dice: Computational Solutions to Practical Probability Problems,
%    Princeton, 2008,
%    ISBN: 978-0-691-15821-1.
%
%  Input parameters:
%
%    Input, integer N, the number of bus lines.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'BUS:\n' );
  fprintf ( 1, '  N bus lines are available at a bus stop.\n' );
  fprintf ( 1, '  In any hour, each bus line will come to the stop at a random time.\n' );
  fprintf ( 1, '  A passenger arrives at the bus stop at a random time.\n' );
  fprintf ( 1, '  What is the average wait for a bus?\n' );

  total_waiting_time = 0;

  for loop = 1 : 1000000

    bus_arrivals = zeros ( 1, n );
    for ( j = 2 : n )
      bus_arrivals(j) = rand ( );
    end

    ride_arrival = rand ( );
    sorted_bus = sort ( bus_arrivals );

    if ( ride_arrival > sorted_bus(n) )

      waiting_time = 1 - ride_arrival;

    else

      test = 1;
      j = 2;

      while ( test == 1 )
        if ( ride_arrival < sorted_bus(j) )
          waiting_time = sorted_bus(j) - ride_arrival;
          test = 0;
        else
          j = j + 1;
        end
      end

    end

    total_waiting_time = total_waiting_time + waiting_time;
  
  end

  total_waiting_time = total_waiting_time / 1000000;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Estimated waiting time = %g\n', total_waiting_time );
  fprintf ( 1, '  Theoretical time = %g\n', 1 / ( n + 1 ) );

  return
end
