Skip to content

Instantly share code, notes, and snippets.

@jooyunghan
Created September 14, 2015 07:14
Show Gist options
  • Save jooyunghan/f5898566e35668425c95 to your computer and use it in GitHub Desktop.
Save jooyunghan/f5898566e35668425c95 to your computer and use it in GitHub Desktop.
Alphabet Cipher
(ns alphabet-cipher.coder)
(defn to-char [n]
(char (+ (int \a) (mod n 26))))
(defn to-int [c]
(- (int c) (int \a)))
(defn m [k s]
(to-char (+ (to-int k)(to-int s))))
(defn rm [k s]
(to-char (- (to-int s) (to-int k))))
(defn encode [keyword message]
(apply str (map m (cycle keyword) message)))
(defn decode [keyword message]
(apply str (map rm (cycle keyword) message)))
(defn inits [s]
(when-let [ss (seq s)]
(cons [] (map #(cons (first ss) %) (inits (rest ss))))))
(defn uncycle [s]
(let [len (count s)]
(first (filter #(= (seq s) (take len (cycle %))) (rest (inits s))))))
(defn decypher [cypher message]
(apply str (uncycle (apply str (map rm message cypher)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment