Permutations Using a Ruby Array Method
ruby
April 3, 2023
Ever needed to perform some operation on all the different permutations in a given array? Me neither, but it can totally be done! Just grab the Array.permutation
method. Below, the Enumerable
returned by the method is iterated and each permutation is shoveled into an array.
An impractical example using triangles
Because of geometry and stuff, it’s known that each side of a triangle cannot be shorter in length than the sum of the lengths of its other two sides. Here, a block is used to check permutations for a given triangle and verify this.
I think the above is a bit nicer looking than something like this:
Pretty neat, but watch out
permutation
is handy in this example, but as elements are added to an array, its number of permutations grows factorially, or, by a lotally. An array with 10 unique elements in it is going to have 3,628,800 permutations.