Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ummels/1647608 to your computer and use it in GitHub Desktop.
Save ummels/1647608 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))]
(encode (cond
(and (even? l) (>= h t)) (concat H Hr)
(and (odd? l) (>= h t)) (concat H [p] Hr)
(even? l) (concat H1 (reverse H1))
(and (odd? l) (< p 9)) (concat H [(inc p)] Hr)
:else (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