Advertisement
Guest User

Day3

a guest
Dec 14th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.96 KB | None | 0 0
  1. import java.awt.*;
  2. import java.io.File;
  3. import java.io.FileNotFoundException;
  4. import java.net.URL;
  5. import java.util.HashMap;
  6. import java.util.Scanner;
  7.  
  8. public class Day3 {
  9.     static HashMap<Point, Integer> wires = new HashMap<>();
  10.  
  11.     public static void main(String[] args) throws FileNotFoundException {
  12.         URL url = Day3.class.getResource("input");
  13.         File file = new File(url.getPath());
  14.         Scanner scanner = new Scanner(file);
  15.         String[] wire1 = scanner.nextLine().split(",");
  16.         String[] wire2 = scanner.nextLine().split(",");
  17.  
  18.         parseWire(wire1);
  19.         parseWire(wire2);
  20.        
  21.         int distance = Integer.MAX_VALUE;
  22.         for (Point crossing:
  23.              wires.keySet()) {
  24.             if (wires.get(crossing.getLocation()) > 1) {
  25.                 int calc = Math.abs(crossing.x) + Math.abs(crossing.y);
  26.                 if (calc < distance) {
  27.                     distance = calc;
  28.                 }
  29.             }
  30.         }
  31.  
  32.         System.out.println(distance);
  33.     }
  34.  
  35.     static void parseWire(String[] strings) {
  36.         Point current = new Point();
  37.         for (String command:
  38.              strings) {
  39.             char dir = command.charAt(0);
  40.             int len = Integer.parseInt(command.substring(1));
  41.             for (int i = 0; i < len; i++) {
  42.                 switch (dir) {
  43.                     case 'U': current.y++; break;
  44.                     case 'D': current.y--; break;
  45.                     case 'L': current.x--; break;
  46.                     case 'R': current.x++;
  47.                 }
  48.                 mapWirePoint(current.getLocation());
  49.             }
  50.         }
  51.     }
  52.  
  53.     static void mapWirePoint(Point current) {
  54.         if (wires.containsKey(current.getLocation())) {
  55.             int crossing = wires.get(current.getLocation());
  56.             crossing++;
  57.             wires.replace(current, crossing);
  58.         } else {
  59.             wires.put(current.getLocation(), 1);
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement