function idiots1 ( trial_num )

%*****************************************************************************80
%
%% idiots1() models a duel between two idiots.
%
%  Discussion:
%
%    A and B fight a duel, but they only have one gun, a six-shot revolver.
%    A will spin the cylinder and fire at B.
%    If the gun doesn't fire, then B will spin the cylinder and fire at A.
%    They continue to alternate until one of them is shot.
%    What is the probablity that A will win?
%    What is the average number of trigger pulls?
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    07 May 2019
%
%  Author:
%
%    Paul Nahin
%
%  Reference:
%
%    Paul Nahin,
%    Dueling Idiots and Other Probability Puzzlers,
%    Princeton, 2012,
%    ISBN: 978-0691155005.
%
%  Input:
%
%    integer trial_num: the number of trials.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'idiots1():\n' );
  fprintf ( 1, '  A and B fight a duel, but they only have one gun, a six-shot revolver.\n' );
  fprintf ( 1, '  A will spin the cylinder and fire at B.\n' );
  fprintf ( 1, '  If the gun does not fire, then B will spin the cylinder and fire at A.\n' );
  fprintf ( 1, '  They continue to alternate until one of them is shot.\n' );
  fprintf ( 1, '  What is the probablity that A will win?\n' );
  fprintf ( 1, '  What is the average number of trigger pulls?\n' );

  duration = zeros(1,100);      % assume no duel exceeds 100 trigger-pulls;
  a = 0;                       % number of times A has won;
  nd = 0;                      % number of duels completed;
  tp = 0;                      % number of trigger pulls so far

  while ( nd < trial_num )

    tp = tp + 1;               %A pulls the trigger
    if ( rand ( ) <= 1 / 6 )   %A wins
      duration(tp) = duration(tp) + 1;
                               %duel is over, update the duration vector;
      tp = 0;                  %initialize trigger-pulls for next duel;
      a = a + 1;
      nd = nd + 1;
    else
      tp = tp + 1;             %B pulls the trigger
      if ( rand ( ) <= 1 / 6 ) %B wins
        duration(tp) = duration(tp) + 1;
                               %duel is over, update duration vector;
        tp = 0;                %initialize trigger-pulls for next duel;
        nd = nd + 1;
      end
    end

  end 

  a = a / trial_num;
  average = 0.0;
  for k = 1 : length ( duration )
    average = average + k * duration(k);
  end
  average = average / trial_num;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  The probability A wins is %g\n', a );
  fprintf ( 1, '  The average number of trigger-pulls/duel is %g\n', average );
%
%  Graphics.
%
  clf ( );
  bar ( duration );
  title ( 'Relative Frequency of the Number of Trigger-Pulls per Duel');
  xlabel ( 'duration of duels, in units of trigger-pulls' );
  ylabel ( 'number of duels' );
  grid ( 'on' );
  filename = 'idiots1.png';
  print ( '-dpng', filename );
  fprintf ( '  Graphics saved as "%s"\n', filename );

  return
end

