-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.rb
More file actions
36 lines (26 loc) · 771 Bytes
/
Copy pathsolution.rb
File metadata and controls
36 lines (26 loc) · 771 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
module Solution1
def self.caesar_cipher(str, shift)
first_codepoint = 'a'.ord
last_codepoint = 'z'.ord
real_shift = shift % (last_codepoint - first_codepoint + 1)
shifted_chars = str.codepoints.map do |cp|
new_codepoint = cp + real_shift
if new_codepoint > last_codepoint
new_codepoint = (first_codepoint + (new_codepoint - last_codepoint) - 1)
end
new_codepoint.chr
end
shifted_chars.join
end
end
module Solution2
def self.caesar_cipher(str, shift)
alphabet = "abcdefghijklmnopqrstuvwxyz"
shifted_chars = str.chars.map do |c|
char_index = alphabet.index(c)
new_index = (char_index + shift) % alphabet.length
alphabet[new_index]
end
shifted_chars.join('')
end
end