Reputation: 4488
I was working on implementing a recursive powerset algorithm in Ruby and I came across this Stack Overflow post.
def powerset(set)
return [set] if set.empty?
p = set.pop
subset = powerset(set)
subset | subset.map { |x| x | [p] }
end
powerset(['a'], ['b'], ['c']) ---> [[], ["a"], ["b"], ["a", "b"], ["c"], ["a", "c"], ["b", "c"], ["a", "b", "c"]]
Basically, I'm at a loss in understanding the last line. I understand that this is the 'bitwise or' operator, and I generally understand what this does, but I'm having a lot of trouble comprehending how it works in this last line works here.
Can someone show me what the equivalent would be in easier to read Ruby?
Upvotes: 2
Views: 390
Reputation: 23955
Here's an equivalent in easier to read words :)
If the set is empty:
return a list with one empty set
Remove an element from the set and call it "p"
Call "subset" the powerset of the new set (that excludes p)
Return the union of this new powerset and another
version of it, where p is added to each of its sets
Upvotes: 1