Aug
14
In my attempt to learn Ruby out in the open, here’s my solution for Project Euler Problem 40.
There’s nothing all that exciting going on here. I’m sure you noticed in past solutions that one can easily map a string to a range of characters. Perhaps the fact that Ruby can build a range of string values for you. In the solution below, I build a range from “1″ to “1000000″. Pretty neat, if you ask me.
As always, any feedback is welcome.
# Euler 40
# http://projecteuler.net/index.php?section=problems&id=40
# An irrational decimal fraction is created by
# concatenating the positive integers:
# 0.123456789101112131415161718192021...
#
# It can be seen that the 12th digit of the fractional
# part is 1.
#
# If dn represents the nth digit of the fractional part,
# find the value of the following expression.
#
# d1 x d10 x d100 x d1000 x d10000 x d100000 x d1000000
timer_start = Time.now
# Build a long string of the numbers 1 - 1 million
# and convert to char array
nums = ("1".."1000000").to_a.join.chars.to_a
i, answer = 1, 1
while i <= 1000000
# Get the product of all numbers which fall in a
# power of 10 position
answer *= nums[i-1].to_i
i*=10
end
puts answer
puts "Elapsed Time: #{(Time.now - timer_start)*1000} milliseconds"