Lazy Evaluation

Marina's coding (mis)adventures
Project Euler in Ruby

I'm taking Bill Wagner up on his Project Euler challenge, but in Ruby.  I've secretly wanted to learn Ruby for a long time, and this looks like the perfect chance.  So if my code makes your eyes bleed, it's cause I'm a total n00b.  Without further ado (because the excitement was becoming unbearable... I agree, Ruby is sexy!), here's my code that prints the answer to Problem 1:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.  Find the sum of all the multiples of 3 or 5 below 1000.

answer = (0..999).select { |a| a%3 ==0 || a%5==0 }
puts answer.inject { |sum, n| sum+n }

 

I love the built-in ruby function inject, which is like foldl in some functional languages.  (See a cute demo here.)   Overall the code is very similar to Bill's C# version.  I wonder if that'll still be the case as we get to the more complex problems.

 [4/08/08: correction of a typo in the code]

Published Sunday, April 06, 2008 1:31 PM by mfedner

Filed under: ,

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required)