Simplify a Formula with Known and Unknown Variables
Problem statement
Given an arithmetic expression and parallel arrays names and values of known variable values, simplify the expression as fully as possible. Substitute known variables, evaluate numeric contributions and preserve unknown variables.
For this exercise, assume input may contain decimal literals, lowercase variable names, binary +/-, parentheses and an optional unary minus before a factor. Input is valid; spaces may occur between tokens. Multiplication, division and invalid-input handling are outside this contract. Pure numeric flat expressions are included.
For this exercise, assume the known names are unique and correspond by index to their integer values; unused known names are allowed. Every unknown variable represents one independent symbol.
For this exercise, assume repeated unknown variables combine into integer coefficients. Return a canonical string: write a nonzero constant first, then nonzero unknown terms in lexicographic name order. Use + or - between terms; omit a leading plus and coefficient magnitude 1; use coefficient*name for larger magnitudes. Omit zero terms. If no term remains, return 0.
Function
simplifyFormula(expression: String, names: String[], values: int[]) → StringExamples
Example 1
expression = "(e+3)-(pressure+temperature)+2"names = ["e","y","pressure"]values = [8,7,5]return = "8-temperature"The exact current linked-task sample substitutes e and pressure, preserves temperature, and returns 8-temperature. The unused known variable y is allowed.
Example 2
expression = "a+a-b+4"names = []values = []return = "4+2*a-b"This authored example combines repeated unknown variables and places the constant first: 4+2*a-b.
Example 3
expression = "12-5+1"names = []values = []return = "8"This authored example shows that pure numeric flat expressions are a subset and simplify to 8.
Constraints
- For this exercise, assume
1 <= expression.length <=500and parenthesis nesting depth at most 50. - Variable names contain 1 through 20 lowercase English letters; there are at most 25 distinct names in the expression and at most 25 known-name entries.
- All literals are from 0 through 1000000; known values are from -1000000 through 1000000.
- Input is valid, arrays have the same length, known names are unique, and all arithmetic intermediates fit signed 32-bit integers.