-
Notifications
You must be signed in to change notification settings - Fork 3
/
lib.swift
74 lines (73 loc) · 1.88 KB
/
lib.swift
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
72
73
74
/*******************************
*
*
* Use: "RailFence cipher test phrase.".encrypt() or "RailFence cipher test phrase.".encrypt(3)
* "RailFence cipher test phrase.".encrypt().decrypt()
*
*
******************************/
import Foundation
extension String {
func encrypt(_ rows: Int = 3) -> String {
var fence = [[String]]()
for _ in 0...rows - 1 {
fence.append(Array<String>())
}
var rail = 0
var change = 1
let str = Array(self)
for i in str {
fence[rail].append(String(i))
rail += change
if (rail == rows-1 || rail == 0) {
change = -change
}
}
var r = ""
for rail in fence {
r += rail.joined(separator: "")
}
return r
}
func decrypt(_ rows: Int = 3) -> String {
var fence = [[String]]()
for _ in 0...rows - 1 {
fence.append(Array<String>())
}
var rail = 0
var change = 1
var str = Array(self)
for i in str {
fence[rail].append(String(i))
rail += change
if (rail == rows-1 || rail == 0) {
change = -change
}
}
var rFence = [[String]]()
for _ in 0...rows - 1 {
rFence.append(Array<String>())
}
var i = 0
let l = str.count
for r in fence {
for _ in 0...r.count - 1 {
rFence[i].append(String(str[0]))
str.remove(at: 0)
}
i += 1
}
rail = 0
change = 1
var r = ""
for _ in 0...l - 1 {
r += rFence[rail][0]
rFence[rail].remove(at: 0)
rail += change
if (rail == rows-1 || rail == 0) {
change = -change
}
}
return r
}
}