Sha256: 8edac4e7bd37c082ce8adf78b2b25bd915f18255b94c328ed6c9fe9f34fb06f4
Contents?: true
Size: 1.14 KB
Versions: 3
Compression:
Stored size: 1.14 KB
Contents
unless (RUBY_VERSION[0,3] == '1.9') require 'enumerator' class Array # Yields the block to each unique combination of _n_ elements. # # a = %w|a b c d| # a.combination(3) # # produces # # [["a", "b", "c"], # ["a", "b", "d"], # ["a", "c", "d"], # ["b", "c", "d"]] # # CREDIT: Florian Gross def combination(k=2) if block_given? s = 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 else to_enum(:combination, k) end end # OLD WAY #a = [] #s = self #n = s.size #return unless (1..n) === k #dx = (0...k).to_a #loop do # a << 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 #a end end
Version data entries
3 entries across 3 versions & 1 rubygems
Version | Path |
---|---|
facets-2.4.4 | lib/core/facets/array/combination.rb |
facets-2.4.2 | lib/core/facets/array/combination.rb |
facets-2.4.3 | lib/core/facets/array/combination.rb |