Sha256: f6b2a675e0887ebd8a2984840baeb83736d55a8b0e05b12303396b02d0ecf0e3

Contents?: true

Size: 987 Bytes

Versions: 26

Compression:

Stored size: 987 Bytes

Contents

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

Version data entries

26 entries across 26 versions & 1 rubygems

Version Path
facets-0.9.0 lib/nano/enumerable/each_combination.rb
facets-1.0.3 packages/core/lib/facet/enumerable/each_combination.rb
facets-1.0.0 lib/facet/enumerable/each_combination.rb
facets-1.2.1 lib/facets/core/enumerable/each_combination.rb
facets-1.1.0 lib/facet/enumerable/each_combination.rb
facets-1.2.0 lib/facets/core/enumerable/each_combination.rb
facets-1.3.0 lib/facets/core/enumerable/each_combination.rb
facets-1.3.1 lib/facets/core/enumerable/each_combination.rb
facets-1.3.3 lib/facets/core/enumerable/each_combination.rb
facets-1.3.2 lib/facets/core/enumerable/each_combination.rb
facets-1.4.0 lib/facets/core/enumerable/each_combination.rb
facets-1.4.2 lib/facets/core/enumerable/each_combination.rb
facets-1.4.1 lib/facets/core/enumerable/each_combination.rb
facets-1.4.3 lib/facets/core/enumerable/each_combination.rb
facets-1.4.4 lib/facets/core/enumerable/each_combination.rb
facets-1.4.5 lib/facets/core/enumerable/each_combination.rb
facets-1.7.30 lib/facets/core/enumerable/each_combination.rb
facets-1.7.0 lib/facets/core/enumerable/each_combination.rb
facets-1.7.38 lib/facets/core/enumerable/each_combination.rb
facets-1.7.46 lib/facets/core/enumerable/each_combination.rb