function biased ( N, q )

%*****************************************************************************80
%
%% BIASED plays odd-man-out with a biased coin.
%
%  Discussion:
%
%    A game of odd man out is played, in which N people each flip a coin.
%    If one person's coin doesn't match all the others, that person 
%    is the odd man out.
%    In this version, N-1 people have fair coins, and one has a biased coin
%    whose probability of heads is Q.
%    Estimate the average number of games played.
%
%  Example:
%
%    N    Q  Games
%
%    3  0.0  1.336
%    3  0.3  1.316
%    3  0.9  1.321
%
%    4  0.0  2.064
%    4  0.3  2.032
%    4  0.9  2.051
%
%    5  0.0  3.15
%    5  0.3  3.167
%    5  0.9  3.242
%
%    6  0.0  5.323
%    6  0.3  5.210
%    6  0.9  5.190
%
%  Modified:
%
%    07 May 2019
%
%  Author:
%
%    Paul Nahin
%
%  Reference:
%
%    Paul Nahin,
%    Dueling Idiots and Other Probability Puzzlers,
%    Princeton, 2012,
%    ISBN: 978-0691155005.
%
%  Input parameters:
%
%    Input, integer N, the number of people.
%
%    Input, real Q, the biased probability of one coin.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'BIASED:\n' );
  fprintf ( 1, '  A game of odd man out is played, in which N people each flip a coin.\n' );
  fprintf ( 1, '  If one person''s coin does not match all the others, that person \n' );
  fprintf ( 1, '  is the odd man out.\n' );
  fprintf ( 1, '  In this version, N-1 people have fair coins, and one has a biased coin\n' );
  fprintf ( 1, '  whose probability of heads is Q.\n' );
  fprintf ( 1, '  Estimate the average number of games played.\n' );

  duration = zeros(1,100);

  for game = 1 : 1000

    gameover = 0;
    flip = 1;

    while ( gameover == 0 )
      s = 0;

      fair = N - 1;
      for n = 1 : fair
        coin = rand ( );
        if ( coin < 1 / 2 )
          s = s + 1;
        end
      end

      coin = rand ( );
      if ( coin < q )
        s = s + 1;
      end
      if ( s == 1 || s == N - 1 )
        gameover = 1;
      else
        flip = flip + 1;
      end
    end
    duration(flip) = duration(flip) + 1;
  end

  average = 0;
  for i = 1 : length ( duration )
    average = average + i * duration(i);
  end
  average = average / 1000;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Average number of games = %g\n', average );
  fprintf ( 1, '  Theoretical number = %g\n', 2^(N-1)/N );

  return
end
