-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.swift
More file actions
38 lines (32 loc) · 876 Bytes
/
Solution.swift
File metadata and controls
38 lines (32 loc) · 876 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
37
38
import Foundation
class Encoder {
private var storage = Dictionary<String, String>()
private var pool = Array("qwertyuiopasdfghjklzxcvbnm1234567890")
func encode(_ str: String) -> String {
var seq = ""
repeat {
seq = randomSequence()
} while storage[seq] != nil
storage[seq] = str
return seq
}
func decode(_ str: String) -> String {
if let result = storage[str] {
return result
}
return ""
}
func randomSequence() -> String {
var str = ""
for _ in 0..<6 {
let c = pool[rand(pool.count)]
str.append(c)
}
return str
}
func rand(_ upper: Int) -> Int {
return Int(arc4random_uniform(UInt32(upper)))
}
}
let coder = Encoder()
print(coder.decode(coder.encode("abc")))