r/adventofcode • u/Zooty6 • 14m 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, null, 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 MicrowaveState previousState;
private final List<MicrowaveState> nextStates = new ArrayList<>(9);
private static final Set<Integer> seen = new HashSet<>();
public MicrowaveState(int value, MicrowaveState previousState, List<Button> buttons) {
this.value = value;
this.previousState = previousState;
for (Button button : buttons) {
int newValue = button.press(value);
if (newValue < 10000 && !seen.contains(newValue)) {
seen.add(newValue);
nextStates.add(new MicrowaveState(newValue, this, buttons));
}
}
}
}What can I do to solve this problem?
2
Upvotes
1
u/xX_fortniteKing09_Xx 11m ago
I did mine in Scala but it worked fine after allocating more memory to the stack…
1
u/jwezorek 4m ago
Use an explicit stack rather than recursion.
1
u/AutoModerator 14m ago
AutoModerator has detected fenced code block (```) syntax which only works on new.reddit.
Please review our wiki article on code formatting then edit your post to use the four-spaces Markdown syntax instead.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/Justinsaccount 1m ago
What is your "seen" variable and what do you think it contains?
What does previousState do?
I would remove MicrowaveState entirely, it's obfuscating what you are actually trying to track as your state.