
class Array

  # Yields the block to each unique combination of _n_ elements.
  #
  #   a = %w|a b c d|
  #   a.each_combination(3) do |c|
  #     p c
  #   end
  #
  # produces
  #
  #   ["a", "b", "c"]
  #   ["a", "b", "d"]
  #   ["a", "c", "d"]
  #   ["b", "c", "d"]
  #
  def each_combination(k=2)
    s = self.to_a
    n = s.size
    return unless (1..n) === k
    idx = (0...k).to_a
    loop do
      yield s.values_at(*idx)
      i = k - 1
      i -= 1 while idx[i] == n - k + i
      break if i < 0
      idx[i] += 1
      (i + 1 ... k).each {|j| idx[j] = idx[i] + j - i}
    end
  end

end



#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCEnumerable < Test::Unit::TestCase

    def test_each_combination
      r = []
      a = [1,2,3,4]
      a.each_combination(2){ |a,b| r << [a,b] }
      assert_equal( [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]], r )
    end

  end

=end

