Skip to content

Commit

Permalink
AoC 2023 Day 6 - java - math refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
pareronia committed Dec 6, 2023
1 parent 2a665ae commit 7cd6bd1
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions src/main/java/AoC2023_06.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,25 @@ protected List<Race> parseInput(final List<String> 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<Race> 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();
}

Expand Down

0 comments on commit 7cd6bd1

Please sign in to comment.