Skip to content

Instantly share code, notes, and snippets.

@Raynes
Created November 7, 2009 05:06
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 Raynes/228543 to your computer and use it in GitHub Desktop.
Save Raynes/228543 to your computer and use it in GitHub Desktop.
(ns cipher
(:use [clojure.contrib.def :only (defnk)]))
(def alphabet-nums (apply hash-map (interleave (range 1 27) "abcdefghijklmnopqrstuvwxyz")))
(def alphabet-chars (apply hash-map (interleave "abcdefghijklmnopqrstuvwxyz" (range 1 27))))
(defn is-letter? [s]
(if (re-find #"(?i)[a-z]" (.toString s)) true false))
(defn shift-char-forward
"Shifts the given Character down the alphabet by three."
[char]
(let [num (+ char 3)
index (if (and (> num 25) (not= num 26)) (- num 26) num)]
(alphabet-nums index)))
(defn shift-char-backward
"Same as shift-char-forward, only this is for decryption."
[char]
(let [num (- char 3)
index (if (and (< num 2) (not= num 1)) (+ num 26) num)]
(alphabet-nums index)))
(defn trans-string
"Transforms a string into a vector of numbers
that correspond with their characters."
[s]
(for [x s] (alphabet-chars x)))
(defnk cipher
"Encrypts a string with Caesar's cipher."
[s :direction :to]
(apply str
(let [func
(if (= direction :from) shift-char-backward shift-char-forward)]
(for [x (trans-string (.toLowerCase (apply str (filter is-letter? s))))]
(func x)))))
(defn to-cleartext
"Transforms ciphertext into cleartext."
[s])
(comment
cipher> (cipher "abd")
"deg"
cipher> (cipher "abd" :from)
; Evaluation aborted.
cipher> (cipher "abd" :direction :from)
"xya"
cipher> (cipher "abd" :direction :to)
"deg"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment