RosettaCodeData/Task/Power-set/Ruby/power-set.rb

45 lines
1.3 KiB
Ruby
Raw Permalink Normal View History

2013-04-10 23:57:08 -07:00
# Based on http://johncarrino.net/blog/2006/08/11/powerset-in-ruby/
2015-02-20 00:35:01 -05:00
# See the link if you want a shorter version.
2015-11-18 06:14:39 +00:00
# This was intended to show the reader how the method works.
2013-04-10 23:57:08 -07:00
class Array
# Adds a power_set method to every array, i.e.: [1, 2].power_set
def power_set
# Injects into a blank array of arrays.
# acc is what we're injecting into
# you is each element of the array
inject([[]]) do |acc, you|
2013-10-27 22:24:23 +00:00
ret = [] # Set up a new array to add into
acc.each do |i| # For each array in the injected array,
ret << i # Add itself into the new array
ret << i + [you] # Merge the array with a new array of the current element
2013-04-10 23:57:08 -07:00
end
2013-10-27 22:24:23 +00:00
ret # Return the array we're looking at to inject more.
2013-04-10 23:57:08 -07:00
end
end
# A more functional and even clearer variant.
def func_power_set
inject([[]]) { |ps,item| # for each item in the Array
ps + # take the powerset up to now and add
ps.map { |e| e + [item] } # it again, with the item appended to each element
}
end
end
#A direct translation of the "power array" version above
2013-10-27 22:24:23 +00:00
require 'set'
2013-04-10 23:57:08 -07:00
class Set
2013-10-27 22:24:23 +00:00
def powerset
inject(Set[Set[]]) do |ps, item|
ps.union ps.map {|e| e.union (Set.new [item])}
2013-04-10 23:57:08 -07:00
end
2013-10-27 22:24:23 +00:00
end
2013-04-10 23:57:08 -07:00
end
2013-10-27 22:24:23 +00:00
p [1,2,3,4].power_set
p %w(one two three).func_power_set
p Set[1,2,3].powerset