Created
April 18, 2018 08:27
-
-
Save igrishaev/d2f1ecdae82da82aa1658a9100df6dba to your computer and use it in GitHub Desktop.
rebase
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
(ns qrfd.hash) | |
(def charset "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") | |
(def num->char | |
(into {} (map-indexed vector charset))) | |
(def char->num | |
(into {} (map-indexed (comp vec reverse vector) charset))) | |
(def base (count charset)) | |
(def divmod (juxt quot rem)) | |
(defn exp [x n] | |
(loop [acc 1 n n] | |
(if (zero? n) acc | |
(recur (* x acc) (dec n))))) | |
(defn encode [n] | |
(loop [n n a ""] | |
(let [[div mod] (divmod n base)] | |
(if (zero? div) | |
(str (get num->char mod) a) | |
(recur div (str (get num->char mod) a)))))) | |
(defn decode-pair [idx chr] | |
(* (get char->num chr) | |
(exp base idx))) | |
(def sum (partial reduce +)) | |
(defn decode [s] | |
(sum (map-indexed decode-pair (reverse s)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment