Ruby Language Arrays Get all combinations / permutations of an array


Example

The permutation method, when called with a block yields a two dimensional array consisting of all ordered sequences of a collection of numbers.

If this method is called without a block, it will return an enumerator. To convert to an array, call the to_a method.

ExampleResult
[1,2,3].permutation#<Enumerator: [1,2,3]:permutation
[1,2,3].permutation.to_a[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
[1,2,3].permutation(2).to_a[[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]
[1,2,3].permutation(4).to_a[] -> No permutations of length 4

The combination method on the other hand, when called with a block yields a two-dimensional array consisting of all sequences of a collection of numbers. Unlike permutation, order is disregarded in combinations. For example, [1,2,3] is the same as [3,2,1]

ExampleResult
[1,2,3].combination(1)#<Enumerator: [1,2,3]:combination
[1,2,3].combination(1).to_a[[1],[2],[3]]
[1,2,3].combination(3).to_a[[1,2,3]]
[1,2,3].combination(4).to_a[] -> No combinations of length 4

Calling the combination method by itself will result in an enumerator. To get an array, call the to_a method.

The repeated_combination and repeated_permutation methods are similar, except the same element can be repeated multiple times.

For example the sequences [1,1], [1,3,3,1], [3,3,3] would not be valid in regular combinations and permutations.

Example# Combos
[1,2,3].combination(3).to_a.length1
[1,2,3].repeated_combination(3).to_a.length6
[1,2,3,4,5].combination(5).to_a.length1
[1,2,3].repeated_combination(5).to_a.length126