Explore Courses Blog Tutorials Interview Questions
0 votes
in AI and Deep Learning by (50.2k points)

For a C# AI program, I use a recursive call to find the best next move (using a 30x30 Array to store the current board state). For each move I make, I want to see which of the possible moves I can make from the new board state will be best... and so on until I either reach an "end of game" position (no further moves possible in that state) or a timer stops the process and no further recursive calls are made (and the "best" known position is returned). This just to explain why I must use recursion (it is not tail recursion) and I cannot use a single (global) board state but must search all board states possible from the current state.

(Sometimes) I get a System.StackOverflowException. Is there a way to check the available stack space before the next recursive call? Then I could just return the current state as a "best position found so far" and not make the next recursive call. I.e. when the available stack becomes too small it should also count as a base case.

The other option, of course, may be to just put each recursive call in a try..catch block and handle the System.StackOverflowException by using it as a base case?

1 Answer

0 votes
by (108k points)

A StackOverflow is a sign of a bug or bad (C#) code. You need an insane amount of recursive calls to trigger a StackOverflow. Use a functional language supporting tail-calls, like F#, if you really want to do it this way. C# is not designed for it.

If you really want to go down that path you can use the EnsureSufficientExecutionstack method. When the stack is not large enough according to this method then it will throw an InsufficientExecutionStackException exception that you can catch.

If you want to learn C# Artificial Intelligence Programming then visit this Artificial Intelligence Course.

Browse Categories