0

I get a stack overflow error due to my recursion creating an infinite loop. Turning the method into an iteration would stop this, but I have no idea how!

Can anyone guide me in turning my recursion into a loop?

private int findEmpty(int startPos, int stepNum, String key) {
    if (arr[startPos] == null) {
        return startPos;
    }
    return findEmpty(getNextLocation(startPos, ++stepNum, key), stepNum, key);
}

It is specifically return findEmpty(getNextLocation(startPos, ++stepNum, key), stepNum, key); that causes the error!

5
  • 2
    If your recursive code recurses infinitely, so will an iterative version of it. Commented Nov 29, 2020 at 23:12
  • I suspect the problem is actually with getNextLocation, so we can't diagnose the problem without seeing that code. I suspect the following is not your problem, but it also looks like you're using ++stepNum in a way you don't expect; the way you have it, stepNum is the same at every iteration and is stepNum+1 inside of getNextLocation. Commented Nov 30, 2020 at 0:09
  • You asked an almost-identical question yesterday. It isn't even closed. Why did you abandon that question and ask this one? Commented Nov 30, 2020 at 17:15
  • edits must not invalidate existing answers. ask new, followup question with link to this one if needed! specifically, your revision 3 is a great candidate; it would attract specific answers no doubt. the newer revisions ask about completely different code, so merit yet another separate post. :) Commented Dec 1, 2020 at 14:35
  • 1
    I see, thanks! @WillNess Commented Dec 1, 2020 at 22:53

1 Answer 1

3

Your recursive call is in tail position. Thus it already describes a loop. Just need to make it explicit, syntactically:

private int findEmpty(int startPos, int stepNum, String key) {
  while( True ) 
  {
    if (arr[startPos] == null) {
        return startPos;
    }
    // return findEmpty(getNextLocation(startPos, ++stepNum, key), stepNum, key);
    ++stepNum;
    int nextPos = getNextLocation(startPos, stepNum, key);
    // return findEmpty(nextPos, stepNum, key);
    startPos = nextPos;
  }
}

I don't code in Java. If the above code is non-compliant in any way, please regard it as a pseudocode and change into something suitable.

Sign up to request clarification or add additional context in comments.

1 Comment

It's okay, though it is non-idiomatic to mutate the arguments of a function. However, this could easily circumvented by moving the values into auxiliary variables before the loop starts and then mutating those.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.