diff --git a/src/aoc2023/Day15.kt b/src/aoc2023/Day15.kt index cf5e011..0fe9fce 100644 --- a/src/aoc2023/Day15.kt +++ b/src/aoc2023/Day15.kt @@ -73,27 +73,20 @@ rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7 } fun part2(input: List): Int { - val boxes = Array>(256) { ArrayList() } - println(hash("cm")) + val boxes = Array>(256) { LinkedHashMap() } input.first().split(",").forEach { it -> if (it.contains('=')) { val (label, value) = it.split("=") - val hash = hash(label) - if (boxes[hash].none { it.startsWith("$label ") }) { - boxes[hash].add("$label $value") - } else { - boxes[hash] = boxes[hash].map { content -> if (content.startsWith("$label ")) "$label $value" else content }.toMutableList() - } + boxes[hash(label)][label] = value.toInt() } else { val label = it.removeSuffix("-") - val hash = hash(label) - boxes[hash] = boxes[hash].filterNot { it.startsWith("$label ") }.toMutableList() + boxes[hash(label)].remove(label) } } - val vals = boxes.mapIndexed { boxno, contents -> - contents.mapIndexed { index, strings -> (boxno + 1) * strings.split(" ")[1].toInt() * (index + 1) }.sum() - } - return vals.sum() + return boxes.mapIndexed { boxno, contents -> + contents.map { entry -> entry.value } + .mapIndexed { index, value -> (boxno + 1) * value * (index + 1) }.sum() + }.sum() } // test if implementation meets criteria from the description, like: