function gr ( a, b, p )

%*****************************************************************************80
%
%% GR simulates the Gambler's Ruin process.
%
%  Discussion:
%
%    Players A and B repeatedly play a game against each other.
%    On each game, player A has a probability P of winning.
%    After each game, the winner gets 1 dollar from the loser.
%    The players begin with A nd B dollars, respectively.
%    They play until one is bankrupt.
%    How long will it take for one player to go bankrupt?
%    What is the probability that A is ruined?
%
%  Modified:
%
%    31 January 2018
%
%  Author:
%
%    Paul Nahin
%
%  Reference:
%
%    Paul Nahin,
%    Will You Be Alive 10 Years From Now?,
%    Princeton, 2014,
%    ISBN: 978-0691156804,
%    LC: QA273.25.N344
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'GR:\n' );
  fprintf ( 1, '  Players A and B repeatedly play a game against each other.\n' );
  fprintf ( 1, '  On each game, player A has a probability P of winning.\n' );
  fprintf ( 1, '  After each game, the winner gets 1 dollar from the loser.\n' );
  fprintf ( 1, '  The players begin with A nd B dollars, respectively.\n' );
  fprintf ( 1, '  They play until one is bankrupt.\n' );
  fprintf ( 1, '  How long will it take for one player to go bankrupt?\n' );
  fprintf ( 1, '  What is the probability that A is ruined?\n' );

  LS = 0;
  AR = 0;

  for loop = 1 : 100000

    A = a;
    B = b;
    X = 0;

    while ( 0 < A && 0 < B )
      if ( rand ( ) < p )
        A = A + 1;
        B = B - 1;
      else
        A = A - 1;
        B = B + 1;
      end
      X = X + 1;
    end

    LS = LS + X;
    if ( A == 0 )
      AR = AR + 1;
    end

  end

  LS = LS / 100000;
  AR = AR / 100000;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Average number of games played is %g\n', LS );
  fprintf ( 1, '  Probability A is ruined = %g\n', AR );

  return
end
