Command Dispatch Table

Problem

Each input line is a command with its numbers: add X Y, sub X Y, mul X Y, max X Y or neg X. Print the result of each line. For any other command print unknown op. Use a table that maps the command name to a function, instead of a long if-else chain.

Constraints

  • 1 <= lines <= 100

Examples

Input

add 2 3
neg 7
pow 2 3

Output

5
-7
unknown op

Solutions

Best approachTime O(n)Space O(1)

To add a new command you add one entry to the table. The loop does not change, and there is no chain of if statements that grows with every command.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Run the commands.
 * Input   : Command lines.
 * Output  : One result per line.
 * Approach: Table of functions
 * Time    : O(n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static String[] solve(String[] lines) {
        // Step 1: The table maps the name of a command to a function. A function is a value like any other.
        java.util.Map<String, java.util.function.Function<long[], Long>> table = new java.util.HashMap<String, java.util.function.Function<long[], Long>>();
        table.put("add", v -> v[0] + v[1]);
        table.put("sub", v -> v[0] - v[1]);
        table.put("mul", v -> v[0] * v[1]);
        table.put("max", v -> Math.max(v[0], v[1]));
        table.put("neg", v -> -v[0]);
        String[] out = new String[lines.length];
        for (int i = 0; i < lines.length; i++) {
            String[] part = lines[i].split(" ");
            long[] values = new long[part.length - 1];
            for (int j = 1; j < part.length; j++) {
                values[j - 1] = Long.parseLong(part[j]);
            }
            // Step 2: Look the function up and call it. A missing name means an unknown command.
            java.util.function.Function<long[], Long> action = table.get(part[0]);
            out[i] = action == null ? "unknown op" : String.valueOf(action.apply(values));
        }
        return out;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        java.util.List<String> all = new java.util.ArrayList<>();
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine().trim();
            if (!line.isEmpty()) {
                all.add(line);
            }
        }
        String[] lines = all.toArray(new String[0]);
        System.out.println(String.join("\n", solve(lines)));
    }
}
Hints (1)
  1. How do you add the command min?