-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.swift
79 lines (64 loc) · 2.28 KB
/
main.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
import Foundation
func main() throws {
let input: [String] = try readInput(fromTestFile: false)
let strings: [NString] = input.map({ NString(content: [Character]($0)) })
print("Part one:", strings.reduce(0, { $1.isNice ? $0 + 1 : $0 }))
let partTwoStrings: [NString2] = input.map({ NString2(content: [Character]($0)) })
print("Part two:", partTwoStrings.reduce(0, { $1.isNice ? $0 + 1 : $0 }))
}
struct NString {
let content: [Character]
var counts: [Character: Int]
var vowelCount: Int {
["a", "e", "i", "o", "u"].map({ counts[$0, default: 0] }).sum()
}
var containsDoubleLetter = false
var containsInvalidString = false
var isNice: Bool {
vowelCount >= 3 && containsDoubleLetter && !containsInvalidString
}
init(content: [Character]) {
self.content = content
var counts: [Character: Int] = [:]
for i in 0..<content.count {
let char = content[i]
if i > 0 {
if content[i-1] == char {
self.containsDoubleLetter = true
}
if ["ab", "cd", "pq", "xy"].contains([String(content[i-1]), String(char)].joined()) {
self.containsInvalidString = true
}
}
counts[char] = counts[char, default: 0] + 1
}
self.counts = counts
}
}
struct NString2 {
let pairs: [String]
var containsRepeatWithCharBetween = false
var containsRepeatedPair: Bool {
var indexesOfPairs: [String: [Int]] = [:]
for i in 0..<pairs.count {
indexesOfPairs[pairs[i], default: []] += [i]
}
let validPairs = indexesOfPairs.filter({ $0.value.count > 1 && ($0.value.last! - $0.value.first!) > 1 })
return !validPairs.isEmpty
}
var isNice: Bool { containsRepeatedPair && containsRepeatWithCharBetween }
init(content: [Character]) {
var pairs: [String] = []
for i in 0..<content.count {
let char = content[i]
if i > 0 {
pairs.append([String(content[i-1]), String(char)].joined())
}
if i > 1 && content[i-2] == char {
self.containsRepeatWithCharBetween = true
}
}
self.pairs = pairs
}
}
Timer.time(main)