diff --git a/src/year2021/day24/Day24.kt b/src/year2021/day24/Day24.kt new file mode 100644 index 0000000..0ff4434 --- /dev/null +++ b/src/year2021/day24/Day24.kt @@ -0,0 +1,46 @@ +package year2021.day24 + +import readInput + +data class Parameter(val remainder: Long, val divisor: Long, val addition: Long) + +fun solver(range: LongProgression, parameters: List): Long { + val cache: MutableMap, Long?> = mutableMapOf() + + fun solveAlternative(i: Int, w: Long, z: Long, overall: Long = 0): Long? { + val cacheKey = Triple(i, w, z) + if (cacheKey in cache) { + return cache[cacheKey]; + } + + val (remainder, divisor, addition) = parameters[i] + val x = if (((z % 26) + remainder) != w) 1 else 0 + + val newZ = z / divisor * (25 * x + 1) + (w + addition) * x + val result = when (i) { + 13 -> if (newZ == 0L) overall else null + else -> range.firstNotNullOfOrNull { + solveAlternative(i + 1, it, newZ, overall * 10 + it) + } + } + + cache[cacheKey] = result + return result + } + + return range.firstNotNullOf { solveAlternative(0, it, 0, it) } +} + +fun part1(parameters: List): Long = solver(9L downTo 1L, parameters) +fun part2(parameters: List): Long = solver(1L..9L, parameters) + +fun List.toParameters(): List = this.chunked(18).map { + val (rem, div, add) = listOf(it[5], it[4], it[15]).map { it.split(" ")[2].toLong() } + Parameter(rem, div, add) +} + +fun main() { + val parameters = readInput(24, "input").toParameters() + println(part1(parameters)) + println(part2(parameters)) +} diff --git a/src/year2021/day24/binary.txt b/src/year2021/day24/binary.txt new file mode 100644 index 0000000..b5b5961 --- /dev/null +++ b/src/year2021/day24/binary.txt @@ -0,0 +1,11 @@ +inp w +add z w +mod z 2 +div w 2 +add y w +mod y 2 +div w 2 +add x w +mod x 2 +div w 2 +mod w 2 \ No newline at end of file diff --git a/src/year2021/day24/negate.txt b/src/year2021/day24/negate.txt new file mode 100644 index 0000000..10afe48 --- /dev/null +++ b/src/year2021/day24/negate.txt @@ -0,0 +1,2 @@ +inp x +mul x -1 \ No newline at end of file diff --git a/src/year2021/day24/three_times.txt b/src/year2021/day24/three_times.txt new file mode 100644 index 0000000..95b52cf --- /dev/null +++ b/src/year2021/day24/three_times.txt @@ -0,0 +1,4 @@ +inp z +inp x +mul z 3 +eql z x \ No newline at end of file