Implementing a permutation algorithm

In this section, 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 this: 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 three 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 created an array of numbers from 0 to 9 and called the method permutation on it.

From there, we converted the permutation object into an array by calling the to_a method on it.

Next, we called the 1,000th variable in the array. If you remember, an array index starts at 0, so the 1,000th variable has an index value of 999,999. Instead of a comma, I used the _ symbol for better readability.

Finally, we called the join method to convert the array into a string.

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

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

Its output will be as follows:

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

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

Now, if you execute the file, the output will be 2783915460, and that's the right answer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.94.153