day8_pt1.java (2816B)
1 import java.nio.file.Files; 2 import java.nio.file.Path; 3 import java.io.IOException; 4 import java.io.BufferedReader; 5 import java.io.StringReader; 6 import java.util.Arrays; 7 import java.util.List; 8 import java.util.HashMap; 9 import java.util.HashSet; 10 import java.util.ArrayList; 11 12 public class day8_pt1 { 13 record Point(int x, int y) {} 14 15 public static void main(String[] args) throws IOException { 16 var input = Files.readString(Path.of(args[0])); 17 var grid = new BufferedReader(new StringReader(input)) 18 .lines() 19 .toList(); 20 // Just gonna do this the naïve way 21 // First pass get the sets of antennas 22 23 var height = grid.size(); 24 var width = grid.getFirst().length(); 25 var antennas = new HashMap<Character, ArrayList<Point>>(); 26 for (var x = 0; x < width; x++) { 27 for (var y = 0; y < height; y++) { 28 var ch = grid.get(y).charAt(x); 29 if (ch != '.') { 30 var al = antennas.computeIfAbsent(ch, ignored -> new ArrayList<>()); 31 al.add(new Point(x, y)); 32 } 33 } 34 } 35 //System.out.printf("antennas = %s\n", antennas); 36 // Second pass calculate the distance to each antenna and check if we're an antinode 37 var ans = new HashSet<Point>(); 38 var antss = antennas.values(); 39 for (var x = 0; x < width; x++) { 40 for (var y = 0; y < height; y++) { 41 var pt = new Point(x, y); 42 for (var ants: antss) { 43 if (isAn(ants, pt)) { 44 ans.add(pt); 45 break; // no need to test other antenna sets 46 } 47 } 48 } 49 } 50 51 // for (var y = 0; y < height; y++) { 52 // for (var x = 0; x < width; x++) { 53 // if (ans.contains(new Point(x, y))) { 54 // System.out.print('#'); 55 // } else { 56 // System.out.print(grid.get(y).charAt(x)); 57 // } 58 // } 59 // System.out.print('\n'); 60 // } 61 System.out.printf("day8, pt1 = %d\n", ans.size()); 62 } 63 64 static boolean isAn(List<Point> ants, Point pt) { 65 for (var i=0; i<ants.size(); i++) { 66 for (var j=0; j<ants.size(); j++) { 67 if (i == j) continue; 68 var ant1 = ants.get(i); 69 var ant2 = ants.get(j); 70 // are we perfectly in line, AND twice the distance? 71 // y distance has to be exactly twice and so does x distance 72 // and signs have to be right (either in same or opposing quadrants) 73 var d1x = ant1.x - pt.x; 74 var d1y = ant1.y - pt.y; 75 var d2x = ant2.x - pt.x; 76 var d2y = ant2.y - pt.y; 77 var s1 = sig(d1x) * sig(d1y); 78 var s2 = sig(d2x) * sig(d2y); 79 if (Math.abs(d1y) == 2 * Math.abs(d2y) && 80 Math.abs(d1x) == 2 * Math.abs(d2x) && 81 s1 == s2) { 82 return true; 83 } 84 } 85 } 86 return false; 87 } 88 static int sig(int x) { 89 return x >= 0 ? 1 : -1; 90 } 91 }