From 7cd6bd18f835114b52db622edceaefdb93acef08 Mon Sep 17 00:00:00 2001 From: pareronia <49491686+pareronia@users.noreply.github.com> Date: Wed, 6 Dec 2023 22:53:32 +0100 Subject: [PATCH] AoC 2023 Day 6 - java - math refactor --- src/main/java/AoC2023_06.java | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/main/java/AoC2023_06.java b/src/main/java/AoC2023_06.java index 2048e902..e3d805c4 100644 --- a/src/main/java/AoC2023_06.java +++ b/src/main/java/AoC2023_06.java @@ -41,11 +41,25 @@ protected List parseInput(final List inputs) { .toList(); } + @SuppressWarnings("unused") + private long bruteForce(final Race race) { + return LongStream.range(1, race.time()) + .filter(t -> t * (race.time() - t) > race.distance()) + .count(); + } + + private long equation(final Race race) { + final double r = Math.sqrt(Math.pow(race.time(), 2) - 4 * race.distance()); + final double fx1 = (race.time() - r) / 2d; + final double fx2 = (race.time() + r) / 2d; + final long x1 = fx1 - ((long) fx1) > 0 ? (long) Math.ceil(fx1) : ((long) fx1) + 1; + final long x2 = fx2 - ((long) fx2) > 0 ? (long) Math.floor(fx2) : ((long) fx2) - 1; + return x2 - x1 + 1; + } + private long solve(final List races) { return races.stream() - .mapToLong(r -> LongStream.range(1, r.time()) - .filter(t -> t * (r.time() - t) > r.distance()) - .count()) + .mapToLong(this::equation) .reduce((a, b) -> a * b).getAsLong(); }