-1

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

rony36
  • 3,277
  • 1
  • 30
  • 42
  • please explain why these down votes. – rony36 Jul 24 '13 at 06:58
  • Please always comment when down voting a question. – reto Jul 24 '13 at 15:57
  • @reto I'm really disappointed about this down-vote. :( . I don't know why all these people who have thousands of reputations do this stuff. I'm really gonna give up to asking question here in this forum. :(. I'm a learner but they don't understand but hurry to get more and more reputations. – rony36 Jul 24 '13 at 16:41
  • it's a bad habit of StackOverflow users to sometimes downvote something that's already down-voted. They use it as an 'I agree button', although the question by itself, compared to other case, isn't that bad. I personally find it rude to downvote without at least taking the time to comment, but others might have a different opinion. – reto Jul 24 '13 at 19:15
  • 1
    So: Don't worry too much and don't take it personally... I hope this will get reopened again. – reto Jul 24 '13 at 19:16

2 Answers2

5
a.repeated_combination(n).to_a
sawa
  • 165,429
  • 45
  • 277
  • 381
  • 2
    @rony36 the [backports gem](https://github.com/marcandre/backports) provides an implementation of [`repeated_combination`](https://github.com/marcandre/backports/blob/master/lib/backports/1.9.2/array/repeated_combination.rb) – Stefan Jul 24 '13 at 07:41
1

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]
reto
  • 16,189
  • 7
  • 53
  • 67