Calculating Combinations In Ruby From Erlang

Well, thanks to the many people (here and here) that provided their versions of an erlang way to calculate combinations, I've really begun to open my mind to how to think functionally.

To help me understand what is going on, I've converted the basic idea into a Ruby version of calculation combinations. This uses recursion like the erlang versions do.



class Array
def head_tail
[self.first, self.tail]
end

def tail
self[1,self.size-1]
end
end

def combos(list)
return [[]] if list.empty?
h, t = list.head_tail
t_combos = combos(t)
t_combos.inject([]) {|memo, obj| memo << [h] + obj} + t_combos
end

c = combos([1,2,3,4])
require 'pp'
pp c



As you can see, I added a bit of erlangism to the Array class, by adding a method to get the head and tail of an array.

Let's run through this.

On the first call to combos([1,2,3,4]) we jump over the first line (the exit in our recursion). We generate the head and tail, which in this case is 1 and [2,3,4] respectively. We immediately begin our recursion by saying, "Get me all the combinations for the tail, which is essentially everything but the head." Then, for each of those combinations, we append the head (again, here it's 1). Finally, we add all of the rest of the combinations and return the array of arrays.

Another way to explain it might be:


  1. H = Remove an element from the list.

  2. T = The rest of the list.

  3. C = Calculate the combinations of T (recursion happens here).

  4. C2 = For each combination in C, generate a new combination by appending H.

  5. return C2 + C

Popular posts from this blog

The 29 Healthiest Foods on the Planet

Lists and arrays in Dart

Converting Array to List in Scala