How to Implement a Permutation Algorithm in Ruby
In this lesson, we are going to build a powerful algorithm that is going to use many important functionalities of Ruby. The problem that we are going to solve is Project Euler problem 24 that asks: What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this guide we are going to build an algorithm that is going to leverage a number of powerful Ruby methods. The math problem that we are going to solve is a problem that asks:

What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?

This may seem like an intimidating problem, but thankfully it can be solved quickly with Ruby thanks to some functional programming methods.

So what is a lexicographic permutation? It's the number of permutations you can make with a given set of numbers. For example, there are six different numbers you can create with the digits 0, 1 and 2.

Now that we know how to build a permutation for 3 numbers, we have to find the millionth permutation of the digits 0 to 9.

In Ruby, we can do this with a single line of code.

p [0,1,2,3,4,5,6,7,8,9].permutation.to_a[999_999].join

In this code, we are creating an array of numbers from 0 to 9 and calling a method called permutation on it.

From there we are converting the permutation object to an array by calling the to_a method on it.

Next we're calling the 1000th variable in the array. If you remember, an array index starts at 0, so the 1000th variable has an index value of 999,999. Instead of a comma, I'm using _ for better readability.

Finally, we are calling the join method to convert the array to a string.

If this still seems a bit fuzzy, let's see how the permutation method works in the irb console. If you execute the code:

arr = [1, 2, 3]
arr.permutation { |i| p i }

The output is:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]

So, the permutation method takes care building all of the combinations for us and even gives us the lexicographic representation.

Now, if you execute our file, the output is 2783915460, and that's the right answer!