Skip to content

Commit 04ddd9b

Browse files
authored
Merge pull request TheAlgorithms#164 from kaiquekandykoga/caesar-cipher
Caesar Cipher
2 parents 782d179 + db5a818 commit 04ddd9b

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

ciphers/caesar.rb

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Caesar Cipher replaces characters rotating X number of positions to the left or to the right.
2+
#
3+
# Alphabet
4+
# 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
5+
#
6+
# shift 4 >> it means to rotate 4 places
7+
#
8+
# After shifting
9+
# 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
10+
#
11+
# plaintext -> apple
12+
# ciphertext -> ettpi
13+
14+
class CaesarCipher
15+
ALPHABET = ('a'..'z').to_a
16+
17+
def self.encrypt(plaintext, shift)
18+
plaintext.chars.map do |letter|
19+
temp = letter.ord + shift
20+
temp -= ALPHABET.length while temp > 'z'.ord
21+
temp.chr
22+
end.join
23+
end
24+
25+
def self.decrypt(ciphertext, shift)
26+
ciphertext.chars.map do |letter|
27+
temp = letter.ord - shift
28+
temp += ALPHABET.length while temp < 'a'.ord
29+
temp.chr
30+
end.join
31+
end
32+
end
33+

ciphers/caesar_test.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
require 'minitest/autorun'
2+
require_relative 'caesar'
3+
4+
class CaesarCipherTest < Minitest::Test
5+
def test_shift4
6+
run_tests('apple', 'ettpi', 4)
7+
end
8+
9+
def test_shift27
10+
run_tests('amateur', 'bnbufvs', 27)
11+
end
12+
13+
private
14+
15+
def run_tests(plaintext, expected_cipher, shift)
16+
encrypted = CaesarCipher.encrypt(plaintext, shift)
17+
assert_equal encrypted, expected_cipher
18+
decrypted = CaesarCipher.decrypt(encrypted, shift)
19+
assert_equal decrypted, plaintext
20+
end
21+
end
22+

0 commit comments

Comments
 (0)