Skip to content

Instantly share code, notes, and snippets.

@igrishaev
Created April 18, 2018 08:27
Show Gist options
  • Save igrishaev/d2f1ecdae82da82aa1658a9100df6dba to your computer and use it in GitHub Desktop.
Save igrishaev/d2f1ecdae82da82aa1658a9100df6dba to your computer and use it in GitHub Desktop.
rebase
(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