2

I am new here and I am somehow stuck. I created an recursive algorithm that uses an global variable for remembering the Position he made the recursive call and I am trying to get rid of this variable as for me it seems to be not a good solution.

Is there any chance to get rid of this global variable? I cannot adjust the method-head so therefore the Interface of the method is fixed.

Here you can see my Code:

static int pos = -1;
static boolean writeInfix(char[] expr) {
    boolean result;
    pos++;
    int printpos = pos;
    if(expr[pos]=='+'||expr[pos]=='-'||expr[pos]=='/'||expr[pos]=='*'){
        System.out.print("(");
        writeInfix(expr);
        System.out.print(expr[printpos]);
        result = writeInfix(expr);
        System.out.print(")");
        return result;
    }else if(expr[pos] >= 'a' && expr[pos] <= 'z'){
        System.out.print(expr[pos]);
        return true;
    }else{
        return false;
    }
}

Thank you for your help :)

1
  • Thank you for your help! :) Commented May 26, 2017 at 15:59

3 Answers 3

2

You can add a new auxiliary method, where you control its variables, and let writeInfix(char[]) be only a wrapper, that does nothing but calling the "real" method.

In this new method, pos is an arument.

  • This also ensures you can call your API method (writeInfix) twice (independently) without worrying from the side effects (pos is initialized with wrong value after first call).
Sign up to request clarification or add additional context in comments.

Comments

0

You should be able to write another method with the position as additional argument:

private static boolean writeInfix(char[] expr, int pos) {
    boolean result;
    int printpos = pos;
    if(expr[pos]=='+'||expr[pos]=='-'||expr[pos]=='/'||expr[pos]=='*'){
        System.out.print("(");
        writeInfix(expr);
        System.out.print(expr[printpos]);
        result = writeInfix(expr, pos + 1);
        System.out.print(")");
        return result;
    }else if(expr[pos] >= 'a' && expr[pos] <= 'z'){
        System.out.print(expr[pos]);
        return true;
    }else{
        return false;
    }
}

and in the method you already have, you just need to call

static boolean writeInfix(char[] expr) {
    return writeInfix(expr, -1);
}

Comments

0

You can add pos as an argument to the writeInfix function.

static boolean writeInfix(char[] expr, int pos);

Whereever you are returning false, return -1. Whereever you are returning true, return the current pos value.

Comments

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.