Sunday, August 31, 2014

Euler Project: Problem 4 in Clojure

This is my solution in Clojure to the fourth problem from Euler project:

(reverse (range 100 1000)) ; (999 998 997 996 995 994 ...)
(defn palindrome? [number]
(let [num-str (str number)]
(= num-str (apply str (reverse num-str)))))
(palindrome? 9009) ; true
(palindrome? 9008) ; false
(apply
max
(filter
palindrome?
(let [numbers (reverse (range 10 100))]
(for [x1 numbers x2 numbers]
(* x1 x2))))) ; 9009
(defn products [lower higher]
(let [numbers (reverse (range lower (+ higher 1)))]
(for [x1 numbers x2 numbers]
(* x1 x2))))
(defn largest-palindrome-product [lower higher]
(apply max (filter palindrome? (products lower higher))))
(largest-palindrome-product 10 99) ; 9009
(largest-palindrome-product 100 999) ; 906609
view raw euler-4.clj hosted with ❤ by GitHub

It was nice to practise with for.

No comments:

Post a Comment