Permutations Using a Ruby Array Method

ruby

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.

arr = [1, 2, 3]
permutations = arr.permutation.each_with_object([]) { |p, a| a << p }

# =>
#
# [
#   [1, 2, 3],
#   [1, 3, 2],
#   [2, 1, 3],
#   [2, 3, 1],
#   [3, 1, 2],
#   [3, 2, 1]
# ]

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.

class Triangle
  def initialize(sides)
    @sides = sides
  end

  def valid?
    @sides.permutation.all? { |a, b, c| a + b >= c }
  end
end

triangle_a = Triangle.new([1, 2, 3])
triangle_b = Triangle.new([1, 1, 3])

triangle_a.valid? # => true
triangle_b.valid? # => false: 1 + 1 is NOT gte 3

I think the above is a bit nicer looking than something like this:

class Triangle
# ...
  def valid?
    @side_a + @side_b >= @side_c && @side_a + @side_c >= @side_b && @side_b + @side_c >= @side_a
  end
end

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.

More Posts