diff --git a/days/src/main/kotlin/Day14.kt b/days/src/main/kotlin/Day14.kt index b30184a..517d74f 100644 --- a/days/src/main/kotlin/Day14.kt +++ b/days/src/main/kotlin/Day14.kt @@ -6,7 +6,7 @@ import be.vandewalleh.aoc.utils.input.Lines import be.vandewalleh.aoc.utils.input.createDay import kotlin.math.pow import org.eclipse.collections.impl.factory.primitive.IntObjectMaps -import org.eclipse.collections.impl.factory.primitive.ObjectLongMaps +import org.eclipse.collections.impl.factory.primitive.ObjectIntMaps @Day(14) class Day14(@Lines val input: Input>) { @@ -42,48 +42,23 @@ class Day14(@Lines val input: Input>) { } fun part2(): Long { - val mem = ObjectLongMaps.mutable.empty() + val mem = ObjectIntMaps.mutable.empty() - var currentMask: String = "" + var currentMask = "" for (line in input.value) { - if (line.startsWith("mask")) { - currentMask = line.removePrefix("mask = ") + if (line[1] == 'a') { + currentMask = line.substring(7) } else { + val (address, value) = memRe.find(line)!!.destructured.let { (add, value) -> - add.toLong().toBin36() to value.toLong() + add.toLong().toBin36() to value.toInt() } - val addresses = address.zip(currentMask).map { (address, mask) -> - when (mask) { - 'X' -> arrayOf('0', '1') - '1' -> arrayOf('1') - else -> arrayOf(address) - } - } + val builders = generateMutations(currentMask, address) - val mutations = currentMask.count { it == 'X' }.let { 2.0.pow(it.toDouble()).toInt() } - val builders = Array(mutations) { StringBuilder() } - - var groups = 1 - - for (address in addresses) { - if (address.size > 1) { - groups *= 2 - val groupSize = mutations / groups - var j = 0 - for (i in 0 until mutations) { - val flip = i % groupSize == 0 - if (flip) j = if (j == 0) 1 else 0 - builders[i].append(address[j]) - } - } else { - builders.forEach { it.append(address[0]) } - } - } - - builders.map { it.toString() }.forEach { address -> - mem.put(address, value) + for (builder in builders) { + mem.put(builder.toString(), value) } } } @@ -91,6 +66,36 @@ class Day14(@Lines val input: Input>) { return mem.values().sum() } + private fun generateMutations(mask: String, address: String): Array { + val mutations = mask.count { it == 'X' }.let { 2.0.pow(it.toDouble()).toInt() } + val builders = Array(mutations) { StringBuilder(36) } + + var groups = 1 + + for (i in mask.indices) { + when (mask[i]) { + 'X' -> { + groups *= 2 + val groupSize = mutations / groups + var j = 1 + for (b in builders.indices) { + val builder = builders[b] + val flip = b % groupSize == 0 + if (flip) j = if (j == 0) 1 else 0 + builder.append(j) + } + } + '1' -> { + builders.forEach { it.append('1') } + } + else -> { + builders.forEach { it.append(address[i]) } + } + } + } + return builders + } + } fun main() = with(createDay()) {