Skip to content

Instantly share code, notes, and snippets.

@temochka
Created August 7, 2014 13:44
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 temochka/0272e0e92559dafec736 to your computer and use it in GitHub Desktop.
Save temochka/0272e0e92559dafec736 to your computer and use it in GitHub Desktop.
A quick & dirty number to string packing implementation
(import '[java.util Random])
(def ^:const seed 42)
(def ^Random shuffler (Random. seed))
(def alphabet (->> "abcdefghijklmnopqrstuvwxyz0123456789"
(sort-by (fn [_] (.nextInt shuffler)))
vec))
(def N (count alphabet))
(defn pack-number
([n] (pack-number n ""))
([n buf]
(let [n-rem (rem n N)
n-quot (quot n N)
buf (str buf (nth alphabet n-rem))]
(if (zero? n-quot)
buf
(recur n-quot buf)))))
(defn unpack-number
[buf]
(reduce #(+ %2 (* N %1)) 0 (map #(.indexOf alphabet %) (reverse buf))))
(pack-number 42)
(unpack-number "lc")
(assert (= (unpack-number (pack-number 42)) 42))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment