aoc2024

Advent of Code 2024
Log | Files | Refs | README

commit 1caf5cea2cc5120fd45f78b483398777c8227c2e
parent 961570ce442e0d98a9fe1e6a1966354d7096ea07
Author: Martin Ashby <martin@ashbysoft.com>
Date:   Tue, 31 Dec 2024 21:25:36 +0000

Day 10 pt2

Diffstat:
Asrc/main/java/day10_pt2.java | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 53 insertions(+), 0 deletions(-)

diff --git a/src/main/java/day10_pt2.java b/src/main/java/day10_pt2.java @@ -0,0 +1,53 @@ +import java.nio.file.Files; +import java.nio.file.Path; +import java.io.IOException; +import java.util.*; +import java.util.stream.*; + +public class day10_pt2 { + record Point(int x, int y) { + Point add(Vec v) { + return new Point(this.x + v.x, this.y + v.y); + } + } + record Vec(int x, int y) {} + private static final Vec[] DIRS = new Vec[]{new Vec( 0, 1), + new Vec( 1, 0), + new Vec( 0,-1), + new Vec(-1, 0)}; + public static void main(String[] args) throws IOException { + var grid = Files.readAllLines(Path.of(args[0])); + var trailheads = new ArrayList<Point>(); + var height = grid.size(); + var width = grid.get(0).length(); + // pass 1 find trailheads + for (int y=0; y<height; y++) { + for (int x=0; x<width; x++) { + var val = gv(grid, new Point(x, y)); + if (val == 0) { + trailheads.add(new Point(x, y)); + } + } + } + var res = trailheads.stream().mapToInt(th -> rating(grid, th)).sum(); + System.out.printf("Day 10, pt2: %d\n", res); + } + + static int gv(List<String> grid, Point p) { + if (p.y < 0 || p.y >= grid.size()) return -1; + if (p.x < 0 || p.x >= grid.get(0).length()) return -1; + return grid.get(p.y).charAt(p.x) - '0'; + } + + static int rating(List<String> grid, Point p) { + var val = gv(grid, p); + if (val == 9) { + return 1; + } else { + return Arrays.stream(DIRS) + .filter(d -> gv(grid, p.add(d)) == val+1) + .mapToInt(d -> rating(grid, p.add(d))) + .sum(); + } + } +}