Guest User

Untitled

a guest
Apr 24th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. (ns cipher
  2. (:use [clojure.contrib.def :only (defnk)]))
  3.  
  4. (def alphabet-nums (apply hash-map (interleave (range 1 27) "abcdefghijklmnopqrstuvwxyz")))
  5. (def alphabet-chars (apply hash-map (interleave "abcdefghijklmnopqrstuvwxyz" (range 1 27))))
  6.  
  7. (defn is-letter? [s]
  8. (if (re-find #"(?i)[a-z]" (.toString s)) true false))
  9.  
  10. (defnk shift-char
  11. "Shifts the given Character down the alphabet by three.
  12. Has optional arg :d which takes :fw or :bw, so it can
  13. be used for deciphering as well as ciphering. If it
  14. isn't provided, will default to :fw for ciphering."
  15. [char :d :fw]
  16. (let [num (if (= d :fw) (+ char 3) (- char 3))
  17. pred (if (= d :fw) (> num 25) (< num 2))
  18. truec (if (= d :fw) (- num 26) (+ num 26))
  19. index
  20. (if (and pred (not= num (if (= d :fw) 26 1))) truec num)]
  21. (alphabet-nums index)))
  22.  
  23. (defn trans-string
  24. "Transforms a string into a vector of numbers
  25. that correspond with their characters."
  26. [s]
  27. (for [x s] (alphabet-chars x)))
  28.  
  29. (defnk cipher
  30. "Encrypts a string with Caesar's cipher."
  31. [s :d :to]
  32. (apply str
  33. (let [args
  34. (if (= d :from) :bw :fw)]
  35. (for [x (trans-string (.toLowerCase (apply str (filter is-letter? s))))]
  36. (shift-char x :d args)))))
  37.  
  38. (defn to-cleartext
  39. "Transforms ciphertext into cleartext."
  40. [s])
  41.  
  42. (comment
  43. cipher> (cipher "abd")
  44. "deg"
  45. cipher> (cipher "abd" :from)
  46. ; Evaluation aborted.
  47. cipher> (cipher "abd" :direction :from)
  48. "xya"
  49. cipher> (cipher "abd" :direction :to)
  50. "deg"
  51. )
Add Comment
Please, Sign In to add comment