Created
May 30, 2011 18:15
-
-
Save johana-star/999245 to your computer and use it in GitHub Desktop.
Euler Project Problem #034
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Solution to Project Euler's thirty-fourth problem | |
# http://projecteuler.net/index.php?section=problems&id=34 | |
# Find the sum of all numbers which are equal to the sum of the factorial of their digits. | |
def fact(n) | |
(1..n).reduce(1, :*) | |
end | |
def seperate_digits(numbers) | |
array = [] | |
numbers.each_with_index do |n, i| | |
array[i] = [] | |
until n < 10 do | |
array[i].unshift (n % 10) | |
n = n / 10 | |
end | |
array[i].unshift n | |
end | |
return array | |
end | |
def sum_digits_as_facts(array_of_arrays) | |
facts = (0..9).to_a | |
facts.each_with_index {|n, i| facts[i] = fact(i) } | |
array_of_sums = [] | |
array_of_arrays.each do |array| | |
sum = 0 | |
array.each do |i| | |
sum = facts[i] + sum | |
end | |
array_of_sums.push sum | |
end | |
return array_of_sums | |
end | |
def compare_array_to_array(first, second) | |
sum = -3 # Set to -1 to negate the false positives on 1 and 2. | |
first.each_with_index do |s, i| | |
if s == second[i] then | |
p "#{s} is #{second[i]}" | |
sum += s | |
end | |
end | |
return sum | |
end | |
range = (1..199999)to_a | |
digits = seperate_digits(range) | |
array_of_sums = sum_digits_as_facts(digits) | |
sum = compare_array_to_array(array_of_sums, range) | |
p sum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment