commit f89b18893aa320fc76f036d542aea31bb12b3fd7
parent efd500459462d87f5df89c3b0479a5356f8aa90d
Author: Martin Ashby <martin@ashbysoft.com>
Date: Thu, 2 Jan 2025 21:44:20 +0000
Day 14 pt2
Diffstat:
1 file changed, 72 insertions(+), 0 deletions(-)
diff --git a/src/main/java/day14_pt2.java b/src/main/java/day14_pt2.java
@@ -0,0 +1,72 @@
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.io.IOException;
+import java.util.*;
+import java.util.stream.*;
+import java.util.regex.*;
+
+class day14_pt2 {
+ static final Pattern P = Pattern.compile("p=(-?\\d+),(-?\\d+) v=(-?\\d+),(-?\\d+)");
+ record Point(int x, int y) {
+ Point add(Vec v, int width, int height) {
+ var nx = (this.x + v.x) % width;
+ if (nx < 0) {
+ nx += width;
+ }
+ var ny = (this.y + v.y) % height;
+ if (ny < 0) {
+ ny += height;
+ }
+ return new Point(nx, ny);
+ }
+ }
+ record Vec(int x, int y) {}
+ record Robot(int label, Vec velocity) {}
+ public static void main(String[] args) throws IOException, InterruptedException {
+ var lines = Files.readAllLines(Path.of(args[0]));
+ var width = 101;
+ var height = 103;
+ var robots = new ArrayList<Robot>();
+ var positions = new ArrayList<Point>();
+ for (var ix=0; ix<lines.size(); ix++) {
+ var line = lines.get(ix);
+ var m = P.matcher(line);
+ if (!m.matches()) throw new RuntimeException("line didn't match [%s]".formatted(line));
+ var px = Integer.parseInt(m.group(1));
+ var py = Integer.parseInt(m.group(2));
+ var dx = Integer.parseInt(m.group(3));
+ var dy = Integer.parseInt(m.group(4));
+ robots.add(new Robot(ix, new Vec(dx, dy)));
+ positions.add(new Point(px, py));
+ }
+ // System.out.println(robots);
+ // System.out.println(positions);
+ for (var secs = 0; true; secs++) {
+ for (var ix=0; ix<robots.size(); ix++) {
+ var robot = robots.get(ix);
+ var p = positions.get(ix);
+ var p2 = p.add(robot.velocity, width, height);
+ positions.set(ix, p2);
+ }
+ //Thread.sleep(300);
+ var cts = positions.stream().collect(Collectors.toMap(p -> p, p -> 1, (i1, i2) -> i1 + i2));
+ // debug
+ if (cts.values().stream().allMatch(x -> x == 1)) {
+ System.out.printf("secs: %d\n", secs+1);
+ for (var y=0; y<height; y++) {
+ for (var x=0; x<width; x++) {
+ var ct = cts.get(new Point(x, y));
+ if (ct != null) {
+ System.out.printf("%d", ct);
+ } else {
+ System.out.print(".");
+ }
+ }
+ System.out.print("\n");
+ }
+ System.out.printf("Day 14 pt1: %d\n", secs+1);
+ break;
+ }
+ }
+ }
+}