function chess ( p, q )

%*****************************************************************************80
%
%% CHESS compares two options for a chess tournament.
%
%  Discussion:
%
%    Player A must play three games of chess, against players B and C.
%    C is the stronger player.
%    A has a choice of two schedules of opponents: BCB or CBC.
%    A will win the tournament by winning two games in immediate succession.
%    What is the better schedule?
%
%  Examples:
%
%    Theoretical results include:
%
%      P    Q      P1      P2
%
%    0.9  0.8  0.7920  0.8640
%    0.9  0.4  0.3960  0.5760
%    0.4  0.3  0.1920  0.2040
%    0.4  0.1  0.0640  0.0760
%
%  Modified:
%
%    22 January 2018
%
%  Author:
%
%    Paul Nahin
%
%  Reference:
%
%    Paul Nahin,
%    Digital Dice: Computational Solutions to Practical Probability Problems,
%    Princeton, 2008,
%    ISBN: 978-0-691-15821-1.
%   
%  Parameters:
%
%    Input, real P, the probability that A will beat B in one game.
%
%    Input, real Q, the probability that A will beat C in one game.
% 
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CHESS:\n' );
  fprintf ( 1, '  A has to play three games of chess against B and C.\n' );
  fprintf ( 1, '  A beats B with probability P, C with probability Q\n' );
  fprintf ( 1, '  A has a choice of schedules: BCB or CBC.\n' );
  fprintf ( 1, '  To win the tournament, A must win two successive games.\n' );
  fprintf ( 1, '  Which schedule is better\n' );

  prob(1,1) = p;
  prob(1,2) = q;
  prob(1,3) = p;

  prob(2,1) = q;
  prob(2,2) = p;
  prob(2,3) = q;

  won_matches = zeros ( 1, 2 );

  for loop = 1 : 1000000

    won_game = zeros(2,3);

    for k = 1 : 3
      result(k) = rand ( );
    end

    for game = 1 : 3
      for sequence = 1 : 2
        if ( result(game) < prob(sequence,game) )
          won_game(sequence,game) = 1;
        end
      end
    end

    for sequence = 1 : 2
      if ( won_game(sequence,1) + won_game(sequence,2) == 2 | ...
           won_game(sequence,2) + won_game(sequence,3) == 2 )
        won_matches(sequence) = won_matches(sequence) + 1;
      end
    end

  end

  won_matches(1) = won_matches(1) / 1000000;
  won_matches(2) = won_matches(2) / 1000000;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Estimated win probability for BCB is = %g\n', won_matches(1) );
  fprintf ( 1, '  Estimated win probability for CBC is = %g\n', won_matches(2) );

  return
end
