Skip to content

Commit 916f7e2

Browse files
committed
Exercism-74 Atbash Cipher
1 parent 0bf673f commit 916f7e2

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,8 @@ solution of many challenges of [Leetcode](https://leetcode.com/), [Exercism](htt
295295
71. [Protein Translation](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/protein_translation.rb)
296296
72. [Wordy](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/wordy.rb)
297297
73. [Secret Handshake](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/secret_handshake.rb)
298+
74. [Atbash Cipher](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/atbash_cipher.rb)
299+
298300

299301
<a name="leetcode"/>
300302

exercism/atbash_cipher.rb

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Problem: https://exercism.org/tracks/ruby/exercises/atbash-cipher
2+
3+
# Solution
4+
class Atbash
5+
LETTERS = ("a".."z").to_a
6+
7+
def self.encode(plaintext)
8+
return "" if plaintext == ""
9+
ciphertext = ""
10+
plaintext = plaintext.downcase
11+
curr_cipher_len = 0
12+
for i in 0...(plaintext.length)
13+
if curr_cipher_len==5
14+
ciphertext+=" "
15+
curr_cipher_len = 0
16+
end
17+
18+
if plaintext[i].match(/\d+/)
19+
ciphertext+=plaintext[i]
20+
curr_cipher_len+=1
21+
next
22+
end
23+
24+
unless LETTERS.index(plaintext[i]).nil?
25+
ciphertext+= LETTERS[25-LETTERS.index(plaintext[i])]
26+
curr_cipher_len+=1
27+
end
28+
end
29+
ciphertext.strip
30+
end
31+
32+
def self.decode(ciphertext)
33+
return "" if ciphertext == ""
34+
plaintext = ""
35+
ciphertext = ciphertext.gsub(" ","")
36+
ciphertext.chars.each do |char|
37+
if LETTERS.index(char).nil?
38+
plaintext+=char
39+
else
40+
plaintext+= LETTERS[25-LETTERS.index(char)]
41+
end
42+
end
43+
plaintext
44+
end
45+
end
46+
47+
# Solution(idiomatic ruby)
48+
lass Atbash
49+
ALPHA = ('a'..'z').to_a.join
50+
51+
def self.encode(text)
52+
decode(text).chars.each_slice(5).map(&:join).join(' ')
53+
end
54+
55+
def self.decode(text)
56+
text.downcase.gsub(/\W/, '').tr(ALPHA, ALPHA.reverse)
57+
end
58+
end

0 commit comments

Comments
 (0)