Create a program that solves a mathematical expression using the elements from alternating sides of the expression. The way it’s done is, instead of reading from left to right, you read the first character, then the last, then the second, then the second to last etc. This will give you a new expression that you must evaluate and output.
a*b/c+d-e 135798642 <-- Order you read the expression in ae*-bd/+c <-- Order of operation.
1*3/2+4-5 15*-34/+2 = -255
If the expression doesn’t «work», a
1 must be inserted in the necessary positions to make it work.
A few examples will probably illustrate it better:
Input: 1+1+1+1+1 Result: 23 // Because 1+1+1+1+1 -> 11++11++1 -> 23 Input: 1+2-3+12-5 Result: -19 // Because 1+2-3+12-5 -> 15+-22-13+ -> 15+-22-13+1 -> -19 // | // Not valid expression Input: 2*2*2*2*2 Result: 968 // Because 2*2*2*2*2 -> 22**22**2 -> 22*1*22*1*2 -> 968 // || || // Not valid, 1 must be inserted Input: 17/2 Output: 127 // Because 17/2 = 127/ -> 127/1 -> 127
The operators that must be supported are
+ - * /. There won't be parentheses. Normal math rules and "syntax" is used, so for instance
** does not mean exponentiation.
a++++1 is equivalent to
a+1 (i.e. MATLAB style, not C++).
In case there's any doubt, some valid operations are:
-a +a a++b a+-b a*-b a*+b a*++b a/b a/-b a/+b -a/--b
While all of the following are not valid. It's shown what they should be substituted with:
a+ | a+1 a- | a-1 a++++ | a++++1 (This is equivalent to a+1) a*+++ | a*+++1 (This is equivalent to a*1) a**b | a*1*b a*/b | a*1/b a/*b | a/1*b a* | a*1 *a | 1*a ***a | 1*1*1*a
- The code can be a function or a full program
- The input can be STDIN or function argument
- The input must be a valid mathematical expression, without quotation marks,
- The output should be the answer to the new expression, as an integer, decimal or a simplified fraction.
- At least three digits after the decimal point must be supported. So
1/3 = 0.333, not
ans = ...is accepted.
- Leading and trailing newlines and spaces are accepted.
- The input will only be integers
- Division by zero can result in an error, NaN, Inf etc. Outputting a number is not accepted.
As always, the shortest code in bytes win. A winner will be selected one week from the day the challenge was posted. Answers posted later may still win if it's shorter than the current leader.