Write a program using Common Lisp that encrypts (encode)and decrypts (decode) a
ID: 3778805 • Letter: W
Question
Write a program using Common Lisp that encrypts (encode)and decrypts (decode) a phrase using the Caesar cipher.First convert all characters to numbers, A = 0, B = 1, C = 2, ..., Z = 25. The Caesar encryption function e(x), where x is the character being encrypted, is represented as e(x) = (x + k) (mod 26). k is the shift or key applied to each letter. After the function is applied the resulting number must then be converted back to a letter. The decryption function is e(x) = (x - k) (mod 26). Function Guidelines: 1) Function may only use recursion, 2) Each word of input must be read as a sub list of the list, and 3) No arrays, loops, or variables
Explanation / Answer
(defun encipher-char (ch key)
(let* ((c (char-code ch)) (la (char-code #)) (ua (char-code #A))
(base (cond ((<= la c (char-code #z)) la)
((<= ua c (char-code #Z)) ua)
(nil))))
(if base (code-char (+ (mod (+ (- c base) key) 26) base)) ch)))
(defun caesar-cipher (str key)
(map 'string #'(lambda (c) (encipher-char c key)) str))
(defun caesar-decipher (str key) (caesar-cipher str (- key)))
(let* ((actual-text "Heloo Good Morning")
(key 3)
(cipher-text (caesar-cipher actual-text key))
(decrypted-text (caesar-decipher cipher-text key)))
(format t " Actual original : ~a ~%" actual-text)
(format t "Encrypted Text: ~a ~%" cipher-text)
(format t "Decrypted Text: ~a ~%" decrypted-text))
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.