I’m trying to write an Array extension that does something like this:
I call it like this:
%w[eggs bacon sausage].with_every_possibiity_of_multiples(2)
And it gives me these:
[
%w[eggs, bacon, sausage],
%w[eggs, eggs, bacon, sausage],
%w[eggs, bacon, bacon, sausage],
%w[eggs, bacon, sausage, sausage],
%w[eggs, eggs, bacon, bacon, sausage],
%w[eggs, eggs, bacon, bacon, sausage, sausage],
]
Hopefully it’s clear what’s going on here. If I had called it with an argument of 3 instead of 2, I’d have gotten an array of 9 elements, one of them being %w[eggs, eggs, eggs, bacon, sausage].
I’m struggling to come up with how to write this. Any suggestions?
As @sawa points out, you probably have your results mixed up. I’m guessing passing 2 gets you 8 elements, not 6, and passing 3 gets you 27, not 9.
You can make good use of
Array#repeated_combinationto generate the number of times you want to repeat each element:Note that
repeated_permutationis new to Ruby 1.9.2. You canrequire 'backports'in earlier versions, or use an uglier version usingproduct: