Introduction
Humans are a remarkable species, but we can be very awkward to understand sometimes—especially for computers. In particular, we seem to like writing polynomials in a very convoluted fashion with seemingly arbitrary rules.
What is the shortest program you can write to format a polynomial correctly using these rules?
Challenge
Input
A list of integers between -1000 and 1000 (inclusive), representing the coefficients of a polynomial, with the last entry being the coefficient of x^0 (the constant), the second last being the coefficient of x^1, etc.
Output
A string representing this polynomial in the correctly formatted mathematical notation of humans.
Rules:
- The sign on the leading coefficient is only shown if it is negative.
Right: -x^2+3
Wrong: +x^2+3
- Components with coefficient of 0 are not printed (except for the corner case where all coefficients are 0*).
Right: x^5-x^2+3
Wrong: x^5+0x^4+0x^3-x^2+0x+3
- Coefficients
-1
and+1
are to be displayed without the 1, unless they are the constant.
Right: x^5-x^2+1
Wrong: 1x^5-1x^2+1
- The exponent is only shown if it is greater than 1 and the variable is only shown if the exponent is greater than 0.
Right: 3x^3-7x^2+2x+1
Wrong: 3x^3-7x^2+2x^1+1x^0
- *Corner case: while zero values usually result in not printing that component, if all coefficients are zero the constant 0 should be printed.
Right: 0
Wrong: 0x+0
Wrong: (nothing)
- This is code-golf so the winner will be the program with the fewest bytes.
Example Input and Output
Input: Output:
[0] 0
[0,0] 0
[0,-1,35,0] -x^2+35x
[5,1,7,-9] 5x^3+x^2+7x-9
[100,0,0,-1] 100x^3-1
[931,21,-11,1] 931x^3+21x^2-11x+1
I look forward to seeing your solutions. Have fun!
EDIT:
- You can surround operations by whitespace if you wish. So
3x+5
and3x + 5
are both fine.3x+ 5
and3x +5
are not. - If you want to produce actual exponent characters (say in Tex) that is allowed as it is even closer to how humans write.
- Coefficients must appear without any decimals e.g.
9x^2
is correct,9.0x^2
is not.
3x^2 + 4
versus3x^2+4
? \$\endgroup\$1x
->x
replacement doesn't change21x^2
into2x^2
. \$\endgroup\$