This challenge but with a better spec.
Your program will take a linear equation containing a single variable
x and output the value of
Input / Parsing
- The input will only contain numbers, operators, parenthesis (
x, and an
=sign (this means no whitespace).
- Parenthesis will always be balanced.
- There will always be at least 1
xmay be preceded by a number.
- All equations will exactly have one result.
A number can be defined by following these steps. A number can be defined by the regex:
If you don't speak regex: A digit is defined as
- It may have a
-at the beginning of it signifying negative
- Then there may be some digits. If they aren't any digits there will be a decimal point
- If a decimal point exists, at least one digit will follow it
The biggest a number / value will be is defined by your language's capabilities.
An operator is any of:
+-*/, they will always appear between numbers, and or parenthesis
(5)(5) is not a valid input for the sake of simplicity.
Parenthesis will always contain a valid expression (a valid combination of numbers and/or operators) inside them. "Balanced" parenthesis is defined as every
( will have an associated closing
- Order of operations should be followed and the precedences are (highest to lowest):
- Parenthesis (most deeply nested first)
- Multiplication & Division
- Addition & Subtraction
- If two operators with the same precedence are occurred you should prefer going left -> right
You should output the result in some way. If you don't output just number result, clarify in your answer how the output is outputted. Your output format should be consistent. Output may be a decimal, but it will always be rational, the precision is limited to your language's precision. Only if your language does not support floating point arithmetic, you do not need to support it.
- Built-ins trivializing this task are allowed but, you must clearly add
[uses built-in]clearly to the header of the answer. This exempts your answer from winning
- A "Built-ins trivializing this task" is any of:
- Something which takes in an equation and outputs the value for a/the variable
- Something which will completely simplify an equation
evalor a related function to do a significant amount of the parsing. Use of
evaland related functions are disallowed if they are used to (with minimal modification to the input) solve linear equations.
- If you're in doubt, just ask in a comment.
- Built-ins which parse the equation are allowed
3+4=x 7 4+x=5 1 3+3*3=x 12 3x-4=7+2x 11 3--1=x 4 3*(2+4x)=7x-4 -2 1.2+2.3x=5.8 2 10=4x 2.5
(5)(4)=x no operator between (5) and (4) 5(x+3)=2 no operator 5 and (...) x=y the only variable is x 4=3 there is no x x+3=x-7 no solution x=x infinite solutions +5=x + is not an unary operator. -5=x would be valid though 1/(x-3)=5 Nonlinear 3/x Nonlinear