Created
February 14, 2012 19:32
-
-
Save kimyoutora/1829494 to your computer and use it in GitHub Desktop.
Powerset
This file contains hidden or 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
# my attempt | |
def powerset(set) | |
all_sets = [[]] | |
set.each do |elem| | |
subsets = [] | |
all_sets.each do |subset| | |
subsets << subset + [elem] | |
end | |
all_sets += subsets | |
end | |
all_sets | |
end | |
puts powerset([]).inspect | |
puts powerset([1]).inspect | |
puts powerset([1,2]).inspect | |
puts powerset([1,2,3]).inspect | |
# Pro version | |
# The Array power set is stolen from http://snippets.dzone.com/posts/show/3524 | |
class Array | |
# Returns the "power set" for this Array. This means that an array with all | |
# subsets of the array's elements will be returned. | |
def power_set | |
# the power set line is stolen from http://johncarrino.net/blog/2006/08/11/powerset-in-ruby/ | |
inject([[]]) do |c,y| | |
r=[] | |
c.each do |i| | |
r << i | |
r << i + [y] | |
end | |
r | |
end | |
end | |
end | |
puts [1,2,3].power_set.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment