Sunday, September 15, 2013

Problem 14 redo - Clojure

Given the fact that I can mostly only find time to solve Euler problems on weekends, I thought it would be a shame to have only done two problems this weekend, so I squeezed in another. Problem 43 looks a little bit daunting to jump into with a hard-to-use language, so I decided to free up a nice language from a while ago that I may or may not use directly for problem 43, but which will certainly be useful to have free - C (or C++, I have been considering them "the same" for my purposes, but now that I am expanding this challenge out so far..maybe I will allow the two to be used separately).

Anyway, I used C back in the initial 24 hour hackathon stage of this challenge for a rather easy problem involving collatz sequences - I used it during the "home stretch" when I had about as many language I knew left as problems left to solve. I decided to noq resolve this problem in clojure. Clojure turns out to be a pretty nice functional language...for whatever reason I had difficulties starting with it before, but now that I know that it is not too different from most lisps/schemes, I may eventually reclaim and reuse it. But anyway, here is my solution to problem 14 in Clojure (runs in about 15s...but Clojure runs in the JVM and does not seem to be fast by any stretch of the imagination).
(defn collatz-count [n c]
    (if (= 1 n) (+ c 1)
        (if (= 0 (mod n 2)) (collatz-count (/ n 2) (+ c 1))
            (collatz-count (+ (* 3 n) 1) (+ c 1)))))

(defn mmax [x y] (if (< (first x) (first y)) y x))

(println (second (reduce mmax (map #(list (collatz-count % 0) %) (range 1 1000000))))) 

No comments:

Post a Comment