Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Convert numbers to Excel headers
(let [chr (zipmap (range) "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
encode (fn [n acc]
(if (< n 26)
(cons n acc)
(recur (dec (quot n 26)) (cons (rem n 26) acc))))]
(defn col-str
"Convert numbers to Excel headers."
(apply str (map chr (encode n '())))))
;;(col-str 0)
;;=> "A"
;;(col-str 25)
;;=> "Z"
;;(col-str 26)
;;=> "AA"
;;(col-str 701)
;;=> "ZZ"
;;(col-str 702)
;;=> "AAA"
(def chrs (zipmap (range) "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))

(defn foo [n]
  (let [base 26 q (quot n base) r (rem n base) c (chrs r)]
    (if (zero? q) [c] (cons c (lazy-seq (foo (dec q)))))))

(defn str-num [n]
  (aply str (reverse (foo n))))

;; (map str-num [0 25 26 701 702])
;; => ("A" "Z" "AA" "ZZ" "AAA")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment