Created
August 7, 2014 13:44
-
-
Save temochka/0272e0e92559dafec736 to your computer and use it in GitHub Desktop.
A quick & dirty number to string packing implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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