-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay10.kt
75 lines (61 loc) · 2.21 KB
/
Day10.kt
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
import java.io.File
fun main() {
part1("src/main/resources/day10sample.txt")
part1("src/main/resources/day10.txt")
part2("src/main/resources/day10sample.txt")
part2("src/main/resources/day10.txt")
}
data class ChunkStack(val openers: MutableList<Char> = mutableListOf()) {
companion object {
val endPairs = mapOf('[' to ']', '(' to ')', '{' to '}', '<' to '>')
}
private fun Char.isOpener(): Boolean = this in endPairs.map { it.key }
private fun Char.isCloserForTopOfStack(): Boolean = this == endPairs[openers.first()]
fun pushOrReturnInvalidChar(c: Char): Char? =
when {
c.isOpener() -> apply { openers.add(0, c) }.let { null }
c.isCloserForTopOfStack() -> apply { openers.removeFirst() }.let { null }
else -> c
}
fun popCompliments(): List<Char> = openers.mapNotNull { c -> endPairs[c] }
}
fun String.getFirstCorruptChar(): Char? =
ChunkStack().let { stack -> this.firstOrNull { c -> stack.pushOrReturnInvalidChar(c) != null } }
fun Char.getSyntaxCheckPoints(): Int =
when(this) {
')' -> 3
']' -> 57
'}' -> 1197
'>' -> 25137
else -> error("Unknown closer")
}
private fun part1(inputFile: String) {
File(inputFile).readLines().asSequence()
.map { line -> line.getFirstCorruptChar() }
.filterNotNull()
.map { it.getSyntaxCheckPoints() }
.apply { println(this.sum()) }
}
//part 2
fun Char.getAutoCompletePoints(): Int =
when(this) {
')' -> 1
']' -> 2
'}' -> 3
'>' -> 4
else -> error("Unknown closer")
}
fun String.getMissingClosers(): List<Char> =
ChunkStack().apply { [email protected] { this.pushOrReturnInvalidChar(it) } }.popCompliments()
private fun part2(inputFile: String) {
File(inputFile).readLines().asSequence()
.filter { line -> line.getFirstCorruptChar() == null }
.map { it.getMissingClosers() }
.map { completeChars ->
completeChars.map { char -> char.getAutoCompletePoints() }
.fold(0L) { acc, pts -> (acc*5)+pts }
}
.sorted().toList()
.let { n -> n[n.size/2] }
.apply { println(this) }
}