More popular than stellar consumer credit you cash advance cash advance your car get your mortgage.


Powerset in Ruby

Now for a real post in a very cool language that is on the rise. Currently my favorite language to write, Ruby.

Simple PowerSet implementation, pretty straight-forward.

class Array
  def powerSet!
    return [[]] if empty?()
    f = shift()
    rec = powerSet!
    return rec + rec.collect {|i| [f] + i }
  end

  def powerSet
    return clone().powerSet!
  end
end

Note, I added this directly to the Array class. In ruby, classes are left open, so you can add to them later. It is a very dynamic language, and there are hooks for just about everything, so you could have some behavior run when a method is added to your class. Now that Array has a new method, you can just call

[1,2,3].powerSet

Now let’s write it using inject, because inject is awesome. (inject is known as reduce in python, and they are removing it from the next version. It’s a shame they are removing it, but it makes sense because python doesn’t sweet sweet blocks like ruby.)

array = [1,2,3]
array.inject([[]]) { |acc, you|
  ret = []
  acc.each { |i|
    ret << i
    ret << i + [you]
 }
  ret
}

The best part about inject is that once you get your head around it, it is pretty clear and also that this expression can be smashed to 50 chars if that is what gets you going.

[1,2,3].inject([[]]){|c,y|r=[];c.each{|i|r<<i;r<<i+[y]};r}

One Response to “Powerset in Ruby”

  1. Bill Mill says:

    Python is not removing reduce, this misinformation is everywhere! It’s just moving to the functools module.