153. Configurable Math Engine

Function pointer syntax (e.g., void (*ptr)(int)) is notoriously hard to read. In professional firmware, we use typedef or using to create an alias for the function pointer type. This makes APIs cleaner and allows passing "Strategies" or "Algorithms" as simple arguments.

Your task is to implement a Calculator that can swap its internal math algorithm at runtime.

  1. Define a typedef named MathOp for a pointer to a function that takes two ints and returns an int.
  2. Implement two global functions:
    • int add(int a, int b): Returns a + b.
    • int multiply(int a, int b): Returns a * b.
  3. Implement class Calculator:
    • Member: MathOp current_op (Initialize to add by default).
    • Method void setMode(MathOp op): Updates the internal pointer.
    • Method void compute(int a, int b): Calls the pointer and prints Result: <value>.

Program Flow:

  1. Instantiate Calculator (default mode is ADD).
  2. Read integer N.
  3. Loop N times.
  4. Read string cmd.
  5. If cmd is "MODE_ADD": call calc.setMode(add).
  6. If cmd is "MODE_MUL": call calc.setMode(multiply).
  7. If cmd is "CALC": read two integers a, b and call calc.compute(a, b).

Input Format:

  • First line: Integer N.
  • Next N lines: String cmd, optionally followed by values.
  • Input is provided via standard input (stdin).

Output Format:

  • Result: <value>
  • Each output on a new line.

Example: 

Example 1

Input:

3
CALC 10 10
MODE_MUL
CALC 10 10

Output:

Result: 20
Result: 100

Constraints:

  • Must use typedef (or using) to define the function pointer type.
  • Must not use switch-case inside compute() to decide the operation.

 

 

 

Loading...

Input

3 CALC 10 10 MODE_MUL CALC 10 10

Expected Output

Result: 20 Result: 100