2

I have array

a = ["w1", "w2", "w3"]

How can I generate a new array with every combination of values? I need the output to look like this:

["w1", "w2", "w3", "w1 w1", "w1 w2", "w1 w3", "w2 w1", "w2 w2", "w2 w3", "w3 w1", "w3 w2", "w3 w3", "w1 w1 w1", "w1 w1 w2", "w1 w1 w3", "w1 w2 w1", "w1 w2 w2", "w1 w2 w3", "w2 w1 w1", "w2 w1 w2", "w2 w1 w2", "w2 w1 w3", "w2 w2 w1", "w2 w2 w2", "w2 w2 w3", "w2 w3 w1", "w2 w3 w2", "w2 w3 w3", "w3 w1 w1", "w3 w1 w2", "w3 w1 w3", "w3 w2 w1", "w3 w2 w2", "w3 w2 w3", "w3 w3 w1", "w3 w3 w2", "w3 w3 w2"]

Try code from Generate array of all combinations of an existing array

Result incorrect

"w1", "w2", "w3", "w1 w2", "w1 w3", "w2 w3", "w1 w2 w3"]
Community
  • 1
  • 1
Max Bublikoff
  • 1,234
  • 1
  • 12
  • 17

1 Answers1

5

Here is one way to do it, however this result has "w3 w3 w3" and you desired result does not, but I do not see the logic to include "w3 w3" and "w1 w1 w1" but not "w3 w3 w3", so I assume you just missed to add that.

What you are looking for is not the combinations, but the permutations (with repetation):

a = ["w1", "w2", "w3"]

result = (1..a.size).flat_map do |size|
  a.repeated_permutation(size).map { |perm| perm.join(' ') }
end
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
hirolau
  • 13,451
  • 8
  • 35
  • 47
  • I don't think it's task of permutation but combination (with repetition). – David Unric Jan 21 '14 at 15:10
  • In the original question the provided desired output include many items that have the same items, but they have different order. The list contains, for example both "w2 w3" and "w3 w2". Thus repeated combinations is not the way to go, as it would only add one of them. – hirolau Jan 21 '14 at 15:16
  • True. I've slided the expected output and it has variations with different order. Appologies. – David Unric Jan 21 '14 at 15:24