diff --git a/day07.kts b/day07.kts new file mode 100755 index 0000000..1318507 --- /dev/null +++ b/day07.kts @@ -0,0 +1,45 @@ +#!/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, operations: List): 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 +}