From f3b014b06c57ff9ba016fe130223a1dd8f7cd519 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 7 Dec 2021 13:22:17 +0100 Subject: [PATCH] day(07): remove brute force Signed-off-by: Matej Focko --- src/day07/Day07.kt | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/day07/Day07.kt b/src/day07/Day07.kt index 6215c40..09400d6 100644 --- a/src/day07/Day07.kt +++ b/src/day07/Day07.kt @@ -10,10 +10,12 @@ fun part1(input: List): Int = input.toSet().minOf { target -> } } -fun part2(input: List): Int = (input.minOrNull()!!..input.maxOrNull()!!).minOf { target -> - input.sumOf { - val diff = (it - target).absoluteValue - diff * (diff + 1) / 2 +fun part2(input: List): Int = (input.average().toInt()).let { average -> + (average - 1..average + 1).minOf { target -> + input.sumOf { + val diff = (it - target).absoluteValue + diff * (diff + 1) / 2 + } } }