From 6e5bb0fffe03669f0d27eeb6fb5be93f9854a5fd Mon Sep 17 00:00:00 2001 From: Paul-Henri Froidmont Date: Wed, 6 Dec 2023 14:45:03 +0100 Subject: [PATCH] Day 06 --- input/day06 | 2 ++ src/day06.scala | 50 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 input/day06 create mode 100644 src/day06.scala diff --git a/input/day06 b/input/day06 new file mode 100644 index 0000000..8aee466 --- /dev/null +++ b/input/day06 @@ -0,0 +1,2 @@ +Time: 61 67 75 71 +Distance: 430 1036 1307 1150 diff --git a/src/day06.scala b/src/day06.scala new file mode 100644 index 0000000..91e18a1 --- /dev/null +++ b/src/day06.scala @@ -0,0 +1,50 @@ +package aoc +package day06 + +val dayNumber = "06" + +@main def part1: Unit = + println(part1(loadInput(dayNumber))) + +@main def part2: Unit = + println(part2(loadInput(dayNumber))) + +def part1(input: String) = + val Array(times, distances) = input + .split("\n") + .map(_.dropWhile(_ != ' ').trim.split("""\W+""").map(_.toInt)) + + times + .zip(distances) + .map((time, distanceToBeat) => + for + pushDuration <- (0 to time) + distance = (time - pushDuration) * pushDuration + if distance > distanceToBeat + yield pushDuration + ) + .map(_.length) + .product + .toString + +def part2(input: String) = + + val Array(time, distance) = input + .split("\n") + .map(_.replaceAll(" ", "").dropWhile(!_.isDigit).toDouble) + + // We are looking for x such that + // d < (t - x) * t + // Which is + // x² - t * x + d > 0 + // This is a parabola and we need to find its roots + val disc = Math.sqrt(time * time - 4 * distance) + val root1 = time / 2 - disc / 2 + val root2 = time / 2 + disc / 2 + + // Count integers between roots + val int1 = root1.ceil.toLong + val res1 = if int1 == root1 then int1 + 1 else int1 + val int2 = root2.floor.toLong + val res2 = if int2 == root2 then int2 - 1 else int2 + (res2 - res1 + 1L).toString