Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ///usr/bin/env jbang "$0" "$@" ; exit $?
- import static java.lang.System.*;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- import java.util.Collections;
- import java.util.function.BiConsumer;
- import java.util.function.Consumer;
- import java.util.function.IntConsumer;
- import java.util.function.ToLongBiFunction;
- import java.util.stream.IntStream;
- public class Day1 {
- static class Mapper implements IntStream.IntMapMultiConsumer {
- private int last = -1;
- @Override
- public void accept(int t, IntConsumer u) {
- if (last >= 0 && t > last)
- u.accept(1);
- last = t;
- }
- }
- static record Window(int a, int b, int c) {
- int sum() {
- return a + b + c;
- }
- boolean isValid() {
- return a >= 0 && b >= 0 && c >= 0;
- }
- }
- static class Windower implements BiConsumer<Integer, Consumer<Window>> {
- private int a = -1;
- private int b = -1;
- private int c = -1;
- @Override
- public void accept(Integer t, Consumer<Window> u) {
- a = b;
- b = c;
- c = t;
- u.accept(new Window(a, b, c));
- }
- }
- static IntStream lines() {
- try {
- return Files.readAllLines(Paths.get("input.txt")).stream().mapToInt(Integer::parseInt);
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- throw new RuntimeException();
- }
- static void part1() {
- final Mapper mapper = new Mapper();
- final Integer sum = lines().mapMulti(mapper).sum();
- out.println("Part 1: " + sum);
- }
- static void part2() {
- final Mapper mapper = new Mapper();
- final Windower windower = new Windower();
- final Integer sum = lines()
- .boxed()
- .mapMulti(windower)
- .filter(Window::isValid)
- .mapToInt(Window::sum)
- .mapMulti(mapper)
- .sum();
- out.println("Part 2: " + sum);
- }
- public static void main(String... args) {
- part1();
- part2();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement