The Challenge
You are the owner of an amazing service called Coyote Beta, which magically answers math questions its users send to it over the internet.
But it turns out, bandwidth is expensive. You have two choices, either create a "Coyote Beta Pro" or find some way to solve this. Just recently, someone queried (x + 2)
. Couldn't the client send x+2
, and the user would see no difference?
The Task
Your task is to "minify" math expressions. Given an input expression, you must get rid of whitespace and parentheses until it gives a minimal representation of the same input. The parentheses around associative operations need not be preserved.
The only operators given here are +
, -
, *
, /
, and ^
(exponentiation), with standard mathematical associativity and precedence. The only whitespace given in the input will be actual space characters.
Sample Input/Output
Input | Output
------------|--------------
(2+x) + 3 | 2+x+3
((4+5))*x | (4+5)*x
z^(x+42) | z^(x+42)
x - ((y)+2) | x-(y+2)
(z - y) - x | z-y-x
x^(y^2) | x^y^2
x^2 / z | x^2/z
- (x + 5)+3 | -(x+5)+3
Scoring
Input/output can use any preferred method. The smallest program in bytes wins.
Exact bits
Exponentiation is right associative and also follows standard math precedence (being the highest). A valid numeric literal is /[0-9]+/
, and a valid variable literal is /[a-z]+/
. A single variable literal represents a single value even when its character length is longer than 1.
What is meant by "the parentheses around associative operations need not be preserved" is that the output should consist of an expression that results in an identical parse tree, with the exception that associative operations can be rearranged.
/[a-z]+/
, that means multiplication by juxtaposition likeab
is disallowed? \$\endgroup\$2+(3+4)
to be changed to2+3+4
, right? This does change the parse tree. \$\endgroup\$x^(y/2)=x^y/2
; exponentiation has a higher order precedence, ergo,x^y/2=(x^y)/2
. \$\endgroup\$Prompt X:expr(X)
in TI-BASIC but you can't simplify :( \$\endgroup\$