function thief ( trial_num )

%*****************************************************************************80
%
%% thief() simulates the Thief of Baghdad problem.
%
%  Discussion:
%
%    A thief is in a room with three doors.
%    He chooses one at random.
%    One door leads immediately to freedom.
%    Another leads back to the room, after S hours.
%    The third leads back to the room, after L hours.
%    If the thief is returned to the room, he randomly tries a door again.
%    How long is the average imprisonment?
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    29 January 2018
%
%  Author:
%
%    Paul Nahin
%
%  Reference:
%
%    Paul Nahin,
%    Dueling Idiots and Other Probability Puzzlers,
%    Princeton, 2012,
%    ISBN: 978-0691155005.
%
%  Input:
%
%    integer trial_num: the number of trials.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'thief()\n' );
  fprintf ( 1, '  A thief is in a room with three doors.\n' );
  fprintf ( 1, '  He chooses one at random.\n' );
  fprintf ( 1, '  One door leads immediately to freedom.\n' );
  fprintf ( 1, '  Another leads back to the room, after S hours.\n' );
  fprintf ( 1, '  The third leads back to the room, after L hours.\n' );
  fprintf ( 1, '  If the thief is returned to the room, he randomly tries a door again.\n' );
  fprintf ( 1, '  How long is the average imprisonment?\n' );

  long = 3;
  short = 1;
  total = 0;
  p1 = 1 / 3;
  p2 = 2 / 3;

  for thiefn = 1 : trial_num

    time = 0;
    trytoescape = 1;
    while ( trytoescape > 0 )

      door = rand ( );

      if ( door < p1 )
        total = total + time;
        trytoescape = 0;
      elseif ( door < p2 )
        time=time + short;
      else
        time=time + long;
      end

    end

  end

  total = total / trial_num;
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Estimated average total time in prison = %g\n', total );
  fprintf ( 1, '  Exact value is %g\n', long + short );

  return
end
                                 
   
