This commit is contained in:
parent
8f47a462df
commit
9e3e1adeaa
45
day07.kts
Executable file
45
day07.kts
Executable file
@ -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<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
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user