Wednesday, November 16, 2011

Learning Clojure

I've started my journey down clojure land. 4clojure and Project Euler are my first goals. Started with project Euler. Here are my first couple solutions. Critiques on clojure idioms, style, optimizations welcome.

#1. http://projecteuler.net/problem=1
Find the sum of all the multiples of 3 or 5 below 1000.

(reduce + (filter #(or (zero? (mod % 3)) (zero? (mod % 5))) (range 1 1000)))



#2. http://projecteuler.net/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.

My solution:

(defn fib [x]
(cond
(<= x 3) x
:else (+ (fib (- x 2)) (fib (- x 1)))))

(reduce + (filter even? (take-while #(< % 4000000) (map fib (iterate inc 1)))))

The unusual form of fibonacci is due to the requirement; the sequence starts with 1 and 2 instead of 0 and 1, so the first 3 terms are 1,2,3 so that is a teensy teensy point of optimization.

I actually started with a range, but that starts with 0 which isn't quite right, and if you have a starting point (say... 1), on a range, you need an ending point. And while I could have used an obviously too high end point (which is actually what I started with), it didn't feel right, so I dug around for the function I knew existed, but couldn't locate.... until I found iterate.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home