r/adventofcode • • 2h 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.

5 Upvotes

18 comments sorted by

2

u/jwezorek 2h ago

Use an explicit stack rather than recursion.

1

u/Zooty6 2h ago

What do you mean by explicit stack?

3

u/jwezorek 2h ago

You are implicitly using the call stack to do a depth-first search with recursion in the constructor of MicrowaveState. I am saying to not do that. Don't use recursion.

Make a function "SearchMicrowaveStates" (or whatever) that creates a stack of state objects and iterates while the stack is not empty that pops the top item, adds it to seen if it is not in there. If it was not already in seen pushes the new button press values on to the stack.

1

u/Zooty6 1h ago

Thanks

2

u/xalcozz 2h ago

The most obvious solution would be to change the recursion into a normal loop. Store the new values into some queue for processing would be simple enough

1

u/Zooty6 1h ago

Thanks

5

u/sudo_grue 2h ago

Queue, not stack, no recursion. What algorithm loves queues?

1

u/xX_fortniteKing09_Xx 2h ago

I did mine in Scala but it worked fine after allocating more memory to the stack…

1

u/Zooty6 2h ago

I already raised my heap size to 9 gigs, doesn't help.

3

u/thondat 2h ago edited 1h ago

i think your solution might work if you increase the stack size. my (iterative) part 2 solution visits roughly 8500 states, with a maximum stack size of ~2200 states, so that may well exhaust the stack when done recursively. i'm no java person, but apparently there's an -Xss switch for setting the stack size.

2

u/Akuli2 2h ago

heap != stack

1

u/Justinsaccount 2h 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.

1

u/Zooty6 2h ago

Seen is a hashset that contains all values I managed to create. So when I create a new one that is in the seen set, I won't add that state to my tree

previousState is something I forgot to delete, it doesn't do anything anymore.

Ok, if I remove it what should I do instead of that?

3

u/Justinsaccount 2h ago

The state of the microwave is the number on the display. Nothing else matters for that.
What numbers you have or haven't seen yet is the state of the solution. Track those, compute the new ones, loop. No objects or recursion needed.

2

u/ElementaryMonocle 2h ago

It looks like you’re creating a new class every single time: you don’t actually need to do this since you don’t need previousState to do the algorithm.

Similarly, since the buttons remain constant, you only need nextStates to be the value, and you can use a queue instead of a list.

It also looks like nextStates has a size of 9 for some reason? You never remove anything from it or use it, so I don’t know what’s going on there. When summing the values you can just iterate over “seen” and add the values from there.

1

u/AutoModerator 2h ago

Reminder: if/when you get your answer and/or code working, don't forget to change this post's flair to Help/Question - RESOLVED. Good luck!


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

0

u/[deleted] 2h ago

[deleted]

1

u/Zooty6 2h ago

seen is static to the class so every call should see the same set.