Sha256: e327e5daf662ca3f32ae5336798ea8c6e3555232b99cd9bc0b3430050d9e21aa
Contents?: true
Size: 812 Bytes
Versions: 2
Compression:
Stored size: 812 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) n = self.size return unless (1..n) === k idx = (0...k).to_a loop do yield self.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 #__TEST__ if $0 == __FILE__ require 'test/unit' class TestCase < Test::Unit::TestCase a = [1, 2, 1] z = [] a.each_combination(2) { |c| z << c } assert_equal([[1,2],[1,1],[1,1],[2,1]], z) end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
facets-0.7.0 | lib/facet/array/each_combination.rb |
facets-0.7.1 | lib/facet/array/each_combination.rb |