Question

Say, I have an array:

a = [1,2]

and

n = 3

I want output like this:

[[1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 2, 2], [2, 1, 1], [2, 1, 2], [2, 2, 1], [2, 2, 2]]

This are all possible combinations of length n of elements from array a.

Most importantly I'm using ruby 1.8.7

Was it helpful?

Solution 2

Please test in detail before use:

x = [1,0]
n = 3

def perm(a, n)
  l = a.length
  (l**n).times do |i|
    entry = []
    o = i
    n.times do
      v = o % l
      entry << a[v]
      o /= l
    end
    yield(i, entry)
  end
end

perm(x, n) do |i, entry|
  puts "#{i} #{entry.reverse.inspect}"
end

prints

0 [0, 0, 0]
1 [0, 0, 1]
2 [0, 1, 0]
3 [0, 1, 1]
4 [1, 0, 0]
5 [1, 0, 1]
6 [1, 1, 0]
7 [1, 1, 1]

OTHER TIPS

a.repeated_combination(n).to_a
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top