Jikku Jose
Jikku Jose

Reputation: 18804

Find every permutation of an array in Ruby, including permutations with sub arrays

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

Answers (1)

Jikku Jose
Jikku Jose

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

Related Questions