From 5e1aec76e4adfd3991a81d0f70e7561f327b08d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fredrik=20R=C3=B8dland?= Date: Sat, 7 Dec 2024 11:21:48 +0100 Subject: [PATCH] 2024 - Day 07 - refactored --- .../kotlin/no/rodland/advent_2024/Day07.kt | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/main/kotlin/no/rodland/advent_2024/Day07.kt b/src/main/kotlin/no/rodland/advent_2024/Day07.kt index f8118491..18395ce2 100644 --- a/src/main/kotlin/no/rodland/advent_2024/Day07.kt +++ b/src/main/kotlin/no/rodland/advent_2024/Day07.kt @@ -8,26 +8,27 @@ import no.rodland.advent.Day class Day07(val input: List) : Day>>> { private val parsed = input.parse() + private val operatorsPart1: List<(Long, Long) -> Long> = listOf(Long::plus, Long::times) + private val operatorsPart2 = operatorsPart1 + { l1, l2 -> "$l1$l2".toLong() } override fun partOne(): Long { - return parsed - .filter { canBeTrue(it.first, 0, it.second, listOf(Long::plus, Long::times)) } - .sumOf { it.first } + return solve(operatorsPart1) } override fun partTwo(): Long { - return parsed - .filter { canBeTrue(it.first, 0, it.second, listOf(Long::plus, Long::times, { l1, l2 -> "$l1$l2".toLong() })) } - .sumOf { it.first } + return solve(operatorsPart2) } + private fun solve(operators: List<(Long, Long) -> Long>) = parsed + .filter { canBeTrue(it.first, 0, it.second, operators) } + .sumOf { it.first } + private fun canBeTrue(sum: Long, acc: Long, values: List, operators: List<(Long, Long) -> Long>): Boolean { if (values.isEmpty()) return sum == acc - val next = values.first() - return operators.any { canBeTrue(sum, it.invoke(acc, next), values.drop(1), operators) } + return operators.any { canBeTrue(sum, it.invoke(acc, values.first()), values.drop(1), operators) } } - override fun List.parse(): List>> { + override fun List.parse(): List>> { return map { line -> line.substringBefore(":").toLong() to line.substringAfter(": ").split(" ").map { it.toLong() } }