Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ///usr/bin/env jbang "$0" "$@" ; exit $?
- //JAVAC_OPTIONS --enable-preview -source 17
- //JAVA_OPTIONS --enable-preview
- import static java.lang.System.*;
- import java.nio.file.Files;
- import java.nio.file.Paths;
- import java.util.function.Function;
- import java.util.stream.Stream;
- public class Day2 {
- static record Position(int h, int d, int a) {
- static Position move(Position position, Movement movement) {
- return switch (movement) {
- case Forward f -> new Position(position.h + f.value, position.d, 0);
- case Down d -> new Position(position.h, position.d + d.value, 0);
- case Up u -> new Position(position.h, position.d - u.value, 0);
- };
- }
- static Position aim(Position position, Movement movement) {
- return switch (movement) {
- case Forward f -> new Position(position.h + f.value, position.d + (position.a * f.value), position.a);
- case Down d -> new Position(position.h, position.d, position.a + d.value);
- case Up u -> new Position(position.h, position.d, position.a - u.value);
- };
- }
- static Position combine(Position l, Position r) {
- return new Position(l.h + r.h, l.d + r.d, l.a + r.a);
- }
- int multiplied() { return h * d;}
- };
- static sealed interface Movement permits Forward, Down, Up {
- int value();
- }
- static record Forward(int value) implements Movement {}
- static record Down(int value) implements Movement {}
- static record Up(int value) implements Movement{}
- static Stream<Movement> lines() {
- final Function<String, Movement> mapper = (s) -> {
- final String[] ss = s.split(" ");
- final String direction = ss[0];
- final int value = Integer.parseInt(ss[1]);
- return switch(direction) {
- case "forward" -> new Forward(value);
- case "down" -> new Down(value);
- case "up" -> new Up(value);
- default -> throw new RuntimeException();
- };
- };
- try {
- return Files.readAllLines(Paths.get("input.txt")).stream().map(mapper);
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- throw new RuntimeException();
- }
- static void part1() {
- final Position pos = lines().reduce(new Position(0, 0, 0), Position::move, Position::combine);
- out.println(pos.multiplied());
- }
- static void part2() {
- final Position pos = lines().reduce(new Position(0, 0, 0), Position::aim, Position::combine);
- out.println(pos.multiplied());
- }
- public static void main(String... args) {
- part1();
- part2();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement