Guest User

Untitled

a guest
Dec 3rd, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 KB | None | 0 0
  1. package adventofcode;
  2.  
  3. import adventofcode.utils.Utils;
  4. import java.awt.Point;
  5. import java.util.HashMap;
  6. import java.util.List;
  7. import java.util.Map;
  8. import java.util.stream.Collectors;
  9.  
  10. public class Day3 {
  11.     public static void solve() {
  12.         List<String> input = Utils.getInput(3);
  13.  
  14.         Map<Point, Integer> wire1 = getAllLocations(input.get(0));
  15.         Map<Point, Integer> wire2 = getAllLocations(input.get(1));
  16.  
  17.         List<Point> intersections = wire1.keySet().stream()
  18.                 .filter(wire2::containsKey)
  19.                 .collect(Collectors.toList());
  20.  
  21.         int closest = intersections.stream()
  22.                 .mapToInt(e -> Math.abs(e.x) + Math.abs(e.y))
  23.                 .min().getAsInt();
  24.         int fastest = intersections.stream()
  25.                 .mapToInt(e -> wire1.get(e) + wire2.get(e))
  26.                 .min().getAsInt();
  27.  
  28.         System.out.println(closest);
  29.         System.out.println(fastest);
  30.     }
  31.  
  32.     private static Map<Point, Integer> getAllLocations(String wire) {
  33.         String[] route = wire.split(",");
  34.         Map<Point, Integer> locations = new HashMap<>();
  35.  
  36.         int x = 0;
  37.         int y = 0;
  38.         int steps = 0;
  39.  
  40.         for(String section : route) {
  41.             char direction = section.charAt(0);
  42.             int length = Integer.parseInt(section.substring(1));
  43.  
  44.             for(int i = 0 ; i < length ; i++) {
  45.                 switch(direction) {
  46.                     case 'U': y++; break;
  47.                     case 'R': x++; break;
  48.                     case 'D': y--; break;
  49.                     case 'L': x--; break;
  50.                     default: throw new IllegalStateException("HCF");
  51.                 }
  52.  
  53.                 steps++;
  54.                 locations.putIfAbsent(new Point(x, y), steps);
  55.             }
  56.         }
  57.  
  58.         return locations;
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment