Last active
December 21, 2022 06:22
-
-
Save saidaspen/4df20b1d262d49bc1c39e41139a33712 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import se.saidaspen.aoc.util.Day | |
import se.saidaspen.aoc.util.words | |
import kotlin.math.absoluteValue | |
import kotlin.math.max | |
fun main() = Dayxx.run() | |
object Dayxx : Day(2022, 21) { | |
var input2 = "root: pppw + sjmn\n" + | |
"dbpl: 5\n" + | |
"cczh: sllz + lgvd\n" + | |
"zczc: 2\n" + | |
"ptdq: humn - dvpt\n" + | |
"dvpt: 3\n" + | |
"lfqf: 4\n" + | |
"humn: 5\n" + | |
"ljgn: 2\n" + | |
"sjmn: drzm * dbpl\n" + | |
"sllz: 4\n" + | |
"pppw: cczh / lfqf\n" + | |
"lgvd: ljgn * ptdq\n" + | |
"drzm: hmdt - zczc\n" + | |
"hmdt: 32" | |
override fun part1(): Any { | |
val monkeys = input.lines().map { it.split(":").map { t -> t.trim() } }.associate { it[0] to it[1] } | |
return getValue(monkeys, "root") | |
} | |
private fun getValue(monkeys: Map<String, String>, m: String): Long { | |
val monkeyDo = monkeys[m]!! | |
return if (monkeyDo.toLongOrNull() != null) { | |
monkeyDo.toLong() | |
} else { | |
val (op1, oper, op2) = words(monkeyDo) | |
when (oper) { | |
"+" -> getValue(monkeys, op1) + getValue(monkeys, op2) | |
"-" -> getValue(monkeys, op1) - getValue(monkeys, op2) | |
"*" -> getValue(monkeys, op1) * getValue(monkeys, op2) | |
"/" -> getValue(monkeys, op1) / getValue(monkeys, op2) | |
else -> throw RuntimeException("Unsupported op") | |
} | |
} | |
} | |
override fun part2(): Any { | |
val monkeys: MutableMap<String, String> = | |
input.lines().map { it.split(":").map { t -> t.trim() } }.associate { it[0] to it[1] }.toMutableMap() | |
var currentGuess = 0L | |
var switch = false | |
var lastDiff = 0L | |
while (true) { | |
val dist = guess(monkeys, currentGuess) | |
if (dist.absoluteValue > lastDiff.absoluteValue && currentGuess != 0L) switch = !switch // Change direction if we are going in the wrong dir | |
if (dist == 0L) return currentGuess | |
println("guessed $currentGuess gave $dist") | |
var change = max(1, dist.absoluteValue / 2) | |
change *= if (switch) -1 else 1 | |
currentGuess += if (dist > 0) change else change * -1 | |
lastDiff = dist | |
} | |
} | |
private fun guess( | |
monkeys: MutableMap<String, String>, | |
currentGuess: Long, | |
): Long { | |
val (op1, _, op2) = words(monkeys["root"]!!) | |
monkeys["humn"] = currentGuess.toString() | |
return getValue(monkeys, op1) - getValue(monkeys, op2) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment