Aug
17
In my attempt to learn Ruby out in the open, here’s my solution for Project Euler Problem 49.
Here, you will find that I took advantage of Ruby’s Prime Class and the Array.permutations method yet again. I think the solution is straight-forward and easy to read — unlike the problem description which I didn’t find very clear at all. After wrestling with the problem for a while I decided to see if 3330 was significant. Apparently, it was.
As always, any feedback is welcome.
# Euler 49
# http://projecteuler.net/index.php?section=problems&id=49
# The arithmetic sequence, 1487, 4817, 8147, in which each
# of the terms increases by 3330, is unusual in two ways:
# (i) each of the three terms are prime, and, (ii) each of
# the 4-digit numbers are permutations of one another.
#
# There are no arithmetic sequences made up of three 1-,
# 2-, or 3-digit primes, exhibiting this property, but
# there is one other 4-digit increasing sequence.
#
# What 12-digit number do you form by concatenating the
# three terms in this sequence?
timer_start = Time.now
require 'mathn'
answer = ""
Prime.each do |a|
next if a == 1487
b, c = a + 3330, a + 6660
next if !b.prime? || !c.prime?
perms = a.to_s.chars.to_a.permutation(4).map{|p| p.join.to_i}
next if !perms.include?(b) || !perms.include?(c)
answer = a.to_s + b.to_s + c.to_s
break
end
puts answer
puts "Elapsed Time: #{(Time.now - timer_start)*1000} milliseconds"