day14_pt1.java (2657B)
1 import java.nio.file.Files; 2 import java.nio.file.Path; 3 import java.io.IOException; 4 import java.util.*; 5 import java.util.stream.*; 6 import java.util.regex.*; 7 8 class day14_pt1 { 9 static final Pattern P = Pattern.compile("p=(-?\\d+),(-?\\d+) v=(-?\\d+),(-?\\d+)"); 10 record Point(int x, int y) { 11 Point add(Vec v, int width, int height) { 12 var nx = (this.x + v.x) % width; 13 if (nx < 0) { 14 nx += width; 15 } 16 var ny = (this.y + v.y) % height; 17 if (ny < 0) { 18 ny += height; 19 } 20 return new Point(nx, ny); 21 } 22 } 23 record Vec(int x, int y) {} 24 record Robot(int label, Vec velocity) {} 25 public static void main(String[] args) throws IOException { 26 var lines = Files.readAllLines(Path.of(args[0])); 27 var width = 101; 28 var height = 103; 29 var robots = new ArrayList<Robot>(); 30 var positions = new ArrayList<Point>(); 31 for (var ix=0; ix<lines.size(); ix++) { 32 var line = lines.get(ix); 33 var m = P.matcher(line); 34 if (!m.matches()) throw new RuntimeException("line didn't match [%s]".formatted(line)); 35 var px = Integer.parseInt(m.group(1)); 36 var py = Integer.parseInt(m.group(2)); 37 var dx = Integer.parseInt(m.group(3)); 38 var dy = Integer.parseInt(m.group(4)); 39 robots.add(new Robot(ix, new Vec(dx, dy))); 40 positions.add(new Point(px, py)); 41 } 42 // System.out.println(robots); 43 // System.out.println(positions); 44 for (var secs = 0; secs<100; secs++) { 45 for (var ix=0; ix<robots.size(); ix++) { 46 var robot = robots.get(ix); 47 var p = positions.get(ix); 48 var p2 = p.add(robot.velocity, width, height); 49 positions.set(ix, p2); 50 } 51 } 52 53 var cts = positions.stream().collect(Collectors.toMap(p -> p, p -> 1, (i1, i2) -> i1 + i2)); 54 // debug 55 for (var y=0; y<height; y++) { 56 for (var x=0; x<width; x++) { 57 var ct = cts.get(new Point(x, y)); 58 if (ct != null) { 59 System.out.printf("%d", ct); 60 } else { 61 System.out.print("."); 62 } 63 } 64 System.out.print("\n"); 65 } 66 var quads = new int[][]{ 67 new int[]{0, 0, width/2, height/2}, 68 new int[]{width/2+1, 0, width, height/2}, 69 new int[]{0, height/2+1, width/2, height}, 70 new int[]{width/2+1, height/2+1, width, height}, 71 }; 72 var res = Arrays.stream(quads).mapToLong(quad -> { 73 var sum = 0l; 74 for (var y=quad[1]; y< quad[3]; y++) { 75 for (var x=quad[0]; x<quad[2]; x++) { 76 sum += cts.getOrDefault(new Point(x, y), 0); 77 } 78 } 79 return sum; 80 }).reduce(1, (a, b) -> a * b); 81 System.out.printf("Day 14 pt1: %d\n", res); 82 } 83 }