Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package adventofcode;
- import adventofcode.utils.Utils;
- import java.awt.Point;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.stream.Collectors;
- public class Day3 {
- public static void solve() {
- List<String> input = Utils.getInput(3);
- Map<Point, Integer> wire1 = getAllLocations(input.get(0));
- Map<Point, Integer> wire2 = getAllLocations(input.get(1));
- List<Point> intersections = wire1.keySet().stream()
- .filter(wire2::containsKey)
- .collect(Collectors.toList());
- int closest = intersections.stream()
- .mapToInt(e -> Math.abs(e.x) + Math.abs(e.y))
- .min().getAsInt();
- int fastest = intersections.stream()
- .mapToInt(e -> wire1.get(e) + wire2.get(e))
- .min().getAsInt();
- System.out.println(closest);
- System.out.println(fastest);
- }
- private static Map<Point, Integer> getAllLocations(String wire) {
- String[] route = wire.split(",");
- Map<Point, Integer> locations = new HashMap<>();
- int x = 0;
- int y = 0;
- int steps = 0;
- for(String section : route) {
- char direction = section.charAt(0);
- int length = Integer.parseInt(section.substring(1));
- for(int i = 0 ; i < length ; i++) {
- switch(direction) {
- case 'U': y++; break;
- case 'R': x++; break;
- case 'D': y--; break;
- case 'L': x--; break;
- default: throw new IllegalStateException("HCF");
- }
- steps++;
- locations.putIfAbsent(new Point(x, y), steps);
- }
- }
- return locations;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment