Skip to content

Commit 1b48118

Browse files
committed
Solved day15 part 2
1 parent 6a1914c commit 1b48118

File tree

4 files changed

+43
-3
lines changed

4 files changed

+43
-3
lines changed

build.gradle

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ plugins {
44

55
// project meta data
66
group 'de.havox_design.aoc2023'
7-
version '0.14.4'
7+
version '0.14.5'
88

99
// Switch to gradle "all" distribution.
1010
wrapper {
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package de.havox_design.aoc2023.day15
2+
3+
data class Box(val code: Int, val lenses: MutableList<Lens> = mutableListOf()) {
4+
fun add(lens: Lens) {
5+
this
6+
.lenses
7+
.firstOrNull { it.label == lens.label }
8+
?.also { it.focalLength = lens.focalLength } ?: this.lenses.addLast(lens)
9+
}
10+
fun remove(label: String) {
11+
this
12+
.lenses
13+
.removeIf { it.label == label }
14+
}
15+
}

day15/src/main/kotlin/de/havox_design/aoc2023/day15/Day15.kt

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,30 @@ class Day15(private var filename: String) {
99
.sumOf { word -> calculateHash(word) }
1010
.toLong()
1111

12-
fun solvePart2(): Long =
13-
145L
12+
fun solvePart2(): Long {
13+
val instructions = getResourceAsText(filename)[0]
14+
.split(ELEMENT_DELIMITER)
15+
val boxes = mutableMapOf<Int, Box>()
16+
17+
for (instruction in instructions) {
18+
val (label, focalLength) = instruction.split('=', '-')
19+
val hash = calculateHash(label)
20+
when {
21+
focalLength.isBlank() -> {
22+
boxes[hash]?.remove(label)
23+
}
24+
else -> {
25+
boxes.computeIfAbsent(hash) { Box(it) }.add(Lens(label, focalLength.toInt()))
26+
}
27+
}
28+
}
29+
30+
return boxes
31+
.filter { it.value.lenses.isNotEmpty() }
32+
.flatMap { it.value.lenses.mapIndexed { idx, lens -> Triple(it.key + 1, idx + 1, lens) } }
33+
.sumOf { it.first * it.second * it.third.focalLength }
34+
.toLong()
35+
}
1436

1537
private fun calculateHash(word: String): Int =
1638
word
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
package de.havox_design.aoc2023.day15
2+
3+
data class Lens(val label: String, var focalLength: Int)

0 commit comments

Comments
 (0)