public
anonymous / gist:6890101
Created

  • Download Gist
gistfile1.clj
Clojure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
(defn palindrome [n]
(let [ to-digits (fn [k] (into [] (map #(mod (quot k %) 10)
(take-while #(< 0 (quot k %)) (iterate #(* 10 %) 1) ))))
to-number (fn [k] (apply + (map * k (iterate #(* 10 %) 1))))
left-digits #(subvec % (/ (count % ) 2))
even-digits? #(even? (count %))
mirror (fn [[num dig]]
(let [ digits (to-digits num)]
(if (= :even dig) (concat (reverse digits) digits)
(concat (reverse (drop 1 digits)) digits))))
init #(let [ld (left-digits %)]
(vector (to-number ld)
(if (even-digits? %) :even :odd)
(long (Math/pow 10 (count ld)))))
nextp (fn [[num even goal]]
(let [m (inc num)]
(if (= m goal)
(if (= even :even)
[goal :odd (* 10 goal)]
[(/ goal 10) :even goal])
[m even goal] )))
i (init (to-digits n))
palindromes (iterate nextp i) ]
(filter (partial <= n ) (map (comp to-number mirror) palindromes))))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.