Get all combinations permutations of an array

suggest change

permutation, called with a block, yields every ordered sequence. Without a block it returns an Enumerator. Call to_a for an array.

Example Result
[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)

combination yields sequences where order does not matter. [1,2,3] and [3,2,1] are the same combination.

Example Result
[1,2,3].combination(1) #<Enumerator: [1, 2, 3]:combination(1)>
[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)

Without a block, combination also returns an enumerator.

repeated_combination and repeated_permutation allow the same element more than once, so [1,1] and [3,3,3] can appear. Those are not valid ordinary combinations or permutations.

Example Count
[1,2,3].combination(3).to_a.length 1
[1,2,3].repeated_combination(3).to_a.length 10
[1,2,3,4,5].combination(5).to_a.length 1
[1,2,3].repeated_combination(5).to_a.length 21

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents