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.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.stream.Collectors;
- public class Day3 {
- private static final List<Map<Point, Integer>> STEPS_TO_POINT = new ArrayList<>();
- public static void solve() {
- List<String> input = Utils.getInput(3);
- List<Point> wire1 = getAllLocations(0, input.get(0));
- List<Point> wire2 = getAllLocations(1, input.get(1));
- List<Point> intersections = wire1.stream()
- .filter(wire2::contains)
- .collect(Collectors.toList());
- int closest = intersections.stream()
- .mapToInt(Day3::manhattanDistanceFromOrigin)
- .min().getAsInt();
- int fastest = intersections.stream()
- .mapToInt(Day3::combinedStepsToPoint)
- .min().getAsInt();
- System.out.println(closest);
- System.out.println(fastest);
- }
- private static List<Point> getAllLocations(int n, String wire) {
- String[] route = wire.split(",");
- List<Point> locations = new ArrayList<>();
- STEPS_TO_POINT.add(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++;
- Point point = new Point(x, y);
- locations.add(point);
- if(!STEPS_TO_POINT.get(n).containsKey(point)) {
- STEPS_TO_POINT.get(n).put(point, steps);
- }
- }
- }
- return locations;
- }
- private static int manhattanDistanceFromOrigin(Point point) {
- return Math.abs(point.x) + Math.abs(point.y);
- }
- private static int combinedStepsToPoint(Point point) {
- return STEPS_TO_POINT.get(0).get(point) + STEPS_TO_POINT.get(1).get(point);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment