function win = monty_hall_simulation ( switch_doors, ndoors )

%*****************************************************************************80
%
%% monty_hall_simulation() simulates the Monty Hall prize game.
%
%  Licensing:
%
%    This code is distributed under the MIT license. 
%
%  Modified:
%
%    26 August 2022
%
%  Author:
%
%    Original Python code by Christian Hill.
%    MATLAB version by John Burkardt
%
%  Reference:
%
%    Christian Hill,
%    Learning Scientific Programming With Python,
%    Second Edition,
%    Cambridge University Press, 2020
%    ISBN: 978-1-108-74591-8
%
%  Input:
%
%    boolean switch_doors: True if the user plans to switch.
%
%    integer ndoors: the number of doors.  Usually 3.
%    Must be at least 3.
%
%  Output:
%
%    integer WIN: 1 if the user chose the prize, 0 otherwise.
%
  if ( ndoors < 3 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'monty_hall_simulation(): Fatal error!\n' );
    fprintf ( 1, '  Number of doors must be at least 3!\n' );
    error ( 'monty_hall_simulation(): Fatal error!\n' );
  end
%
%  The prize is hidden behind a random door.
%
  prize_door = randi ( [ 1, ndoors ], 1 );
%
%  The user chooses a door at random.
%
  chosen_door = randi ( [ 1, ndoors ], 1 );
%
%  One of the doors is revealed.
%  It is always a door that was not chosen by the user,
%  and which does not contain a prize.
%
  revealable_door = [];
  revealable_num = 0;

  for door = 1 : ndoors
    if ( ( door ~= chosen_door ) && ( door ~= prize_door ) )
      revealable_door = [ revealable_door, door ];
      revealable_num = revealable_num + 1;
    end
  end

  revealed_index = randi ( [ 1, revealable_num ], 1 );
  revealed_door = revealable_door(revealed_index);
%
%  If the user's strategy is to switch, choose one of the 
%  unchosen unrevealed doors.
%
  if ( switch_doors )

    available_door = [];
    available_num = 0;

    for door = 1 : ndoors
      if ( ( door ~= chosen_door ) && ( door ~= revealed_door ) )
        available_door = [ available_door, door ];
        available_num = available_num + 1;
      end
    end

    available_index = randi ( [ 1, available_num ], 1 );
    chosen_door = available_door(available_index);

  end
%
%  Did the user win?
%
  win = ( chosen_door == prize_door );

  return
end

