-
-
Notifications
You must be signed in to change notification settings - Fork 153
/
CryptoSquareExample.swift
82 lines (65 loc) · 2.63 KB
/
CryptoSquareExample.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
75
76
77
78
79
80
81
82
import Darwin
private extension String {
func stripCharacters(_ charToRemove: String) -> String {
var returnString = ""
self.characters.forEach {
if !charToRemove.contains(String($0)) {
returnString.append($0)
}}
return returnString
}
var stripWhiteSpace: String { return stripCharacters(" ") }
var stripPunctuations: String { return stripCharacters(",.!?") }
var stripSymbols: String { return stripCharacters("#$%^&") }
}
struct Crypto {
func segmentSorter(_ value: String, spacing: Int) -> [String] {
var tempCounter = 0
var tempString: String = ""
for each in value.characters {
if tempCounter % spacing == 0 && tempCounter != 0 {
tempString += " \(each)"
} else { tempString += "\(each)" }
tempCounter += 1
}
return (tempString.components(separatedBy: " ") )
}
func getSquareSize(_ text: String, floorNoCeling: Bool = false) -> Int {
let tempDouble = Double(text.characters.count)
let tempRoot = sqrt(tempDouble)
let tempCeil = ceil(tempRoot)
let tempFloor = floor(tempRoot)
if floorNoCeling { return Int(tempFloor)} else {
return Int(tempCeil)}
}
func normalizer(_ textInput: String) -> String {
return textInput.stripSymbols.stripPunctuations.stripWhiteSpace.lowercased()
}
var ciphertext: String {
var plaintextSegmentsArray = [[Character]]()
for each in plaintextSegments {
plaintextSegmentsArray.append(Array(each.characters))
}
var ciphertextReturn = ""
for i in 0 ..< plaintextSegmentsArray[0].count {
for e in 0 ..< plaintextSegmentsArray.count {
if i < plaintextSegmentsArray[e].count {
ciphertextReturn.append(plaintextSegmentsArray[e][i])
}
}}
return ciphertextReturn
}
var normalizeCiphertext: String {
let sizeNormal: Int = (ciphertext.characters.count == self.size * self.size ) ? getSquareSize(self.ciphertext) : getSquareSize(self.ciphertext, floorNoCeling: true)
return segmentSorter(ciphertext, spacing: sizeNormal).joined(separator: " ")
}
var plaintextSegments: [String] { get { return segmentSorter(self.normalizePlaintext, spacing: self.size)}}
var textValue: String = ""
var normalizePlaintext: String = ""
var size: Int = 0
init (_ value: String) {
self.textValue = value
self.normalizePlaintext = normalizer(value)
self.size = getSquareSize(self.normalizePlaintext)
}
}