tags:

views:

109

answers:

3

What would be the correct translation of the following Python method to Ruby?

def uniqueCombinations(self, items, n):
    """ 
    items: list of elements
    n: number in a group
    """
    if n == 0:
        yield []
    else:
        for i in range(len(items)-n+1):
            for cc in uniqueCombinations(items[i+1:],n-1):
                yield [items[i]]+cc

What I want to do is call

uniqueCombinations(['01', '02', '03'], 2)

and get

[['01', '02'], ['01', '03'], ['02', '03']]

This is what I have so far.

def uniq_c(items, n)
  if n == 0
    yield []
  else
    puts items.inspect
    range_max = items.length-n+1
    for i in (0...range_max)
      u = uniq_c(items[(i+1)..-1], n-1) { |x| x }
      u.each do |cc|
        yield [items[i]] + cc
      end
    end
  end
end

but I get this:

in `+': can't convert Fixnum into Array (TypeError)
+2  A: 
yield [items[i]] + cc

You are attempting to concatenate an array ([items[i]]) and a Fixnum (cc). You could instead turn both into an array or use the << method to push cc onto [items[i]].

yield [items[i]] << cc
Ed Swangren
Eh, you type faster than me. Voting this up.
Toms Mikoss
Thank you. I tried '<<' but the end result of the function gives me range (0..2). This baffles me.
Jeffery H.
A: 

First, it'd be better to do this as a method of the Array class.

Second, you can fix your error by changing [items[i]] + cc to [items[i]] + [cc].

Third, here's a different implementation I had lying around, see what you think. It creates an array of permutations represented by indices, then maps each index to its value.

class Array
  def combinations(n)
    perms = []
    a = (0...n).to_a
    while perms.push a.dup
      break if a.increment!(a.length - 1, self.length-1).nil?
    end
    perms.map {|p| p.map {|i| self[i]} }
  end
  def increment!(i, max)
    self[i] += 1
    while self[i] > max
      return nil if i <= 0
      return nil if self.increment!(i - 1, max).nil?
      self[i] = self[i - 1] + 1
    end
    self.dup
  end
end

[1,2,3].combinations 3 # => [[1, 2, 3]]
[1,2,3].combinations 2 # => [[1, 2], [1, 3], [2, 3]]
[1,2,3].combinations 1 # => [[1], [2], [3]]
[:foo,:bar,:baz,:quux,:wibble].combinations 3
# => [[:foo, :bar, :baz],
#     [:foo, :bar, :quux],
#     [:foo, :bar, :wibble],
#     [:foo, :baz, :quux],
#     [:foo, :baz, :wibble],
#     [:foo, :quux, :wibble],
#     [:bar, :baz, :quux],
#     [:bar, :baz, :wibble],
#     [:bar, :quux, :wibble],
#     [:baz, :quux, :wibble]]
jtbandes
You method works like a charm. Thank you.
Jeffery H.
Glad to hear it! It looks like it may be less efficient than yours, but easier to understand. Or maybe I'm just sleep-deprived. In any case, I think trying to use `yield` the same way in Ruby doesn't work.
jtbandes
+2  A: 

From Ruby 1.8.7 onwards, class Array provides a method to return combinations:

irb> ['01', '02', '03'].combination(2).to_a => [["01", "02"], ["01", "03"], ["02", "03"]]

William
Thank you very much for your input.
Jeffery H.