Skip to content

Instantly share code, notes, and snippets.

@whamtet
Last active October 26, 2022 10:04
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 whamtet/ee8d0cbb9bc33336c16c10778905b961 to your computer and use it in GitHub Desktop.
Save whamtet/ee8d0cbb9bc33336c16c10778905b961 to your computer and use it in GitHub Desktop.
(ns test.encoder
(:require
[clojure.string :as string]))
(def alphabet "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
(def alphabet? (set alphabet))
(def a->i (zipmap alphabet (range 1 27)))
(def i->a (zipmap (range 1 27) alphabet))
(defn- c>> [previous curr]
(let [shift (if previous (a->i previous) 0)]
(-> curr a->i (+ shift) (mod 26) i->a)))
(defn- c<< [previous curr]
(let [shift (if previous (a->i previous) 0)]
(-> curr a->i (- shift) (mod 26) i->a)))
(defn- encode* [previous [char & rest]]
(when char
(lazy-seq
(if (alphabet? char)
(cons (c>> previous char) (encode* char rest))
(cons char (encode* previous rest))))))
(defn encode [s]
(->> s .toUpperCase (encode* nil) string/join))
(defn- decode* [previous [char & rest]]
(when char
(lazy-seq
(if (alphabet? char)
(cons (c<< previous char) (decode* (c<< previous char) rest))
(cons char (decode* previous rest))))))
(defn decode [s]
(->> s .toUpperCase (decode* nil) string/join))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment