Project Euler 002 – IronRuby

9 02 2011

Problem 2

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Solution

#By considering the terms in the Fibonacci sequence

#whose values do not exceed four million, find the

#sum of the even valued terms.

 

 

# this uses the same technique

# as the c# implementation

# I find this initialization

# syntax interesting

answer = 0

fib0, fib1, fib2 = 1, 1, 2;

while fib2 < 4000000

   

    answer += fib2

    #odd + even = odd

    fib0 = fib1 + fib2;

    #odd + even = odd

    fib1 = fib0 + fib2;

    #odd + odd = even

    fib2 = fib0 + fib1;

end

 

puts answer

 

Discussion

This is obviously a port of the C# solution.  The one piece I find interesting is

fib0, fib1, fib2 = 1,1,2;

Seems to be equivalent to

fib0 = 1, fib1 = 1, fib2 = 2;

For cutting and pasting large lists, the first option might be more attractive?  Why not use an array in that case?  I suppose I’ll learn more as I continue down the path.

If you have questions, leave a comment or please find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).

Advertisements




Project Euler 001 – IronRuby

2 02 2011

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.

Solution

# Add all the natural numbers below one

# thousand that are multiples of 3 or 5.

 

# this is interesting

# I wasn’t sure how to create the arrays

# with a step so I just rejected the ones

# I didn’t want.  For small numbers this

# should work fine

threes = (01000).reject { |i| i % 3 != 0 }

fives = (01000).reject { |i| i % 5 != 0 }

fifteens = (01000).reject { |i| i % 15 != 0 }

 

answer = 0

threes.each { |i| answer += i }

fives.each { |i| answer += i }

fifteens.each { |i| answer -= i }

puts answer

 

Discussion

Remember, Ruby is brand new to me.  I wasn’t really sure how to create an array with a step so I used the “reject” feature.  It felt pretty natural.

If you have questions, leave a comment or find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).