Introduction
The four basic math operators (+, -, *, /) can be reduced to just two, due to the fact that:
x + y = x - (-y)
x * y = x / (1/y), y != 0
x * 0 = 0/x
Challenge
The challenge is to take input as a "string" containing:
- Numbers
- Single character variables ("x", "y")
- The four basic math operators (+, -, *, /)
- Parenthesis
and output a string manipulated so that it would produce the same mathematical result as the input, but containing only the mathematical symbols '-' and '/'
Specifics
- Input can be in any acceptable form (file, STDIN, etc.) and may be represented as a string or character array (but not an array of arrays)
- Output can be in any acceptable form (file, STDIN, etc.) and may be represented as a string or character array (but not an array of arrays)
- You must recognize and maintain balanced parenthesis
- Standard loopholes are disallowed
- It is your choice if you want to represent
x + y
asx - -y
orx - (-y)
- You must maintain the order of operations
- You never have to handle invalid input
- Input can be empty or a single number/variable, in that case the program should output the input
- Note: You do not have to use the substitutions in the introduction, so long as
input = output
, your program could change2 * 2
to8/2
, if you wanted - You can assume that "0" is the only way a zero will appear in the equation (I.e. you don't have to handle
1 * (4 - 4)
) - Suggestion: to test your program, go to this website type in
input = output
, where input is the input, and output is the output, and if the result is "true" your program handled that case successfully (example, example)
Test Cases
Below are some test cases, input as a single string and output as a single string.
x + y
x - (-y)
x * y
x / (1/y)
x / y
x / y
x - y
x - y
1
1
5
5
-6
-6
+x
x
1 + (x * 4) - (512 * 3)
1 - (-(x / (1/4))) - (512 / (1/3))
1 - 3 / 4 + l / g
1 - 3/4 - (-(l / g))
5 * 0 / 2
0/5 / 2
(a + g) * 0
0/(a - (-g))
Scoring
It's code-golf, so shortest answer in bytes wins. Ties are resolved by first-post.
x / 1/y
=x/y
because division isn't associative. I know what you're thinking, but even WolframAlpha doesn't recognize that you want spaces to change the order of operations.... so you probably should rethink this or not cite that as a valid way to check things. \$\endgroup\$y=0
, but I'm guessing the challenge implicitly assumes thatn/d => d != 0
. \$\endgroup\$v
to be a proper solution in Pyth. \$\endgroup\$5 * (a - b)
if a=b. And do we have to detect things like5 * (a - a)
? How about5 * (4 - 4)
and5 * (a / a - 1)
or5 * (4 / 4 - 1)
? \$\endgroup\$