Simon Kröger
12/24/2005 12:56:00 AM
Sorry, i couldn't resist:
class Array
def powset
(0...(2**size)).map do |n|
(0...size).reject{|i|n[i].zero?}.map{|i|at(i)}
end
end
end
cheers
Simon
Stefan Walk wrote:
> 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]]
>
>