35
3
Given a nonempty list of nonnegative integers, consider rewriting it as an arithmetic problem where:
- A plus sign (
+
) is inserted between pairs of numbers that increase from left to right (a.k.a. from the start of the list to the end). - A minus sign (
-
) is inserted between pairs of numbers that decrease from left to right. - A multiplication sign (
*
) is inserted between pairs of numbers that are equal.
Said another way: any sublist a,b
becomes a+b
if a<b
, a-b
if a>b
, and a*b
if a==b
.
For example, the list
[12, 0, 7, 7, 29, 10, 2, 2, 1]
would become the expression
12 - 0 + 7*7 + 29 - 10 - 2*2 - 1
which evaluates to 75
.
Write a program or function that takes in such a list and evaluates it, printing or returning the result.
- Order of operations matters. Multiplications should be done before any addition or subtraction.
- If the input list has one number, that should be what it evaluates to. e.g.
[64]
should give64
. - Use of
eval
orexec
or similar constructs is allowed.
Here are some additional examples:
[list]
expression
value
[0]
0
0
[1]
1
1
[78557]
78557
78557
[0,0]
0*0
0
[1,1]
1*1
1
[2,2]
2*2
4
[0,1]
0+1
1
[1,0]
1-0
1
[1,2]
1+2
3
[2,1]
2-1
1
[15,4,4]
15-4*4
-1
[9,8,1]
9-8-1
0
[4,2,2,4]
4-2*2+4
4
[10,9,9,12]
10-9*9+12
-59
[1,1,2,2,3,3]
1*1+2*2+3*3
14
[5,5,4,4,3,3]
5*5-4*4-3*3
0
[3,1,4,1,5,9,2,6,5,3,5,9]
3-1+4-1+5+9-2+6-5-3+5+9
29
[7637,388,389,388,387,12,0,0,34,35,35,27,27,2]
7637-388+389-388-387-12-0*0+34+35*35-27*27-2
7379
The shortest code in bytes wins. Tiebreaker is earlier answer.
5Regarding "order of operations matters" it might be good to state explicitly that addition and subtraction are left-associative and have the same precedence. – Martin Ender – 2016-06-12T08:15:04.410