-4

This is a finite-state machine:

private int recursive(int rc, int pc, int sc) {
    for (;;) {
        Instruction actual = program[rc][pc];
        switch (actual.type) {
            case FIRST:
                if (sc >= input.length || input[sc] != actual.c1) return -1;
                pc++; sc++;
                continue;
            case SECOND:
                pc = actual.n1;
                continue;
            case THIRD:
                int result = recursive(rc, actual.n1, sc);
                if (result != -1) return result;
                pc = actual.n2;
                continue;
            case FOURTH:
                result = recursive(actual.n1, 0, sc);
                if (result == -1) return -1;
                pc++; sc = result;
                continue;
            case FIFTH:
                if (sc == input.length) return sc;
                return -1;
        }
        return -1;
    }
}

Thanks for helping.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501

1 Answers1

1

Think about recursion. When you invoke method recursively you actually call method and store somewhere the state of previous invocations of the same method. Where are you storing this state? The answer is "in stack." But when you are using recursive invocation the system manages stack for you.

So, you have to mange it yourself. This means the following. Create stack before the first method invocation. Change the signature of the method: it should accept the stack as a parameter. The stack should contain your state. Without examining your code it can be either primitive or complex object. If you need complex object create your own class State, that will hold all needed information.

I hope this is enough. Good luck!

AlexR
  • 114,158
  • 16
  • 130
  • 208