Skip to content

Instantly share code, notes, and snippets.

@Raynes
Created November 7, 2009 18:53
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/228840 to your computer and use it in GitHub Desktop.
Save Raynes/228840 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))
(defnk shift-char-forward
"Shifts the given Character down the alphabet by three.
Has optional arg :d which takes :fw or :bw, so it can
be used for deciphering as well as ciphering. If it
isn't provided, will default to :fw for ciphering."
[char :d :fw]
(let [num (if (= d :fw) (+ char 3) (- char 3))
pred (if (= d :fw) (> num 25) (< num 2))
truec (if (= d :fw) (- num 26) (+ num 26))
index
(if (and pred (not= num (if (= d :fw) 26 1))) truec 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 :d :to]
(apply str
(let [args
(if (= d :from) :bw :fw)]
(for [x (trans-string (.toLowerCase (apply str (filter is-letter? s))))]
(shift-char-forward x :d args)))))
(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