Created
February 25, 2016 12:20
-
-
Save clrnd/ed77a284ec78ae96c245 to your computer and use it in GitHub Desktop.
alphabet-cipher kata solution
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 alphabet-cipher.coder) | |
; Vemos que encodear un caracter `m` con | |
; una letra de keyword `k` es equivalente a sumar sus indices | |
; en el abecedario modulo 26. | |
; | |
; Por ejemplo: con indice("m") = 12 y indice("s") = 18 tenemos | |
; 12 + 18 ≡ 4 (mod 26) | |
; y 4 = indice("e") | |
; | |
; De la misma forma, para volver, pensemos en: | |
; | |
; a = indice de la letra del mensaje | |
; k = indice de la letra de la keyword | |
; b = indice de la letra resultante | |
; | |
; a + k ≡ b (mod 26) | |
; iff | |
; b - k ≡ a (mod 26) | |
; | |
; Osea, para obtener la letra original tenemos que restar al reves, | |
; y para obtener la letra de la keyword con el mensaje y el resultado: | |
; | |
; a + k ≡ b (mod 26) | |
; iff | |
; b - a ≡ k (mod 26) | |
; | |
; QED | |
(def abc (seq "abcdefghijklmnopqrstuvwxyz")) | |
(defn rotate-n [f k c] | |
(let [i1 (.indexOf abc k) | |
i2 (.indexOf abc c) | |
offset (mod (f i1 i2) (count abc))] | |
(nth abc offset))) | |
(defn encode [keyword message] | |
(apply str | |
(map (fn [a b] (rotate-n + a b)) (cycle keyword) message))) | |
(defn decode [keyword message] | |
(apply str | |
(map (fn [a b] (rotate-n #(- %2 %1) a b)) (cycle keyword) message))) | |
(defn decipher [cipher message] | |
(apply str | |
(map (fn [a b] (rotate-n - a b)) cipher message))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment