Skip to content

Instantly share code, notes, and snippets.

Created January 20, 2012 10:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/1646667 to your computer and use it in GitHub Desktop.
Save anonymous/1646667 to your computer and use it in GitHub Desktop.
;; ummels's solution to Palindromic Numbers
;; https://4clojure.com/problem/150
(fn [n]
(letfn [(decode [n] (if (< n 10) [n] (conj (decode (quot n 10)) (rem n 10))))
(encode [x] (reduce #(+ (* % 10) %2) 0 x))
(next-pal [n]
(let [N (decode n)
l (count N)
d (quot l 2)
H (take d N)
H1 (decode (inc (encode H)))
Hr (reverse H)
h (encode Hr)
p (nth N d)
t (encode (take-last d N))]
(cond
(and (even? l) (>= h t)) (encode (concat H Hr))
(and (odd? l) (>= h t)) (encode (concat H [p] Hr))
(even? l) (encode (concat H1 (reverse H1)))
(and (odd? l) (< p 9)) (encode (concat H [(inc p)] Hr))
:else (encode (concat H1 [0] (reverse H1))))))]
(iterate (comp next-pal inc) (next-pal n))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment