function optimal ( n, top )

%*****************************************************************************80
%
%% OPTIMAL simulates the dating problem.
%
%  Discussion:
%
%    A dating club offers N potential partners.
%    It turns out that any of TOP of these partners would be acceptable.
%    The dater gets 1 date with each partner, but immediately after the
%    date, must either marry that partner, or move to the next date.
%    The dater plans to date a sample of the partners without a marriage
%    offer, and then marry the next partner who is better than all
%    the sample dates. 
%    As the sample size is varied, what are the chances of happiness?
%    
%  Modified:
%
%    27 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 parameters:
%
%    Input, integer N, the size of the dating pool.
%
%    Input, integer TOP, the number of acceptable choices.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'OPTIMAL:\n' );
  fprintf ( 1, '  A dating club offers N potential partners.\n' );
  fprintf ( 1, '  It turns out that any of TOP of these partners would be acceptable.\n' );
  fprintf ( 1, '  The dater gets 1 date with each partner, but immediately after the\n' );
  fprintf ( 1, '  date, must either marry that partner, or move to the next date.\n' );
  fprintf ( 1, '  The dater plans to date a sample of the partners without a marriage\n' );
  fprintf ( 1, '  offer, and then marry the next partner who is better than all\n' );
  fprintf ( 1, '  the sample dates. \n' );
  fprintf ( 1, '  As the sample size is varied, what are the chances of happiness?\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Use graphics to display result.\n' );

  results = zeros ( 1, ceil ( 4 * n / 5 ) );

  for sample_size = 1 : ceil ( 4 * n / 5 )

    check = zeros ( 1, sample_size );
    success = 0;
    for loop = 1 : 10000
      order = randperm ( n );
      for j = 1 : sample_size
        check(j) = order(j);
      end
      best_in_sample = min(check);
      exit = 0;
      k = sample_size + 1;
      while ( exit == 0 )
        if ( order(k) < best_in_sample )
          select = order(k);
          exit = 1;
        else
          k = k + 1;
        end
        if ( k == n + 1 )
          select = order(n);
          exit = 1;
        end
      end

      for k = 1 : top
        if ( select == k )
          success = success + 1;
        end
      end

    end

    results(sample_size) = success;

  end

  results = results / 10000;
%
%  Graphics.
%
  clf
  bar(results);
  grid on
  xlabel ( 'Sample lot size' )
  ylabel ( 'Probability of happiness' )
  title ( 'OPTIMAL: The dating problem.' )
  filename = 'optimal.png';
  print ( '-dpng', filename )
  fprintf ( 1, '  Graphics saved as "%s"\n', filename );
  pause ( 5 );

  return
end
