Aug
14
In my attempt to learn Ruby out in the open, here’s my solution for Project Euler Problem 41.
I started off by iterating through all prime numbers up to the max value but it took way too long for the routine to complete. Instead I ended up gathering all possible pandigitals and I iterated through each descending. It takes a little while to collect the pandigitals, but the rest of the routine is fast. As for Ruby, I don’t think we’ve played with permutations since the early problems and I feel like I haven’t used selectfor quite some time. It’s good to see it back in a solution.
As always, any feedback is welcome.
# Euler 41
# http://projecteuler.net/index.php?section=problems&id=41
# We shall say that an n-digit number is pandigital if it
# makes use of all the digits 1 to n exactly once. For
# example, 2143 is a 4-digit pandigital and is also prime.
#
# What is the largest n-digit pandigital prime that exists?
timer_start = Time.now
require 'mathn'
# Get every pandigital, 1 - 987654321
def pandigitals()
base, result = [], []
# We build the list like so...
#[1].permutation(1).map { |x| x.join.to_i } + \
#[1,2].permutation(2).map { |x| x.join.to_i } + \
#[1,2,3].permutation(3).map { |x| x.join.to_i } + \
# ...
1.upto(9).each do |n|
base << n
result += base.permutation(n).map { |x| x.join.to_i }
end
# Start with the max values
result.sort.reverse
end
puts pandigitals.select { |n| n.prime? }.take(1)
puts "Elapsed Time: #{(Time.now - timer_start)*1000} milliseconds"