Reputation: 1234
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"]
Upvotes: 2
Views: 866
Reputation: 13901
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
Upvotes: 5