function election ( trial_num, N, n, M, may_vote_for_self )

%*****************************************************************************80
%
%% election() models papal and imperial elections.
%
%  Discussion:
%
%    N voters participate in an election.
%    n of the voters are candidates.
%    Voting rules may allow a voter to vote for themselves, or not.
%    M votes are required in order for a leader to be chosen.
%    What is the probability that, on a single vote, a leader will be chosen?
%
%  Example:
%
%    N  n  M  self  leader
%
%    3  2  2     0   1.000
%    3  2  2     1   1.000
%    3  3  2     0   0.750
%    3  3  2     1   0.778
%    7  7  4     0   0.05989
%    7  7  4     1   0.07099
%   25  2 17     0   0.09278
%   25  2 17     1   0.10891
%   25  3 17     0   0.00094
%   25  3 17     1   0.00115
%   25  4 17     0   0.00004
%   25  4 17     1   0.00005
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    26 January 2018
%
%  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 N, the number of voters.
%
%    integer n, the number of candidates.
%
%    integer M, the number of votes required for a leader.
%
%    logical, may_vote_for_self, is 1 if a voter may vote for themself.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'election():\n' );
  fprintf ( 1, '  N voters participate in an election.\n' );
  fprintf ( 1, '  n of the voters are candidates.\n' );
  fprintf ( 1, '  Voting rules may allow a voter to vote for themselves, or not.\n' );
  fprintf ( 1, '  M votes are required in order for a leader to be chosen.\n' );
  fprintf ( 1, '  What is the probability that, on a single vote, a leader will be chosen?\n' );

  leader = 0;
 
  for loop = 1 : trial_num

    result = zeros ( 1, n );
    for ballot = 1 : N
      select = ceil ( n * rand ( ) );
      if ( may_vote_for_self == 0 )
        while ( select == ballot )
          select = ceil ( n * rand ( ) );
        end
      end
      result(select) = result(select) + 1;
    end
    most = max ( result );
    if ( M <= most )
      leader = leader + 1;
    end
  end

  leader = leader / trial_num;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Probability a leader was selected = %g\n', leader );

  return
end
