Skip to content

Commit 7df1287

Browse files
committed
AOC - Day 16
1 parent 6ac063a commit 7df1287

File tree

3 files changed

+355
-0
lines changed

3 files changed

+355
-0
lines changed

src/main/java/Exercise16-part2.kt

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
fun main() {
2+
val input = object {}.javaClass.getResource("input-16.txt").readText().split("\n\n")
3+
4+
val ranges = input[0].split("\n")
5+
.associateBy({
6+
it.substring(0, it.indexOf(":"))
7+
}, {
8+
it.substring(it.indexOf(":") + 1)
9+
.replace(" or", "")
10+
.trim()
11+
.split(" ")
12+
.map { range ->
13+
range.split("-").let { it[0].toInt()..it[1].toInt() }
14+
}
15+
})
16+
17+
val myTicket = input[1].split("\n")[1]
18+
.split(",")
19+
.map(String::toLong)
20+
21+
val validTickets = input[2].split("\n")
22+
.drop(1)
23+
.map { it.split(",").map(String::toInt) }
24+
.filter {
25+
it.all { value ->
26+
ranges.any { entry ->
27+
entry.value.any { range -> value in range }
28+
}
29+
}
30+
}
31+
32+
val possibleRules = (myTicket.indices).map { index ->
33+
ranges.values
34+
.mapIndexed { rangeIndex, ranges ->
35+
rangeIndex to ranges
36+
}
37+
.filter { (_, ranges) ->
38+
validTickets.all { ticket -> ranges.any { range -> ticket[index] in range } }
39+
}
40+
.map { (rangeIndex, _) -> rangeIndex }
41+
.toMutableList()
42+
}.toMutableList()
43+
44+
val ordering = IntArray(possibleRules.size)
45+
46+
while (possibleRules.any { it.isNotEmpty() }) {
47+
val indexToRemove = possibleRules.indexOfFirst { it.size == 1 }
48+
val valueToRemove = possibleRules[indexToRemove][0]
49+
possibleRules[indexToRemove].clear()
50+
ordering[indexToRemove] = valueToRemove
51+
possibleRules.onEach { it.remove(valueToRemove) }
52+
}
53+
54+
ranges.entries
55+
.asSequence()
56+
.filter { it.key.startsWith("departure") }
57+
.mapIndexed { index, entry -> index to entry.key }
58+
.map { (index, _) -> myTicket[ordering.indexOf(index)] }
59+
.fold(1L) { acc, next -> acc * next }
60+
.also(::println)
61+
}

src/main/java/Exercise16.kt

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
fun main() {
2+
val input = object {}.javaClass.getResource("input-16.txt").readText().split("\n\n")
3+
4+
val ranges = input[0].split("\n")
5+
.flatMap { line ->
6+
line.substring(line.indexOf(":") + 1)
7+
.replace(" or", "")
8+
.trim()
9+
.split(" ")
10+
.map { range ->
11+
range.split("-").let { bounds ->
12+
bounds[0].toInt()..bounds[1].toInt()
13+
}
14+
}
15+
}
16+
17+
input[2].split("\n")
18+
.drop(1)
19+
.flatMap {
20+
it.split(",")
21+
}
22+
.map { it.toInt() }
23+
.filter { value -> ranges.all { range -> value !in range } }
24+
.sum()
25+
.also(::println)
26+
}

0 commit comments

Comments
 (0)