Generate All Permutations Of An Array In Ruby
Produce every possible ordering of array elements using Array#permutation.
Description
Array#permutation generates all permutations of an array’s elements. Called without an argument it generates full-length permutations; called with n it generates permutations of length n. It returns an Enumerator — chain .to_a to materialize or use a block to process one permutation at a time without holding all in memory.
Sample input:
[1, 2, 3]
Sample Output:
[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Answer
arr = [1, 2, 3]
# All full-length permutations
arr.permutation.to_a
# => [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
# Permutations of length 2
arr.permutation(2).to_a
# => [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]
# Process without holding all in memory
arr.permutation { |p| puts p.inspect }
# Count without materializing
arr.permutation.count # => 6 (3!)
arr.permutation(2).count # => 6 (3 * 2)
# Combinations (order doesn't matter) — use combination instead
arr.combination(2).to_a
# => [[1,2],[1,3],[2,3]]
Check viewARU - Brand Newsletter!
Newsletter to DEVs by DEVs - boost your Personal Brand & career! 🚀