Last active
October 26, 2022 10:04
-
-
Save whamtet/ee8d0cbb9bc33336c16c10778905b961 to your computer and use it in GitHub Desktop.
This file contains 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 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