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.