mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-26 21:58:56 +01:00
Add Caesar
extra line
This commit is contained in:
parent
f7538d07b4
commit
db5a8181b6
2 changed files with 55 additions and 0 deletions
33
ciphers/caesar.rb
Normal file
33
ciphers/caesar.rb
Normal file
|
@ -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
|
||||||
|
|
22
ciphers/caesar_test.rb
Normal file
22
ciphers/caesar_test.rb
Normal file
|
@ -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
|
||||||
|
|
Loading…
Reference in a new issue