-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrot.rb
More file actions
71 lines (51 loc) · 1.96 KB
/
rot.rb
File metadata and controls
71 lines (51 loc) · 1.96 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
=begin
Source: interview challenege
Description:
The rot13() function encrypts a string by rotating the letters around the alphabet by 13.
rot13('ABCD') outputs 'NOPQ'
Write a rotation encryption function called 'rotx' that returns a string encrypted by rotating the letters x places around the alphabet.
The function should have 3 input parameters:
x: the number to rotate by
string: the input string
encrypt: defaulted to true, when false it should decrypt an encrypted string with the same rotation
Example:
rotx(5, 'Hello world') => 'Mjqqt btwqi'
rotx(5, 'Mjqqt btwqi', false) => 'Hello world'
=end
# first solution, could use some refactoring
def rotx1(x, string, encrypt=true)
return string if x % 26 == 0
offset = encrypt ? x % 26 : -x % 26
return string.tr('A-Za-z', 'B-ZAb-za') if offset == 1
return string.tr('A-Za-z', "ZA-Yza-y") if offset == 25
rot_a = (offset + 'a'.ord).chr
rot_z = (rot_a.ord - 1).chr
string.tr('A-Za-z', rot_a.upcase + "-ZA-" + rot_z.upcase + rot_a + "-za-" + rot_z)
end
# second solution, refactored the first solution and created a helper function to get the rotated translation string
def rotx2(x, string, encrypt=true)
offset = encrypt ? x % 26 : -x % 26
string.tr('A-Za-z', rotated_alph(offset))
end
def rotated_alph(offset)
case offset
when 0; "A-Za-z"
when 1; "B-ZAb-za"
when 25; "ZA-Yza-y"
else
rot_a = (offset + 'a'.ord).chr
rot_z = (rot_a.ord - 1).chr
rot_a.upcase + "-ZA-" + rot_z.upcase + rot_a + "-za-" + rot_z
end
end
# third solution, removed case statement and refactored
TR = { 0 => "A-Za-z", 1 => "B-ZAb-za", 25 => "ZA-Yza-y" }
def rotx3(x, string, encrypt=true)
offset = encrypt ? x % 26 : -x % 26
string.tr('A-Za-z', rotated_alpha(offset))
end
def rotated_alpha(offset)
rot_a = (offset + 'a'.ord).chr
rot_z = (rot_a.ord - 1).chr
TR[offset] || rot_a.upcase + "-ZA-" + rot_z.upcase + rot_a + "-za-" + rot_z
end