function c = comb ( n, p, l )

%*****************************************************************************80
%
%% comb() selects a subset of order P from a set of order N.
%
%  Discussion:
%
%    This subroutine finds the combination set of N things taken
%    P at a time for a given lexicographic index.
%
%  Modified:
%
%    30 March 2016
%
%  Author:
%
%    Bill Buckles, Matthew Lybanon
%
%  Reference:
%
%    Bill Buckles, Matthew Lybanon,
%    Algorithm 515: Generation of a Vector from the Lexicographical Index,
%    ACM Transactions on Mathematical Software,
%    Volume 3, Number 2, June 1977, pages 180-182.
%
%  Input:
%
%    integer N, the number of things in the set.
%
%    integer P, the number of things in each combination.
%    0 < P < N.
%
%    integer L, the lexicographic index of the 
%    desired combination.  1 <= L <= choose(N,P).
%
%  Output:
%
%    integer C(P), the combination set.
%
  c = zeros ( p, 1 );
%
%  Special case: P = 1
%
  if ( p == 1 )
    c(1) = l;
    return
  end
%
%  Initialize lower bound index.
%
  k = 0;
%
%  Select elements in ascending order.
%
  p1 = p - 1;
  c(1) = 0;

  for i = 1 : p1
%
%  Update lower bound as the previously selected element.
%
    if ( 1 < i )
      c(i) = c(i-1);
    end
%
%  Check validity of each entry.
%
    while ( true )

      c(i) = c(i) + 1;
      r = binom ( n - c(i), p - i );
      k = k + r;

      if ( l <= k )
        break
      end

    end

    k = k - r;

  end

  c(p) = c(p1) + l - k;

  return
end
