2
\$\begingroup\$

Here is the description of the problem.

Write a simple interpreter which understands "+", "-", and "*" operations. Apply the operations in order using command/arg pairs starting with the initial value of value. If you encounter an unknown command, return -1.

Example:
interpret(1, ["+"], [1]) → 2
interpret(4, ["-"], [2]) → 2
interpret(1, ["+", "*"], [1, 3]) → 6

I'm trying to implement this function using recursion. Here is my implementation.

public int interpret(int value, String[] commands, int[] args) {
  // base case
  if (commands.length == 0 && args.length == 0) {
    return value;
  }

  // Get top command and arg to calculate value
  final String cmd = commands[0];
  final int arg = args[0];

  // Construct remaining commands and args for recursion
  final int[] remainArgs 
          = Arrays.copyOfRange(args, 1, args.length);
  final String[] remainCommands 
          = Arrays.copyOfRange(commands, 1, commands.length);

  switch (cmd) {
    case "*":
      return interpret(value * arg, remainCommands, remainArgs);
    case "+":
      return interpret(value + arg, remainCommands, remainArgs);
    case "-":
      return interpret(value - arg, remainCommands, remainArgs);
    default:
      // unknown command return -1
      return -1;
  }
}

Please comment on my implementation in regarding to code readability and efficiency. Please also share your implementation if you have a better idea. Thanks.

\$\endgroup\$
0

1 Answer 1

3
\$\begingroup\$

You don't need to use recursion here, commands and args array have the same size you can simply loop through it.

long result=value;
for (int i=0; i<commands.length;i++) {
   result = calc(result, commands[i], args[i]);
}

And you need to check size of arrays before use, to prevent ArrayIndexOutOfBoundsException

if (commands.length != args.length)
    return -1;

P.S. You work with int, but result can be larger than Integer.MAX_VALUE, therefore use long type for result

\$\endgroup\$
2
  • \$\begingroup\$ What if the result is larger than Long.MAX_VALUE? \$\endgroup\$
    – RoToRa
    Nov 6, 2019 at 8:59
  • 1
    \$\begingroup\$ @RoToRa, I meant: if you use long as result you can check Integer overflow if (result> Integer.MAX_VALUE) || (result < Integer.MIN_VALUE) return -1 or throw OverflowException. \$\endgroup\$
    – rpc1
    Nov 6, 2019 at 9:47

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.