Files
cipher-analytical-machine/src/cipher_analytical_machine/ciphers/caesar.clj
T
KKlochko 4d7e9da1d1
continuous-integration/drone/push Build is passing
Refactor the project structure.
2023-10-11 21:12:10 +03:00

45 lines
1.3 KiB
Clojure

(ns cipher-analytical-machine.ciphers.caesar
(:require [clojure.string :as cs])
(:gen-class))
(defn calculate-char-index
"Calculate the index of a char."
[char symbols]
(cs/index-of symbols char))
(defn encrypt-index
"Calculates new index of a character. Uses its index, the key and max-index (exclusive)."
[index key max-index]
(-> index
(+ key)
(mod max-index)))
(defn encrypt-or-skip
"If symbols do not have a character, then it will be skipped."
[index character key symbols max-index]
(if (nil? index) character
(get symbols
(encrypt-index index key max-index))))
(defn encrypt-char
"Calculates new index of a character. Uses a char from symbols, the key and max-index (exclusive)."
[char key symbols max-index]
(-> char
(calculate-char-index symbols)
(encrypt-or-skip char key symbols max-index)))
(defn encrypt-message
"Encrypt a message using the Caesar cipher. The function is case-insensitive."
[message key symbols]
(let [max-index (count symbols)]
(->> message
(cs/lower-case)
(map (fn [char] (encrypt-char char key symbols max-index)))
(cs/join))))
(defn decrypt-message
"Decrypt the ciphtext using the Caesar cipher."
[ciphertext key symbols]
(encrypt-message ciphertext (- key) symbols))