Skip to content

Instantly share code, notes, and snippets.

@ghoseb
Created January 6, 2012 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghoseb/1569742 to your computer and use it in GitHub Desktop.
Save ghoseb/1569742 to your computer and use it in GitHub Desktop.
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."
[n]
(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"
@kumarshantanu
Copy link

(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