aoc_2024/day07.kts
Logiar 9e3e1adeaa
All checks were successful
Solve / example-action (push) Successful in 2m31s
Day 7!
2024-12-07 16:54:30 +01:00

46 lines
1.4 KiB
Kotlin
Executable File

#!/usr/bin/env kotlin
import java.util.Scanner
val scanner = Scanner(System.`in`)
var total = 0L
var totalTwo = 0L
val operations = listOf("*", "+")
while (scanner.hasNext()) {
val line = scanner.nextLine()
val (targetString, rest) = line.split(":", limit = 2).map { it.trim() }
val target = targetString.toLong()
val values = rest.split(Regex("""\s+""")).map { it.toLong() }
if (hitsTarget(target, values, operations)) {
total += target
totalTwo += target
} else if (hitsTarget(target, values, listOf("||") + operations)) {
totalTwo += target
}
}
println("Total result: $total")
println("Total result (part 2): $totalTwo")
fun hitsTarget(target: Long, values: List<Long>, operations: List<String>): Boolean {
if (values.size == 1) {
return target == values[0]
}
val (operandOne, operandTwo) = values.take(2)
if (operandOne > target) {
return false
}
val rest = values.drop(2)
for (op in operations) {
val result = when (op) {
"+" -> operandOne + operandTwo
"*" -> operandOne * operandTwo
"||" -> "$operandOne$operandTwo".toLong()
else -> throw IllegalArgumentException("Unknown operation: $op")
}
if (hitsTarget(target, listOf(result) + rest, operations)) {
return true
}
}
return false
}