-
Notifications
You must be signed in to change notification settings - Fork 0
/
Contents.swift
49 lines (33 loc) · 1.32 KB
/
Contents.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
//: [Previous](@previous)
import Foundation
//: # Advent of code 2018 playground
//: ## Day 5 Part 2
//: ### Problem definition
let problem = Problem { (polymer: [String]) -> Int in
var counts: [Int] = []
var allTypes: Set<String> = []
polymer.forEach { allTypes.insert($0.uppercased()) }
for toRemove in allTypes {
let colapsed = polymer.reduce(into: [], { (units: inout [String], unit: String) in
if unit.uppercased() == toRemove { return }
if let last = units.last {
if last.caseInsensitiveCompare(unit) == .orderedSame {
if (last == last.uppercased() && unit == unit.lowercased()) ||
(last == last.lowercased() && unit == unit.uppercased()) {
units.removeLast()
return
}
}
}
units.append(unit)
})
counts.append(colapsed.count)
}
return counts.min()!
}
//: ### Tests
problem.test(input: ["d","a","b","A","c","C","a","C","B","A","c","C","c","a","D","A"], expected: 4)
//: ### Find Solution
let input = try getInputString().trimmingCharacters(in: .whitespacesAndNewlines).reduce(into: []) { $0.append(String($1)) }
problem.run(input: input)
//: [Next](@next)