function [ AR, LS ] = gamblers_ruin ( a, b, p )

%*****************************************************************************80
%
%% gamblers_ruin() 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?
%
%  Licensing:
%
%    This code is distributed under the MIT license. 
%
%  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
%
%  Input:
%
%    real A, B: the initial dollars for players A and B.
%
%    real P: the probability that A will win any one game.
%
%  Output:
%
%    real AR: the probability that A will be ruined.
%
%    integer LS: the average number of games played before one player is ruined.
%
  LS = 0;
  AR = 0.0;
  trial_num = 100000;

  for loop = 1 : trial_num

    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 / trial_num;
  AR = AR / trial_num;

  return
end
