From 3a8a2d79a9c488cb36c24c59396f6d89e964ee45 Mon Sep 17 00:00:00 2001 From: chrisly42 Date: Sat, 16 Dec 2023 13:19:03 +0100 Subject: [PATCH] Minor update to Day 15 because I should have used a linked hashmap in the first place, if I had only read the instructions clearly enough. --- src/aoc2023/Day15.kt | 21 +++++++-------------- 1 file changed, 7 insertions(+), 14 deletions(-) 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: