Skip to content

Commit

Permalink
add Enumerable.all_combinations
Browse files Browse the repository at this point in the history
  • Loading branch information
chastell committed May 19, 2009
1 parent 9b41d70 commit e05c36c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
17 changes: 17 additions & 0 deletions lib/enumerable.rb
@@ -1,5 +1,22 @@
module Enumerable

def self.all_combinations source
result_count = source.map(&:size).inject(:*)
group_count = 1
result = []
source.each do |elems|
row = []
group_count.times do
elems.each do |elem|
(result_count / group_count / elems.size).times { row << elem }
end
end
group_count *= elems.size
result << row
end
result.transpose
end

def pairs
return combination 2 if respond_to? :combination
Enumerator.new do |yielder|
Expand Down
6 changes: 6 additions & 0 deletions spec/enumerable_spec.rb
Expand Up @@ -11,4 +11,10 @@
array.pairs
end

it 'should have a method to get all possible combinations of the passed elements' do
source = [[:a,:b], [:c], [:d,:e,:f]]
Enumerable.all_combinations(source).should == [[:a,:c,:d], [:a,:c,:e], [:a,:c,:f],
[:b,:c,:d], [:b,:c,:e], [:b,:c,:f]]
end

end

0 comments on commit e05c36c

Please sign in to comment.