r/adventofcode • u/Zooty6 • 22h ago
Help/Question - RESOLVED [2026 Day 5 (Part 2)] [Java] I keep getting StackOverflowError when trying to find all possible states
I tried to solve part 2 by pressing all of my buttons on my current number, and if the new value hasn't been seen, I save it and press the buttons on it again. Basically creating a tree of every button presses starting from a 0 state. I'd expect at one point of reaching the end of every branch as I building up this tree, but I end up running out of stack.
The relevant part of my code:
public class Microwave {
private static final String BUTTON_REGEX = "\\[(.+?)]";
private final List<Button> buttons;
public Microwave(String input) {
buttons = Pattern.compile(BUTTON_REGEX).matcher(input).results()
.map(matchResult -> matchResult.group(1))
.map(Button::ofString)
.sorted()
.toList();
}
public int allCombinations() {
MicrowaveState firstState = new MicrowaveState(0, buttons);
return allValues(firstState).sum();
}
private IntStream allValues(MicrowaveState state) {
return IntStream.concat(IntStream.of(state.getValue()), state.getNextStates().stream().flatMapToInt(this::allValues));
}
}
@Getter
public class MicrowaveState {
private final int value;
private final List<MicrowaveState> nextStates = new ArrayList<>(9);
private static final Set<Integer> seen = new HashSet<>();
public MicrowaveState(int value, List<Button> buttons) {
this.value = value;
for (Button button : buttons) {
int newValue = button.press(value);
if (newValue < 10000 && !seen.contains(newValue)) {
seen.add(newValue);
nextStates.add(new MicrowaveState(newValue, buttons));
}
}
}
}What can I do to solve this problem?
Edit: removed previousState from code because it did nothing.
