From db5a8181b6e5777ffd4bac06607beea318842a9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ka=C3=ADque=20Kandy=20Koga?= Date: Sun, 25 Jul 2021 16:13:34 -0300 Subject: [PATCH] Add Caesar extra line --- ciphers/caesar.rb | 33 +++++++++++++++++++++++++++++++++ ciphers/caesar_test.rb | 22 ++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 ciphers/caesar.rb create mode 100644 ciphers/caesar_test.rb diff --git a/ciphers/caesar.rb b/ciphers/caesar.rb new file mode 100644 index 0000000..c76ea74 --- /dev/null +++ b/ciphers/caesar.rb @@ -0,0 +1,33 @@ +# Caesar Cipher replaces characters rotating X number of positions to the left or to the right. +# +# Alphabet +# a b c d e f g h i j k l m n o p q r s t u v w x y z +# +# shift 4 >> it means to rotate 4 places +# +# After shifting +# e f g h i j k l m n o p q r s t u v w x y z a b c d +# +# plaintext -> apple +# ciphertext -> ettpi + +class CaesarCipher + ALPHABET = ('a'..'z').to_a + + def self.encrypt(plaintext, shift) + plaintext.chars.map do |letter| + temp = letter.ord + shift + temp -= ALPHABET.length while temp > 'z'.ord + temp.chr + end.join + end + + def self.decrypt(ciphertext, shift) + ciphertext.chars.map do |letter| + temp = letter.ord - shift + temp += ALPHABET.length while temp < 'a'.ord + temp.chr + end.join + end +end + diff --git a/ciphers/caesar_test.rb b/ciphers/caesar_test.rb new file mode 100644 index 0000000..090945d --- /dev/null +++ b/ciphers/caesar_test.rb @@ -0,0 +1,22 @@ +require 'minitest/autorun' +require_relative 'caesar' + +class CaesarCipherTest < Minitest::Test + def test_shift4 + run_tests('apple', 'ettpi', 4) + end + + def test_shift27 + run_tests('amateur', 'bnbufvs', 27) + end + + private + + def run_tests(plaintext, expected_cipher, shift) + encrypted = CaesarCipher.encrypt(plaintext, shift) + assert_equal encrypted, expected_cipher + decrypted = CaesarCipher.decrypt(encrypted, shift) + assert_equal decrypted, plaintext + end +end +