Skip to main content
added the 'how it works' section
Source Link
Arnauld
  • 197.7k
  • 20
  • 179
  • 650

##Javascript (ES6), 57 bytes (array) / 60 bytes (integer)

Returning an array of all intermediate results:

o=>[...o].map(c=>x=[x>>1,x+1,x*2,x-1][eval(2+c+3)&3],x=0)

For instance, the output for "++**--/" will be [1, 2, 4, 8, 7, 6, 3].

Returning only the final result:

o=>[...o].reduce((x,c)=>[x>>1,x+1,x*2,x-1][eval(2+c+3)&3],0)

###How it works

Both solutions are based on the same idea: using the perfect hash function eval(2+c+3)&3 to map the different operator characters c in [0, 3].

 operator | eval(2+c+3)  | eval(2+c+3)&3
----------+--------------+---------------
    +     |  2+3 = 5     |    5 & 3 = 1
    -     |  2-3 = -1    |   -1 & 3 = 3
    *     |  2*3 = 6     |    6 & 3 = 2
    /     |  2/3 ~= 0.67 | 0.67 & 3 = 0

##Javascript (ES6), 57 bytes (array) / 60 bytes (integer)

Returning an array of all intermediate results:

o=>[...o].map(c=>x=[x>>1,x+1,x*2,x-1][eval(2+c+3)&3],x=0)

For instance, the output for "++**--/" will be [1, 2, 4, 8, 7, 6, 3].

Returning only the final result:

o=>[...o].reduce((x,c)=>[x>>1,x+1,x*2,x-1][eval(2+c+3)&3],0)

##Javascript (ES6), 57 bytes (array) / 60 bytes (integer)

Returning an array of all intermediate results:

o=>[...o].map(c=>x=[x>>1,x+1,x*2,x-1][eval(2+c+3)&3],x=0)

For instance, the output for "++**--/" will be [1, 2, 4, 8, 7, 6, 3].

Returning only the final result:

o=>[...o].reduce((x,c)=>[x>>1,x+1,x*2,x-1][eval(2+c+3)&3],0)

###How it works

Both solutions are based on the same idea: using the perfect hash function eval(2+c+3)&3 to map the different operator characters c in [0, 3].

 operator | eval(2+c+3)  | eval(2+c+3)&3
----------+--------------+---------------
    +     |  2+3 = 5     |    5 & 3 = 1
    -     |  2-3 = -1    |   -1 & 3 = 3
    *     |  2*3 = 6     |    6 & 3 = 2
    /     |  2/3 ~= 0.67 | 0.67 & 3 = 0
Source Link
Arnauld
  • 197.7k
  • 20
  • 179
  • 650

##Javascript (ES6), 57 bytes (array) / 60 bytes (integer)

Returning an array of all intermediate results:

o=>[...o].map(c=>x=[x>>1,x+1,x*2,x-1][eval(2+c+3)&3],x=0)

For instance, the output for "++**--/" will be [1, 2, 4, 8, 7, 6, 3].

Returning only the final result:

o=>[...o].reduce((x,c)=>[x>>1,x+1,x*2,x-1][eval(2+c+3)&3],0)