package dev.forstenlechner.aoc; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class Day12 { public static void main(String[] args) throws Exception { new Day12().solve(); } private enum Orientation { N(0), E(1), S(2), W(3); int value; Orientation(int value) { this.value = value; } int getValue() { return value; } static Orientation from(int value) { return switch (value) { case 1 -> E; case 2 -> S; case 3 -> W; default -> N; }; } } private enum Instruction { N { @Override LocationFacing move(LocationFacing current, int value) { return new LocationFacing(current.east, current.north + value, current.orientation); } }, S { @Override LocationFacing move(LocationFacing current, int value) { return new LocationFacing(current.east, current.north - value, current.orientation); } }, E { @Override LocationFacing move(LocationFacing current, int value) { return new LocationFacing(current.east + value, current.north, current.orientation); } }, W { @Override LocationFacing move(LocationFacing current, int value) { return new LocationFacing(current.east - value, current.north, current.orientation); } }, L { @Override LocationFacing move(LocationFacing current, int value) { value = (value % 360) / 90; int newValue = (current.orientation.getValue() - value + 4) % 4; return new LocationFacing(current.east, current.north, Orientation.from(newValue)); } }, R { @Override LocationFacing move(LocationFacing current, int value) { value = (value % 360) / 90; int newValue = (current.orientation.getValue() + value + 4) % 4; return new LocationFacing(current.east, current.north, Orientation.from(newValue)); } }, F { @Override LocationFacing move(LocationFacing current, int value) { if (current.orientation == Orientation.N) { return N.move(current, value); } if (current.orientation == Orientation.S) { return S.move(current, value); } if (current.orientation == Orientation.E) { return E.move(current, value); } if (current.orientation == Orientation.W) { return W.move(current, value); } throw new IllegalArgumentException("not implemented"); } }; abstract LocationFacing move(LocationFacing current, int value); } private record NavigationInstruction(Instruction ins, int value) {}; private record LocationFacing(int east, int north, Orientation orientation) {}; private void solve() throws Exception { Stream lines = Files.lines(Paths.get("day12/input")); List navigationInstructions = lines .map(l -> new NavigationInstruction(Instruction.valueOf(l.substring(0, 1)), Integer.parseInt(l.substring(1)))) .collect(Collectors.toList()); LocationFacing result = navigationInstructions.stream().reduce(new LocationFacing(0, 0, Orientation.E), (l, n) -> { System.out.println(l); return n.ins().move(l, n.value()); }, (l1, l2) -> l1); System.out.println(Math.abs(result.east) + Math.abs(result.north)); // 5641 } }