From 79e316c51bf8c7b5d389eaa4f600941acae56863 Mon Sep 17 00:00:00 2001 From: KKlochko Date: Thu, 21 Sep 2023 21:05:22 +0300 Subject: [PATCH] Update the Caesar to be case-insensitive and skip unknown symbols. --- src/cipher_analytical_machine/caesar.clj | 23 ++++++++++++------- .../cipher_analytical_machine/caesar_test.clj | 10 ++++++-- 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/src/cipher_analytical_machine/caesar.clj b/src/cipher_analytical_machine/caesar.clj index 7ac2285..cdaba11 100644 --- a/src/cipher_analytical_machine/caesar.clj +++ b/src/cipher_analytical_machine/caesar.clj @@ -14,21 +14,28 @@ (+ 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] - (get symbols - (-> char - (calculate-char-index symbols) - (encrypt-index key 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." + "Encrypt a message using the Caesar cipher. The function is case-insensitive." [message key symbols] (let [max-index (count symbols)] - (cs/join - (map (fn [char] (encrypt-char char key symbols max-index)) - message)))) + (->> 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." diff --git a/test/cipher_analytical_machine/caesar_test.clj b/test/cipher_analytical_machine/caesar_test.clj index bdb4b8d..e1b773e 100644 --- a/test/cipher_analytical_machine/caesar_test.clj +++ b/test/cipher_analytical_machine/caesar_test.clj @@ -51,14 +51,20 @@ (testing "The message 'abc' is encrypted to 'bca'" (is (= "bca" (encrypt-message "abc" 1 symbols)))) + (testing "The message 'ABC' is encrypted to 'bca', because of case-insensitive." + (is (= "bca" (encrypt-message "ABC" 1 symbols)))) + (testing "The message 'bca' is decrypted to 'abc'" (is (= "abc" (encrypt-message "bca" -1 symbols)))))) (deftest decrypt-message-text (let [symbols "abc"] (testing "The message 'bca' is decrypted to 'abc'" - (is (= "abc" (decrypt-message "bca" 1 symbols))) + (is (= "abc" (decrypt-message "bca" 1 symbols)))) + + (testing "The message 'BCA' is decrypted to 'abc', because of case-insensitive." + (is (= "abc" (decrypt-message "BCA" 1 symbols)))) (testing "The message 'abc' is encrypted to 'bca'" - (is (= "bca" (decrypt-message "abc" -1 symbols))))))) + (is (= "bca" (decrypt-message "abc" -1 symbols))))))