Advertisement
Guest User

Untitled

a guest
Dec 10th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. package adventofcode;
  2.  
  3. import adventofcode.utils.Utils;
  4. import java.awt.Point;
  5. import java.util.ArrayList;
  6. import java.util.HashMap;
  7. import java.util.HashSet;
  8. import java.util.List;
  9. import java.util.Map;
  10. import java.util.Set;
  11.  
  12. public class Day10 {
  13.     public static void solve() {
  14.         List<String> input = Utils.getInput(10);
  15.  
  16.         char[][] map = input.stream().map(String::toCharArray).toArray(char[][]::new);
  17.  
  18.         List<Point> points = new ArrayList<>();
  19.         for(int y = 0 ; y < map.length ; y++) {
  20.             for(int x = 0 ; x < map[y].length ; x++) {
  21.                 if(map[y][x] == '#') {
  22.                     points.add(new Point(x, y));
  23.                 }
  24.             }
  25.         }
  26.  
  27.         Map<Point, Set<Point>> visibleAsteroids = new HashMap<>();
  28.  
  29.         for(Point point : points) {
  30.             visibleAsteroids.put(point, new HashSet<>());
  31.             for(Point other : points) {
  32.                 if(point == other) {
  33.                     continue;
  34.                 }
  35.  
  36.                 int dx = other.x - point.x;
  37.                 int dy = other.y - point.y;
  38.                 int gcd = gcd(dx, dy);
  39.                 visibleAsteroids.get(point).add(new Point(dx / gcd, dy / gcd));
  40.             }
  41.         }
  42.  
  43.         int mostVisible = visibleAsteroids.values().stream()
  44.                 .mapToInt(Set::size)
  45.                 .max().getAsInt();
  46.  
  47.         System.out.println(mostVisible);
  48.     }
  49.  
  50.     private static int gcd(int a, int b) {
  51.         if(a < 0) return gcd(-a, b);
  52.         if(b < 0) return gcd(a, -b);
  53.         if(a == b) return a;
  54.         if(a == 0) return b;
  55.         if(b == 0) return a;
  56.         if((a & 1) == 0 && (b & 1) == 0) return gcd(a >> 1, b >> 1) << 1;
  57.         if((a & 1) == 0) return gcd(a >> 1, b);
  58.         if((b & 1) == 0) return gcd(a, b >> 1);
  59.         if(a > b) return gcd((a - b) >> 1, b);
  60.         return gcd((b - a) >> 1, a);
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement