|
1 | 1 | package org.ck.adventofcode.year2015; |
2 | 2 |
|
3 | 3 | import java.util.Scanner; |
4 | | -import java.util.function.IntBinaryOperator; |
5 | 4 | import java.util.function.IntPredicate; |
| 5 | +import java.util.function.ToIntFunction; |
| 6 | +import java.util.stream.Gatherer; |
6 | 7 | import org.ck.adventofcode.util.AOCSolution; |
7 | 8 | import org.ck.codechallengelib.annotation.Solution; |
8 | 9 |
|
|
19 | 20 | public class Day01 extends AOCSolution { |
20 | 21 | @Override |
21 | 22 | protected void runPartOne(final Scanner in) { |
22 | | - run(in, (floor) -> false, (floor, position) -> floor); |
| 23 | + run(in, _ -> true, state -> state.floor); |
23 | 24 | } |
24 | 25 |
|
25 | 26 | @Override |
26 | 27 | protected void runPartTwo(final Scanner in) { |
27 | | - run(in, (floor) -> floor < 0, (floor, position) -> position); |
| 28 | + run(in, floor -> floor >= 0, state -> state.position - 1); |
28 | 29 | } |
29 | 30 |
|
30 | 31 | private void run( |
31 | | - final Scanner in, final IntPredicate getBreakCondition, final IntBinaryOperator getResult) { |
32 | | - int floor = 0; |
33 | | - int position = 1; |
34 | | - |
35 | | - final String path = in.nextLine(); |
36 | | - |
37 | | - for (char command : path.toCharArray()) { |
38 | | - floor += command == '(' ? 1 : -1; |
| 32 | + final Scanner in, |
| 33 | + final IntPredicate getBreakCondition, |
| 34 | + final ToIntFunction<State> getResult) { |
| 35 | + in.nextLine() |
| 36 | + .chars() |
| 37 | + .boxed() |
| 38 | + .gather( |
| 39 | + Gatherer.ofSequential( |
| 40 | + () -> new State(0, 1), |
| 41 | + (state, element, _) -> { |
| 42 | + state.floor += element == '(' ? 1 : -1; |
| 43 | + state.position += 1; |
| 44 | + |
| 45 | + return getBreakCondition.test(state.floor); |
| 46 | + }, |
| 47 | + (state, downstream) -> downstream.push(getResult.applyAsInt(state)))) |
| 48 | + .forEach(this::print); |
| 49 | + } |
39 | 50 |
|
40 | | - if (getBreakCondition.test(floor)) { |
41 | | - break; |
42 | | - } |
| 51 | + private static final class State { |
| 52 | + private int floor; |
| 53 | + private int position; |
43 | 54 |
|
44 | | - ++position; |
| 55 | + public State(final int floor, final int position) { |
| 56 | + this.floor = floor; |
| 57 | + this.position = position; |
45 | 58 | } |
46 | | - |
47 | | - print(getResult.applyAsInt(floor, position)); |
48 | 59 | } |
49 | 60 | } |
0 commit comments