I am trying to get a powerset (all subsets) of a set.
I couldn’t find a code in Ruby, but I found a code in Python.
I’m trying to convert it to Ruby but it’s not done easily.
def powset(seq):
if seq:
head, tail = seq[:1], seq[1:]
for smaller in powset(tail):
yield smaller
yield head + smaller
else:
yield []
Can somebody translate the Python code into Ruby?
(I have difficulty in understanding the yield part)
Actually I want to add a method to Set class.
How can I change the function into a method which won’t take any
parameter.
(Can a method be recursive if it doesn’t take a parameter?
Maybe not.
Do I need a helper private method?)
example:
s = Set[1,2,3]
ps = s.powerset #returns a set of powerset of s
Non-recursive version:
I’m sure you can translate this for sets…
class Array
def powset
ret = []
0.upto(2**size - 1) do |n|
ret << []
0.upto(size - 1) do |i|
ret.last << self[i] if (n & (1 << i)) != 0
end
end
ret
end
end
p [].powset
p [1].powset
p [1,2].powset
p [1,2,3].powset
[[]]
[[], [1]]
[[], [1], [2], [1, 2]]
[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
class Set
def powerset
result = Set.new
for element_map in 0…(1 << self.length) do
subset = Set.new
each_with_index do |element, index|
subset.add(element) if element_map[index] == 1
end
result.add(subset)
end
return result
end
end
s = Set[1,2,3]
ps = s.powerset #returns a set of powerset of s
p ps