-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrail_fence.rb
57 lines (48 loc) · 1.23 KB
/
rail_fence.rb
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
def encrypt(str, number_of_rails)
rails = Array.new(number_of_rails) { |_i| Array.new(str.length) }
dir_down = false
row = 0
(0...(str.length)).each do |i|
dir_down = !dir_down if row.zero? || row == number_of_rails - 1
# puts [dir_down, row].to_s
rails[row][i] = str[i]
dir_down ? row += 1 : row -= 1
end
output = ''
rails.each do |row|
output += row.join
end
puts output
output
end
def decrypt(cipher, number_of_rails)
rails = Array.new(number_of_rails) { |_i| Array.new(cipher.length) }
row = 0
(0...(cipher.length)).each do |i|
dir_down = !dir_down if row.zero? || row == number_of_rails - 1
rails[row][i] = '*'
dir_down ? row += 1 : row -= 1
end
char_pos = 0
rails.each do |row|
row.each_with_index do |row_char, index|
if row_char == '*'
row[index] = cipher[char_pos]
char_pos += 1
end
end
end
# puts rails.to_s
row = 0
output = ''
(0...(cipher.length)).each do |i|
dir_down = !dir_down if row.zero? || row == number_of_rails - 1
output << rails[row][i]
dir_down ? row += 1 : row -= 1
end
output
end
str = 'WEAREDISCOVEREDFLEEATONCE'
cipher = encrypt(str, 3)
decrypted_text = decrypt(cipher, 3)
puts decrypted_text == str