function broke ( trial_num, l, m, n, p )

%*****************************************************************************80
%
%% broke(): average number of flips til odd man out is lost.
%
%  Discussion:
%
%    Three players begin with L, M and N dollars.
%    On each turn, each player flips a coin.
%    All coins have the same bias P.
%    If one player is "odd man out", he pays a dollar to each other player.
%    When a player is bankrupt, the game is over.
%    What is the average number of turns required?
%
%    If P = 0.5 (no bias) then the average is 4*L*M*N/3/(L+M+N-2);
%
%    L  M  N    P  FLIPS
%
%    1  1  1  0.5    4/3
%    1  2  3  0.5    2
%    2  3  4  0.5   32/7
%    3  3  3  0.5   36/7
%    4  7  9  0.5 1008/54
%
%    1  1  1  04   100/72
%
%    1  2  3  0.4   2.0814 (estimate)
%    2  3  4  0.4   4.7721 (estimate)
%    3  3  3  0.4   5.36   (estimate)
%    4  7  9  0.4  19.4875 (estimate
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    07 May 2019
%
%  Author:
%
%    Paul Nahin
%
%  Reference:
%
%    Paul Nahin,
%    Digital Dice: Computational Solutions to Practical Probability Problems,
%    Princeton, 2008,
%    ISBN: 978-0-691-15821-1.
%
%  Input:
%
%    integer trial_num: the number of trials.
%
%    integer L, M, N, the number of dollars each player has at the start.
%
%    real P, the bias on the coins.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'broke():\n' );
  fprintf ( 1, '  Three players begin with L, M and N dollars.\n' );
  fprintf ( 1, '  On each turn, each player flips a coin.\n' );
  fprintf ( 1, '  All coins have the same bias P = %g\n', p );
  fprintf ( 1, '  If one player is "odd man out", he pays a dollar to each other player.\n' );
  fprintf ( 1, '  When a player is bankrupt, the game is over.\n' );
  fprintf ( 1, '  What is the average number of turns required?\n' );

  total_flips = 0;

  for sequences = 1 : trial_num

    sequence_flips = 0;

    man = [ l, m, n ];

    while ( 0 < man(1) & 0 < man(2) & 0 < man(3) )

      flip(1) = rand ( );
      flip(2) = rand ( );
      flip(3) = rand ( );

      for j = 1 : 3
        if ( flip(j) < p )
          flip(j) = 1;
        else
          flip(j) = 0;
        end
      end

      test = sum ( flip );

      if ( test == 1 | test == 2 )
        if ( test == 1 )
          for j = 1 : 3
            if ( flip(j) == 0 )
              flip(j) = -1;
            else
              flip(j) = 2;
            end
          end
        else
          for j = 1 : 3
            if ( flip(j) == 0 )
              flip(j) = 2;
            else
              flip(j) = -1;
            end
          end
        end

        man(1:3) = man(1:3) + flip(1:3);

      end

      sequence_flips = sequence_flips + 1;

    end

  total_flips = total_flips + sequence_flips;

  end

  total_flips = total_flips / trial_num;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Average number of turns = %g\n', total_flips );

  return
end
