As you try to figure out what to do next, you notice a poster on a wall near the ferry dock. “Boat races! Open to the public! Grand prize is an all-expenses-paid trip to Desert Island!” That must be where the sand comes from! Best of all, the boat races are starting in just a few minutes.
Solution in Java
Full source can be found: in GitHub
Part 1
1public void part1() {
2 var parsed = parseInput(inputLoader.string());
3
4 var totalWaysToWin = 1L;
5 for (var x = 0; x < parsed.get(0).length; x++) {
6 var time = parsed.get(0)[x];
7 var distance = parsed.get(1)[x];
8
9 var waysToWin = computeWaysToWin(time, distance);
10 LoggerFactory.getLogger(getClass()).debug("Time: {}, Distance: {}, Ways to win: {}", time, distance, waysToWin);
11 totalWaysToWin *= waysToWin;
12 }
13
14 validator.part1(totalWaysToWin);
15}
16
17private int computeWaysToWin(long time, long distance) {
18 var d = Math.sqrt(time * time - 4.0 * distance);
19 var min = Math.floor(.5 * (time - d)) + 1;
20 var max = Math.ceil(.5 * (time + d)) - 1;
21 return (int) (max - min + 1);
22}
23
24private List<Integer[]> parseInput(String input) {
25 var pattern = Pattern.compile("(\\d+)");
26
27 return input.lines()
28 .map(pattern::matcher)
29 .map(matcher -> {
30 var numbers = new ArrayList<Integer>();
31 while (matcher.find()) {
32 numbers.add(Integer.parseInt(matcher.group(1)));
33 }
34 return numbers.toArray(new Integer[0]);
35 })
36 .toList();
37}
Part 2
1public void part2() {
2 var lines = inputLoader.split("\n");
3 var time = lines[0].substring("Time:".length()).replaceAll("\\s", "");
4 var distance = lines[1].substring("Distance:".length()).replaceAll("\\s", "");
5
6 var answer = computeWaysToWin(Long.parseLong(time), Long.parseLong(distance));
7 validator.part2(answer);
8}