Reputation: 18804
Consider an array: [4, 6, 9]
Require all the permutations: (one, two and three digit ones)
[[9],
[6],
[4],
[9, 6],
[9, 4],
[6, 9],
[6, 4],
[4, 9],
[4, 6],
[9, 6, 4],
[9, 4, 6],
[6, 9, 4],
[6, 4, 9],
[4, 9, 6],
[4, 6, 9]]
Upvotes: 1
Views: 168
Reputation: 18804
Recording this question and my own finding as I didn't find anything simple enough while searching. Perhaps this may help someone:
a = [4, 6, 9]
(1..a.length).flat_map { |n| a.permutation(n).to_a }
And for every combination, just switch the method, like so:
a = [4, 6, 9]
(1..a.length).flat_map { |n| a.combination(n).to_a }
Upvotes: 3