Created
October 10, 2010 15:03
-
-
Save sahglie/619299 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def subsets(array) | |
subsets = [] | |
array.each do |elem| | |
new = subsets.inject([]) { |accum, n| accum << n.dup.push(elem) } | |
subsets.concat(new) | |
subsets << [elem] | |
end | |
subsets | |
end | |
def filter_subsets(subsets, array) | |
lookup = array.inject({}) { |hash, elem| hash[elem] = true && hash } | |
subsets.inject([]) do |accum, subset| | |
if (subset.length > 1) && lookup[subset.inject(:+)] | |
accum << subset | |
end | |
accum | |
end | |
end | |
array = [3, 4, 9, 14, 15, 19, 28, 37, 47, 50, 54, 56, 59, 61, 70, 73, 78, 81, 92, 95, 97, 99] | |
sets = subsets(array) | |
puts "generated #{sets.length} subsets" | |
puts "filtering subsets" | |
fsets = filter_subsets(sets, array) | |
puts "#{fsets.length} matching subsets" | |
# $ time ruby find_subsets.rb | |
# => Generated 4194303 subsets | |
# filtering subsets | |
# 179 matching subsets | |
# 42.422 secs | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment