title: Minecraft piston pushing

text:
# Question
Title: Minecraft piston pushing
In Minecraft, pistons are blocks that can move other blocks. However, they can only move at most twelve blocks, and won't work at all if any obsidian is in the way. Also, slime blocks are sticky and stick to other blocks, except for obsidian.

# Your challenge

Take as input a 5x5 matrix or similar, containing one piston at the bottom, and output the result of the single piston pushing upwards, as 5x6. Input format should have five distinct values for obsidian, slime, other block, piston and empty space, here represented by `O`, `S`,`B`,`P`, and  respectively.

For example, say you start with

```
  B
  B
  B
  B
  P

```

Output the result, if the piston was activated, as 5x6:

```
  B
  B
  B
  B
  P

```

Note that the whole configuration with the piston is moved up, as long as it is legal

# Testcases:

```

BBBBB
BBBBB
SSSSS
  S
  P
=>

BBBBB
BBBBB
SSSSS
  S
  P
Because 16 is too many blocks.

 SBS
 SBS
 SBS
 SBS
  P
=>
  B
 SBS
 SBS
 SBS
 SPS
Because slime sticks to blocks, but blocks don't stick to slime.
O
SSSSS
    S
    S
    P
=>
O
SSSSS
    S
    S
    P

Because the obsidian is in the way, the whole thing can't move.
S S S

S S S

S P S
=>

S S S

S S S
  P
S   S

The stray blocks stay where they are.

SSSSS
B S B
B S B
B S B
B P B
=>
SSSSS
B S B
  S
B S B
B P B
B   B
The slime pulls the first two blocks, but the rest stay in place.

 OSO
 OSO
 OSO
 OSO
 OPO
=>
  S
 OSO
 OSO
 OSO
 OPO
 O O
Slime doesn't stick to obsidian, so it's free to move.

```

# Scoring

This is , the shorter the better!

# Answer
> 9 votes
# , 121 98 bytes

Takes in  `POSB` as digits `01234`. Probably some microgolfs left, these long tacit definitions tend to get confusing. :-)

```
((0,~*)+0,(*-.))[(]*(2 e.*&,)<14>+/@,@])[(]*@+(2&<@[*[:+/((,-)=i.2)t]*3=[)+*@[*1(t=:|.!.0)])^:_=&1

```

Try it online!

### How it works

* `=&1` Start a will-be-pushed bitmap with the piston
* `^:_` expand the bitmap until it does not expand further:
* `1(t=:|.!.0)]` Push the bitmap upwards (non-wrapping, thus `!.0`)
* `*@[*` but only if a non-space was pushed.
* `t]*3=[` Extend push of the will-be-pushed slimes towards
* `((,-)=i.2)` all 4 direction
* `2&<@[*[:+` but only push slimes and blocks.
* `]*@+…+` OR old bitmap, slime pushes, and up pushes for the next iteration.
* `[(]*…)` Set the final bitmap to 0 if …
* `(2 e.#~&,)` There is an obsidian block in it
* `<14>+/@,@]` or the sum (including the piston) is not less 14.
* `0,(*-.)` Original map * not-pushed bitmap and an empty row above.
* `(0,~*)` Original map * pushed bitmap and an empty row under.
* `+` Add both maps – as empty spaces are 0 they don't overlap.

# Answer
> 8 votes
# Charcoal, ~~144~~ 120 bytes

```
ＷＳ⊞υι≔⪫υ¶θＰθ…θ⌕θP≔⟦⟦ⅈⅉ⟧⟧ηＦη«Ｊ§ι⁰⊖§ι¹Ｆ‹@ＫＫ⊞η⟦ⅈⅉ⟧↓Ｆ⁼SＫＫＦ³«Ｍ✳⊗⁺²λＦ№⪪BS¹ＫＫ⊞η⟦ⅈⅉ⟧Ｍ✳⊗λ» »Ｆη«Ｊ§ι⁰⁻§ι¹›‹Ｌη¹⁴⊙η⁼O§§υ§ι¹§ι⁰§§υ⊟ι⊟ι

```

Try it online! Link is to verbose version of code. Explanation:

```
ＷＳ⊞υι

```

Input the layout. (I've decided to take input as newline-terminated lines; this allows you to experiment with layouts of different numbers of lines if you so wish.)

```
≔⪫υ¶θＰθ…θ⌕θP

```

Output the layout and move the cursor to the position of the piston.

```
≔⟦⟦ⅈⅉ⟧⟧ηＦη«

```

Perform a breadth-first search starting with the position of the piston.

```
Ｊ§ι⁰⊖§ι¹

```

Jump to the square above the current position.

```
Ｆ‹@ＫＫ⊞η⟦ⅈⅉ⟧

```

Add this position to the list unless it's empty.

```
↓Ｆ⁼SＫＫＦ³«

```

If the current position is a sticky block, then check the other three sides too.

```
Ｍ✳⊗⁺²λＦ№⪪BS¹ＫＫ⊞η⟦ⅈⅉ⟧Ｍ✳⊗λ

```

If there is a (sticky) block on that side then add this position to the list.

```
» »

```

Erase the block, assuming it will be moved. This also avoids considering the same block twice.

```
Ｆη«

```

Loop over each block.

```
Ｊ§ι⁰⁻§ι¹›‹Ｌη¹⁴⊙η⁼O§§υ§ι¹§ι⁰

```

Jump to its old or new position depending on whether there weren't too many blocks to push or any obsidian in the way.

```
§§υ⊟ι⊟ι

```

Print the block.

---
Tags: code-golf, matrix
---


title: Let's draw the flag of Nepal

text:
# Question
Title: Let's draw the flag of Nepal
Nepal’s flag (Wikipedia, Numberphile) looks very different from any other. It also has specific drawing instructions (included in the Wikipedia article). I want you guys to make a program which will draw the flag of Nepal.

The user inputs the requested height of the flag (from 100 to 10000 pixels) and the program outputs the flag of Nepal. You can choose any way to draw the flag: everything from ASCII art to OpenGL.

This is a popularity contest, so the winner will be the highest voted answer on the 1st of February, so don’t worry about length of code, but remember that shorter code may get more up-votes.

There is only one requirement: you are not allowed to use web resources.

Have fun :)

# Answer
# SVG, ~~1375~~, ~~1262~~, ~~1036~~, ~~999~~, ~~943~~, 939

```
<svg>
<defs>
<style>.w{fill:white}</style>
<g id="f"><path d="M1,1L1,20L18,20L6,10L17,10z" style="stroke:#003893;fill:#dc143c"/></g>
<g id="m"><polygon points="1,0 -.5,.86 -.5,-.86"/></g>
<g id="b"><polygon points="1,0 -.5,.86 -.5,-.86"/><polygon points="1,0 -.5,.86 -.5,-.86"transform="rotate(32)"/></g>
<g id="t"><use xlink:href="#b"/><use xlink:href="#b"transform="rotate(60)"/></g>
<g id="s">
<use xlink:href="#m"/>
<use xlink:href="#m"transform="rotate(20)"/>
<use xlink:href="#m"transform="rotate(45)"/>
<use xlink:href="#m"transform="rotate(70)"/>
<use xlink:href="#m"transform="rotate(90)"/>
</g>
</defs>
<g transform="scale(.7)">
<use xlink:href="#f" x="5" y="6"transform="scale(19,23)"/>
<use xlink:href="#t" x="2.8" y="7"class="w"transform="scale(70)"/>
<path d="M157,292 A 40,35 0 1 0 237,292 43,45 0 1 1 157,292z"class="w"/>
<use xlink:href="#s" x="5.6" y="8.9"class="w"transform="scale(35)"/>
</g>
</svg>

```

SVG doesn't really have user input, AFAIK, so you can change the scale modifying this line:

> `<g transform="scale(.7)">`
> 17 votes

# Answer
# JavaScript, 569 537 495 442 characters (ASCII)

```
h="";M=Math;Z=M.max;Y=M.min;function d(a,b,r,s,t){n=M.sqrt(a*a+e*e);return n-(r+M.abs((M.atan2(a,e
)/M.PI*b+t)%1-0.5)*s*n)}f=parseInt(prompt(),10);for(g=0;g<f;g++){for(k=0;k<2*f;k++)e=k/(0.5*f)-0.8
,q=g/(0.25*f),u=q-1.08,v=q-1.29,z=e*e+u*u-0.3364,E=Z(-e-0.8,Y(Z(0.62*e+0.8-q,-2.06+q),Z(1*e+0.8+
0.85-q,-3.87+q))),p=0>Y(d(q-2.91,6,0.38,0.7,10),Y(Z(e*e+v*v-0.3025,-z),Z(d(q-1.54,8,0.25,0.6,10.5)
,q-1.7)))?" ":-0.13>E?";":0>=E?"8":"",h+=p;h+="\n"}h

```

To run : copy-paste to browser console (eg: Chrome developer tools or Firebug)

Result :

```
8
8888
8888888
8888;88888
8888;;;;88888
8888;;;;;;;888888
8888;;;;;;;;;;;88888
8888;;;;;;;;;;;;;;88888
8888;;;;;;;;;;;;;;;;;88888
8888;;;;;;;;;;;;;;;;;;;;888888
8888;;;;;;;;;;;;;;;;;;;;;;;;88888
8888;;;;;;;;;;;;;;;;;;;;;;;;;;;88888
8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;88888
8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;88888
8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;888888
8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;88888
8888;;;;;;;;;;;; ;  ;  ; ;;;;;;;;;;;;;;;;;;;;;;88888
8888;;; ;;;;;               ;;;;; ;;;;;;;;;;;;;;;;88888
8888;;;  ;;;;;;           ;;;;;;  ;;;;;;;;;;;;;;;;;;;888888
8888;;;;   ;;;             ;;;   ;;;;;;;;;;;;;;;;;;;;;;;;88888
8888;;;;;                       ;;;;;;;;;;;;;;;;;;;;;;;;;;;;88888
8888;;;;;;;                   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;88888
8888;;;;;;;;;               ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;88888
8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;888888
8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;88888
8888;;;;;;;;;;;;;;;;;;;;;;8888888888888888888888888888888888888888888888888888888
8888;;;;;;;;;;;;;;;;;;;;;;;;888
8888;;;;;;;;;;;;;;;;;;;;;;;;;;888
8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;888
8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;888
8888;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;888
8888;;;;;;;;;   ;;;   ;;;   ;;;;;;;;;;888
8888;;;;;;;;;;             ;;;;;;;;;;;;;888
8888;;;;                         ;;;;;;;;;888
8888;;;;;;                     ;;;;;;;;;;;;;888
8888;;;;;;;                   ;;;;;;;;;;;;;;;;888
8888;;;                           ;;;;;;;;;;;;;;888
8888;;;;;                       ;;;;;;;;;;;;;;;;;;888
8888;;;;;;;                   ;;;;;;;;;;;;;;;;;;;;;;888
8888;;;;;                       ;;;;;;;;;;;;;;;;;;;;;;888
8888;;;; ;;;;;             ;;;;; ;;;;;;;;;;;;;;;;;;;;;;;888
8888;;;;;;;;;               ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;888
8888;;;;;;;;;  ;;;;   ;;;;  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;888
8888;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;888
8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;888
8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;888
8888;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;888
8888888888888888888888888888888888888888888888888888888888888888888888888
888888888888888888888888888888888888888888888888888888888888888888888888888

```

---

EDIT : added height as user input as ST3 suggested. it works best with big values (eg : 120)
> 27 votes

# Answer
# Mathematica

Nepal's Interim Constitution - Schedule 1 (rel. to Article 6), pp. 260 and 262, provides 25 detailed instructions about how to construct the flag. (see http://www.ccd.org.np/resources/interim.pdf). The numbers in the comments refer to the corresponding instructions in the constitution.

We will need functions to draw equilateral triangles and determine the distance from a point to a line:

```
ClearAll[triangle]
triangle[a_?NumericQ,b_?NumericQ,c_?NumericQ,labeled_:True]:=
Block[{x,y,pt,sqr},sqr=#.#&;
pt[a1_,b1_,c1_]:=Reduce[sqr[{x,y}]==b1^2&&sqr[{x,y}-{a1,0}]==c1^2&&y>0,{x,y}];
{(
(*Polygon[{{0,0},{a,0},{x,y}}]*)
Polygon[{{-a/2(*0*),0},{a/2,0},{x-a/2,y}}]),
If[labeled,
{Text[Style[Framed[a,Background->LightYellow],11],{a/2,0}],
Text[Style[Framed[b,Background->LightYellow],11],{x/2,y/2}],
Text[Style[Framed[c,Background->LightYellow],11],{(a+x)/2,y/2}]},{}]}/.ToRules[pt[a,b,c]]]

(*distance from point to a line *)
dist[line_,{x0_,y0_}]:=(Abs[a x0+b y0+c]/.{x0-> m[[1]],y0-> m[[2]]})/Sqrt[a^2+b^2]; (* used below *)

```

The remaining code, with numbers referring to the instructions. By far, the most challenging part is to make the rays for the moon and the sun. `GeometricalTransformation` comes in handy for doing translations and rotations.

```
    (*shape inside flag*)
(*1*)
w=100;a={0,0};b={w,0};
lAB=Line[{a,b}];
tA=Text["A",Offset[{-10,-20},a]];
tB=Text["B",Offset[{20,-20},b]];

(*2*)
c={0,w 4/3};d={0,w};
lAC=Line[{a,c}];
tC=Text["C",Offset[{-10,20},c]];
lAD=Line[{a,d}];
tD=Text["D",Offset[{-10,0},d]];
lBD=Line[{b,d}];

(*3*)
e=Solve[(x-w)^2+y^2==(w)^2&&y==w-x,{x,y}][[1,All,2]];
tE=Text["E",Offset[{15,0},e]];

(*4*)
f={0,e[[2]]};tF=Text["F",Offset[{-10,0},f]];
g={w,e[[2]]};tG=Text["G",Offset[{15,0},g]];
lFG=Line[{f,g}];
poly={a,b,e,g,c};

(*5*)lCG= Line[{c,g}];

(*moon*)
(*6*)
lineCG=N[((f[[2]]-c[[2]])/w)x+c[[2]](*100*)];
h={w/4,0};tH=Text["H",Offset[{0,-20},h]];
i={h[[1]],lineCG/.x->h[[1]]};tI=Text["I",Offset[{10,0},i]];
lHI={Dashed, LightGray,Line[{h,i}]};

(*7*)
j={0,f[[2]]+(c[[2]]-f[[2]])/2};tJ=Text["J",Offset[{-10,10},j]];
lineJG=N[((f[[2]]-j[[2]])/g[[1]])x+j[[2]]];
k={Solve[lineCG==j[[2]],x][[1,1,2]],j[[2]]};tK=Text["K",Offset[{10,10},k]];
(*k={Solve[lineCG\[Equal]c[[2]],x][[1,1,2]],j[[2]]};tK=Text["K",Offset[{10,10},k]];*)
lJK={Dashed, LightGray,Line[{j,k}]};

(*8*)l={i[[1]],j[[2]]};tL=Text["L",Offset[{0,10},l]];
(*9*)lJG={LightGray,Dashed,Line[{j,g}]};
(*10*)m={h[[1]],(lineJG/.x-> h[[1]])};tM=Text["M",Offset[{0,10},m]];
(*11*)distMfromBD=dist[{1,1,-w(*100*)},m];
 n={i[[1]],m[[2]]-distMfromBD};tN=Text["N",Offset[{0,0},n]];
(*ln=Abs[l[[2]]-n[[2]]];*)
(*12*)o={0,m[[2]]};tO=Text["O",Offset[{-10,0},o]];
lM={Dashed,LightGray,Line[{o,{g[[1]],o[[2]]}}]};

(*13*)
radiusLN=l[[2]]-n[[2]];
p={m[[1]]-radiusLN,m[[2]]};tP=Text["P",Offset[{0,10},p]];
q={m[[1]]+radiusLN,m[[2]]};tQ=Text["Q",Offset[{0,10},q]];
moonUpperEdge={White,Circle[l,radiusLN,{Pi,2 Pi}]};
moonLowerEdge={White,Circle[m,radiusMQ,{Pi,2 Pi}]};

(*14*)radiusMQ=q[[1]]-m[[1]];

(*15*)radiusNM=m[[2]]-n[[2]];
arc={Yellow,Circle[n,radiusNM,{Pi/7,6 Pi/7}]};
{r,s}=Solve[(x-l[[1]])^2+(y-l[[2]])^2==(radiusLN)^2 &&(x-n[[1]])^2+(y-n[[2]])^2==(radiusNM)^2,{x,y}][[All,All,2]];
tR=Text["R",Offset[{0,0},r]];
tS=Text["S",Offset[{0,0},s]];
t={h[[1]],r[[2]]};
tT={Black,Text["T",Offset[{0,0},t]]};

(*16*)radiusTS=Abs[t[[1]]-s[[1]]];
(*17*)radiusTM=Abs[t[[2]]-m[[2]]];

(*18 triangles*)
t2=Table[GeometricTransformation[GeometricTransformation[triangle[4,4,4,False][[1]],RotationTransform[k Pi/8]],{TranslationTransform[t]}],{k,-4,3}];
midRadius=(Abs[radiusTM+radiusTS]/2-2);
pos=1;table2=GeometricTransformation[t2[[pos++]],{TranslationTransform[#]}]&/@Table[midRadius {Cos@t,Sin[t]},{t,Pi/16,15 Pi/16,\[Pi]/8}];

(*19 sun*)u={0,f[[2]]/2};tU=Text["U",Offset[{-10,0},u]];
lineBD=N[(d[[2]]/w)x+d[[2]]];
v={-Solve[lineBD==u[[2]],x][[1,1,2]],u[[2]]};tV=Text["V",Offset[{10,0},v]];
lUV={LightGray,Dashed,Line[{u,v}]};

(*20*)w={h[[1]],u[[2]]};tW={Black,Text["W",Offset[{0,0},w]]};
(*21*)
(*22*)

t3=Table[GeometricTransformation[GeometricTransformation[triangle[9,9,9,False][[1]],RotationTransform[k Pi/6]],{TranslationTransform[w]}],{k,-3,9}];
midRadius3=(Abs[radiusTM+radiusTS]/2+2.5);
pos=1;
table3=GeometricTransformation[t3[[pos++]],{TranslationTransform[#]}]&/@Table[midRadius3 {Cos@t,Sin[t]},{t,0,2 Pi,2\[Pi]/12}];

Show[
Graphics[{Gray,
(*1*)lAB,tA,tB,
(*2*)lAC,tC,lAD,tD,lBD,
(*3*)tE,
(*4*)tF,lFG,tG,{Red,Opacity[.4],Polygon[poly]},
(*5*)lCG,
(*6*)tH,lCG,tI,lHI,
(*7*)tJ,lJK,tK,
(*8*)tL,
(*9*)lJG,
(*10*)tM,
(*11*)tN,
(*12*)lM,tO,
(*13*)moonUpperEdge,tP,tQ,
(*14*)moonLowerEdge,
(*15*)arc,tR,tS,tT,
(*16*){White,Dashed,Circle[t,radiusTS(*,{0, Pi}*)]},

(*17*){White,Opacity[.5],Disk[t,radiusTM,{0, 2 Pi}]},
(*18 triangles*){White,(*EdgeForm[Black],*)table2},
(*19 sun*)tU,tV,lUV,

(*20*)tW,{Opacity[.5],White,Disk[w,Abs[m[[2]]-n[[2]]]]},
(*21*)Circle[w,Abs[l[[2]]-n[[2]]]],
(*22*){Black(*White*),EdgeForm[Black],triangle[4,4,4,False](*table3*)},
{White,(*EdgeForm[Black],*)table3},

(*23*)
{Darker@Blue,Thickness[.03],Line[{a,b,e,g,c,a}]}

},
Ticks-> None(*{{0,100},{0,80,120,130}}*), BaseStyle-> 16,AspectRatio-> 1.3,Axes-> True],

(*cresent moon*)
RegionPlot[{(x-25)^2+(y-94.19)^2<21.4^2&&(x-25)^2+(y-102.02)^2>21.4^2},{x,0,100},{y,30,130},PlotStyle->{Red,White}]]

```

The following flag, from the above code, is made according to the instructions in the constitution.

Colors are modified to enable easier viewing of the construction lines. The letters refer to points and lines in the instructions.

---

By the way, flags of the world can be called up directly within Mathematica. For example:

```
Graphics[CountryData["Nepal", "Flag"][[1]], ImageSize->{Automatic,200}]

```
> 22 votes

# Answer
# Python

```
import turtle, sys
from math import sqrt, sin, cos, pi

height = int(sys.argv[1])
width = height / 4 * 3
turtle.screensize(width, height)
t = turtle.Turtle()

# the layout
t.pencolor("#0044cc")
t.fillcolor("#cc2244")
t.pensize(width / 25)
t.pendown()
t.fill(True)
t.forward(width)
t.left(135)
t.forward(width)
t.right(135)
t.forward(width / sqrt(2))
t.right(90)
t.goto(0, height)
t.forward(height)
t.fill(False)
t.penup()

# the bottom star
t.fillcolor("#ffffff")
t.pencolor("#ffffff")
t.pensize(1)
radius = width / 5
x = width / 4
y = height / 4
t.goto(x + radius, y)
t.pendown()
t.fill(True)
for i in range(24):
    t.goto(x + radius * (5 + (-1) ** i) / 6 * cos(i * pi / 12), y + radius * (5 + (-1) ** i) / 6 * sin(i * pi / 12))
t.fill(False)
t.penup()

# the top star
radius = width / 9
x = width / 4
y = height * 2 / 3
t.goto(x + radius, y)
t.pendown()
t.fill(True)
for i in range(28):
    t.goto(x + radius * (6 + (-1) ** i) / 7 * cos(i * pi / 14), y + radius * (6 + (-1) ** i) / 7 * sin(i * pi / 14))
t.fill(False)
t.penup()

# the moon
radius = width / 5
x = width / 4
y = height / sqrt(2)
t.goto(x + radius, y)
t.pendown()
t.fill(True)
for i in range(30):
    t.goto(x + radius * cos(i * pi / 30), y - radius * sin(i * pi / 30))
for i in range(30):
    t.goto(x - radius * cos(i * pi / 30), y - radius / 2 * sin(i * pi / 30))
t.fill(False)
t.penup()
t.hideturtle()

raw_input("press enter")

```

Uses python's Tk turtles, example of `python nepal.py 150` and `python nepal.py 200` respectively:
> 9 votes

# Answer
# Python (+PIL), 578

Because I'm quite bored today..

```
from PIL import Image,ImageDraw
from math import*
I,k,l,m,n,o,_=Image.new('P',(394,480)),479,180,465,232,347,255;D=ImageDraw.Draw(I);P,G=D.polygon,D.pieslice
I.putpalette([_,_,_,0,0,_,_,20,60])
def S(x,y,r,e,l,b):
 p,a,h=[],2*pi/e,r*l;c,d=[0,-a/2][b],[a/2,0][b]
 for i in range(e):p+=[(x+r*cos(i*a+c),y+r*sin(i*a+c)),(x+h*cos(i*a+d),y+h*sin(i*a+d))]
 P(p,fill=0)
P([(0,0),(393,246),(144,246),(375,k),(0,k)],fill=1)
P([(14,25),(o,n),(110,n),(o,m),(14,m)],fill=2)
S(96,o,68,12,.6,0)
G([(31,90),(163,221)],0,l,fill=0)
G([(28,68),(166,200)],0,l,fill=2)
S(96,178,40,16,.7,1)
I.show()

```
> 5 votes

# Answer
# PostScript

Code:

```
.15 .15 scale            % over-all scale

% draw the red area and blue border
7 7 moveto
360 7 lineto
128 240 lineto
367 240 lineto
7 467 lineto
closepath
gsave                    % save the outline path for further use
.86 .08 .24 setrgbcolor  % crimson red
fill                     % draw the red area
grestore                 % get back the saved outline path
0 .22 .58 setrgbcolor    % dark blue
14 setlinewidth
stroke                   % draw the blue border

1 setgray                % white

% draw the lower sun
96 130 translate         % coordinate origin of sun
69 0 moveto
12 {                     % 12 spikes
  69 0 lineto
  15 rotate
  46 0 lineto
  15 rotate
} repeat
closepath fill

% draw the upper sun
0 167 translate          % coordinate origin at center of sun
29 0 moveto
16 {                     % 16 spikes
  29 0 lineto
  11.25 rotate
  42 0 lineto
  11.25 rotate
} repeat
closepath fill

% draw the crescent moon
0 24 65 180 0 arc        % the lower arc
0 57 72 335 205 arcn     % the upper arc
closepath fill

showpage

```

The flag size can be controlled by specifying the resolution in the Ghostscript call.

Result (height of flag is 480 pixels, created by `gswin64c -r480 nepal.ps`):

Result (height of flag is 120 pixels, created by `gswin64c -r120 nepal.ps`):
> 1 votes

---
Tags: popularity-contest, ascii-art, graphical-output, kolmogorov-complexity, geometry
---


title: Random Move 2x2 Scrambling

text:
# Question
Title: Random Move 2x2 Scrambling
A simple way to scramble a 2x2x2 Rubik's cube is to make a sequence random moves. This is not how official scrambles are done, but can get pretty close to a uniform distribution of all possible scramble states. Due to the way a 2x2 only has two layers, doing one turn on one face is equivalent (without considering the puzzle's orientation in space) to doing the same direction turn on the opposite face. For example, turning the top face clockwise moves all the pieces in relation to each other the same way turning the bottom face clockwise does. So scrambles only need to turn the top (U), right (R), and front (F) faces.

For this challenge, your program must generate a string that represents a sequence of 16 moves. A move is represented by a face, one of the letters `U`, `R`, `F`, followed by a direction: clockwise (empty string or space ), counterclockwise (apostrophe `'`), or 180 degrees (`2`). The turn and direction should be chosen uniformly at random, however two consecutive moves cannot turn the same face, For example a scramble cannot contain `R' R2`. So the first move should have a 1/3 chance for each face, but there should be a 50/50 chance for the chosen face *after the first move*. Moves are separated by a space.

Example scramble:

```
U  F' R2 F' R' F  R  F2 U' F  R2 F  U2 F' U2 F2

```

# Answer
# Python 3.8, ~~84~~ ~~83~~ 82 bytes

-2 bytes thanks to dingledooper!

```
import random as R
print(*[(R:=c([*{*"FUR"}-{R}]))+c(" '2")for c in[R.choice]*16])

```

Try it online!
> 8 votes

# Answer
# 05AB1E, 19 bytes

```
16Fн…FRUsK… '2âΩð«?

```

Try it online!

```
16F                  # iterate 16 times:
   н                 # get the first character from the value that was last on stack
    …FRU             # push string "FRU"
        sK           # remove the result from н
          … '2       # push string " '2"
              â      # cartesian product of the strings
               Ω     # choose a random string from the list
                ð«   # append a space
                  ?  # print without a trailing newline

```

---

`Ô` \- *Connected uniquified a* seems like a promising builtin for this challenge, but the best I could do with it is 22 bytes:

```
…FRU¸Þ€ΩÔ16£ε… '2Ω«}ðý

```

Try it online!

```
…FRU¸Þ                 # infinite list ["FRU", "FRU", ...
     €Ω                # select a random character from each string
       Ô               # remove consecutive duplicates
        16£            # take the first 16 characters
           ε      }    # for each of those:
            … '2Ω«     # append a random char from " '2"
                   ðý  # join the resulting list by spaces

```
> 7 votes

# Answer
# Vyxal, ~~35~~ ~~29~~ ~~25~~ 19 bytes

```
16(h‛⊍Ṁ⇧$-` '2`Ẋ℅¨…

```

Try it Online!

Thanks to Lyxal for -6 bytes.

```
16(                 # Repeat 16 times (Automatically closed)
   h                # Take first of previous
    ‛⊍Ṁ⇧            # Push `fru`, uppercased
        $           # Swap top two elements on stack
         -          # Remove (So fru loses the first of previous iteration)
          ` '2`     # Push ` '2`
               Ẋ    # Cartesian product
                ℅   # Random choice
                 ¨… # No idea (Can't find any docs)

```

## My old version, 25 bytes

```
16(‛Ŀ¦⇧'¥≠;℅:£`'2 `℅+⅛)¾Ṅ

```

Try it Online!

```
16(                   )   # 16 times
   ‛Ŀ¦⇧                   # Push compressed string `fur`, to uppercase
       '  ;               # Filter by...
        ¥≠                # is not equal to register
           ℅              # Random choice
            :£            # Duplicate and push to register
              `'2 `℅      # Random of `'2 `
                    +     # Concatentated
                     ⅛    # Push to global array
                       ¾  # Push global array to stack
                        Ṅ # Join by space

```

I know this is a mess. Also this seems to be the only one that compresses even one of the strings.
> 5 votes

# Answer
# Charcoal, 18 bytes

```
Ｆ¹⁶«≔‽⁻FRUωωω‽ 2'→

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｆ¹⁶«

```

Repeat 16 times.

```
≔‽⁻FRUωω

```

Choose a random turn that wasn't just used.

```
ω

```

Output that turn.

```
‽ 2'

```

Output a random direction.

Except for the last move, leave a space for the next move.
> 4 votes

# Answer
# Retina, 50 bytes

```
$
¶FRU¶ 2'
(([FRU])¶.¶.*)\2
$1
16}%@L`.
¶

|' L`..

```

Try it online! Explanation:

```
$
¶FRU¶ 2'

```

Append the possible turns and directions.

```
(([FRU])¶.¶.*)\2
$1

```

Remove the turn that was made the last time.

```
%@L`.

```

Pick a random turn and direction from those left.

```
16}`

```

Repeat the above 16 times.

Join everything together.

```
|' L`..

```

Add spaces between the moves.
> 4 votes

# Answer
# Factor, 83 bytes

```
[ [ "UFR"""16 [ over remove random dup , "2 '"random , 32 , ] times ] ""make 2nip ]

```

Try it online!

One of the odd times `make` is shorter than sequence words (or smart combinators like `append-outputs`). Mainly because turning code points into strings is verbose in Factor, but `make`, despite being verbose itself, can do that with ease. Plus, `,` is much shorter than `suffix` or `append`.

## Explanation:

It's a quotation (anonymous function) that takes no input and leaves a string on the data stack as output.

* `[ ... ] ""make` Make a string. Inside the quotation, `,` appends elements to a sequence. The `""` is an exemplar that tells `make` the result should be a string.
* `"UFR"""` Place two strings on the stack. The first, `"UFR"`, indicates which possible faces we can choose. The second, `""`, is the last face we chose, so we don't choose it twice in a row.
* `16 [ ... ] times` Call a quotation 16 times.
* `over remove random` Pick a random face that we didn't pick last time.
* `dup ,` Append it to our sequence without destroying it (since we need to know our last move again).
* `"2 '" random ,` Append a random direction/move to the face.
* `32 ,` Append a space.
* `2nip` Once `make` is done building the string, we still have some junk on the data stack to remove.
> 4 votes

# Answer
# JavaScript (ES6),  ~~82 81~~  79 bytes

```
f=i=>i>>10?"":"FRU"[(i=~~i-Math.random()*~-~!i)%3|0]+" '2"[i*3%3|0]+" "+f(i+64)

```

Try it online!

Or run a consistency check on 500,000 calls

### How?

We start with \\$i=0\\$. \[1\]

At each iteration, we add to \\$i\\$ a random float in \\$\left\[0,3\right\[\\$ if \\$i=0\\$ (3 possible choices) or in \\$\left\[0,2\right\[\\$ if \\$i\neq 0\\$ (only 2 possible choices).

We use \\$\lfloor i\bmod 3 \rfloor\\$ as the index of the face character and \\$\lfloor (3\times i)\bmod 3 \rfloor\\$ as the index of the direction character.

After each iteration\[1\], we update \\$i\\$ to \\$\lfloor i+64 \rfloor\\$ in order to:

* get rid of the decimal part whose only purpose was to to choose a direction character
* make sure that we won't pick the same face character twice in a row (because \\$64 \bmod3=1\\$)
* be able to know that we've processed 16 iterations by testing if \\$i\\$ is greater than or equal to \\$1024\\$, because we add at least \\$16\times64=1024\\$ to \\$i\\$ (and at most \\$16\times65+1=1041\\$)

---

*\[1\] in order to save a few bytes, we actually start with \\$i\\$ undefined, coerce it to a number at the very beginning of an iteration, and add \\$64\\$ at the end.*
> 2 votes

# Answer
# GolfScript, 41 bytes

```
16,{;'FRU'[a]-.,rand=:a" '2"3rand=32}%""+

```

Try It Online!

### Explanation

```
16,{;'FRU'[a]-.,rand=:a" 'r"3rand=32}%""+
16,                                        // push the list [0..15]
   {                                       // begin code block
    ;                                      // remove the element already in the list
     'FRU'[a]-                             // remove the previous value of a from the possible choices
                                              (initially, [a] evaluates to an empty list as a is undefined)
              .,rand=                      // push the length of the string, and index the string to a
                                              random integer in this range
                     :a                    // set a to this value for the next iteration
                       " 'r"               // push " 'r"
                            3rand=         // index the string to a random position
                                  32}      // push the ASCII value for ' ', and end the block
                                     %     // map the block over the list [0..15]
                                      ""+  // convert the resulting list of ASCII values into a string
                                           // the string is output implicitly

```
> 2 votes

# Answer
# Python 3.8 (pre-release), ~~107 106 116 108 105~~ 104 bytes

Basic randoms

-1 bytes to @qwr's space

-1 bytes to @razetime's space

+11 bytes to randomize starting n

-8 bytes by applying new loop method and skipping `' '.join()` and also defining `r` to `randint`

-3 bytes by spliting lines and removing some brackets and rearranging.

-1 byte by changing loop mathod to `exec`.

```
from random import*
r=randint;n=r(0,2)
exec("print('RFU'[(n:=n+r(1,2))%3]+choice('\\' 2'),end=' ');"*16)

```

Try it online!
> 1 votes

# Answer
# JavaScript, ~~101~~ ~~99~~ 91 bytes

```
f=(i=s=17,m=Math.random)=>--i?'URF'[s=(s>3?m()*3:s+1+m()*2)%3|0]+" '2"[m()*3|0]+' '+f(i):''

```

Try it online.

## Explanation

We start with `i` and `s` both set to 17, then each iteration, if subtracting one from `i` yields a positive integer, we get the face character using a simple ternary and add a random direction character and then add a recursive call to `f` with the newly decremented `i`, and otherwise we simply return an empty string.
> 1 votes

# Answer
# Japt `-S`, ~~20~~ 19 bytes

Would be 17 if we could output the pairs reversed and in lowercase.

```
GÆ="RUF"kU ï" '2" ö

```

Test it or run it 100 times
or verify that the same move isn't used twice in a row over 100 runs

```
GÆ="RUF"kU ï" '2" ö
G                        :16
 Æ                       :Map the range [0,G)
  =                      :  Assign to variable U (initially 0)
   "RUF"                 :  String literal
        kU               :  Remove characters in U
           ï" '2"        :  Cartesian product with " '2"
                  ö      :  Random element of resulting array
                         :Implicit output joined with spaces

```
> 1 votes

# Answer
# Haskell, 114 bytes

```
(' '?16!!)<$>randomRIO(0,9*6^15-1)
_?0=[""]
c?n=[m:d:' ':r|m<-"RUL",m/=c,d<-" '2",r<-m?(n-1)]
import System.Random

```

Try it online! (times out for obvious reasons, you can test it out here with 8 moves).

The relevant "function" is `(' '?16!!)<$>randomRIO(0,9*6^15-1)`, an `IO String` object "containing" a random sequence of moves.

As always, solving challenges in Haskell is a great idea.

## How?

```
_?0=[""]
c?n=[m:d:' ':r|m<-"RUL",m/=c,d<-" '2",r<-m?(n-1)]

```

(?) is a pure function taking a character `c` and an integer `n` as input and returning the list of all valid sequences of moves of length `n` such that the first move is not `c`.

---

```
(' '?16!!)<$>randomRIO(0,9*6^15-1)

```

`randomRIO(0,9*6^15-1)` generates a random integer in the range `(0,9*6^15-1)`; incidentally, `9*6^15` is exactly the number of valid sequences of length 16. Then with `(' '?16!!)<$>` we use this random integer to index into `' '?16`, which is the list of valid sequences of length 16.
> 1 votes

# Answer
# PowerShell, 63 61 bytes

```
"$(1..16|%{($l='R','U','F'-ne$l|random)+("'",' ',2|random)})"

```

Try it online!

Technically, a 60-byte solution works by using an empty string rather than a space to the second random selection; however, an error is thrown each time the empty element is selected.
> 1 votes

# Answer
# Java, ~~157~~ 151 bytes

```
$->{for(char i=16,c=0,j=3;i-->0;j=2)System.out.format("%c%c ",c="URF".replace(c+"","").charAt(j*=Math.random())," '2".charAt((int)(Math.random()*3)));}

```

*Saved 6 bytes thanks to Kevin Cruijssen.*

Try it online!
> 1 votes

# Answer
# Jelly, 23 bytes

```
“FUR“ '2”Wẋ⁴ŻṖḟ@"X€ɗ\ḊK

```

Try it online!

A full program that prints a 16-long scramble.

## Explanation

```
“FUR“ '2”               | ["FUR"," '2"]
         W              | Wrap in a further list
          ẋ⁴            | Repeat 16 times
            Ż           | Prepend a zero
                   ɗ\   | Reduce using the following as a dyad, keeping intermediate values:
             Ṗ          | - Remove last item
              ḟ@"       | - Filter out this from the next incoming copy of the list (but because of the Ṗ and ", this will only affect the FUR part)
                 X€     | - Randomly pick a value for each
                     Ḋ  | Remove the first value (the zero)
                      K | Separate with spaces
                        | (Implicitly) print

```
> 1 votes

# Answer
# , 46 bytes

```
3 :0
,'URF 2'''{~3(,3,~?@3-3:)@|+/\1+?3,15$2
)

```

Try it online!

Surprisingly verbose.

The only part of this I liked was the code to pick the random faces:

```
3|+/\1+?3,15$2

```

Here we create the 16 element list:

```
3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2

```

Then "roll" `?` for each element (so pick randomly among `0 1 2` for the first element, and among `0 1` for the second), then scan sum the result `+/\`, then mod by 3 `3|`.

## tacit version, also 46

```
[:,'URF 2'''{~3(,3,~?@3-3:)@|?@3+/\@,1+15?@$2:

```

But I think the explicit version is easier to read, since if you discount the boilerplate `3 :0` and `)` it is effectively fewer bytes.
> 1 votes

# Answer
# Raku, 54 bytes

```
(<F R U>.roll(*).squish Z~"2' ".comb.roll(*))[^16].put

```

Try it online!

* Uses `squish` to get rid of consecutive face repeats
* `Z~` metaoperator zips the two lists, then concatenates the resulting pairs
* `comb` makes light work of the literal space requirement

---

While golfing I found other interesting Raku features that are worth highlighting:

### Alternative, 86 bytes

```
((<F R U>.roll,{{:F<R U>,:R<F U>,:U<F R>}{$_}.roll}…*)Z~"2' ".comb.roll(*))[^16].put

```

Try it online!

* Compact pair literal syntax within sequence generator to determine valid next cube face

### Alternative, 94 bytes

```
my@m=<F R U>;((@m.roll,{%(@m.map:{$_=>(@m∖$_)}){$_}.roll}…*)Z~"2' ".comb.roll(*))[^16].put

```

Try it online!

* Uses set difference operator to exclude key from `@m` when creating key-value pairs
> 1 votes

# Answer
# JavaScript (Node.js), 83 bytes

```
f=(p='',g=s=>s[0][Math.random()*3|0],a=g`URF`)=>p[47]?p:f(p[0]==a?p:a+g` '2`+' '+p)

```

Try it online!
> 0 votes

---
Tags: code-golf, string, random, rubiks-cube
---


title: Let's play Judgement!

text:
# Question
Title: Let's play Judgement!
In this challenge, you will be making a 3 bot to play the card game judgement!

Sandbox

# Rules

Judgement is a hand based game similar to games like rummy. In each round, 7 cards are dealt to each player, a trump suit is chosen (trump suits are chosen sequentially from the list Spades/Hearts/Diamonds/Clubs/No Trump), and based on these cards, the trump suit, and the play order, each player must make a guess as to how many hands they will win.

The first player to play in a particular hand can play any card they want. From then on, any subsequent player must play a card of the same suit as the first player if they have it, otherwise, they can play any card.

Once every player has played a card, the winner of the hand is determined as follows:

* If a trump card has been played, the highest trump card wins
* Otherwise, the highest card in the suit played by the first player wins

(As in most card games, the ordering is 2,3,4,5,6,7,8,9,10,J,Q,K,A)

The winner of a given hand starts the next hand. Once everyone's cards are depleted, each player counts the number of hands they have won. If it is equal to their guess, they earn 10 + the number of guessed hands. Otherwise, they earn nothing.

The winner of the game is the player with the highest scores after several rounds.

# Challenge

I've built the game controller here. Everything in this section is present in the link, but I'll include it here for completeness.

### A submission must include 5 parts:

---

```
"name"

```

A name for the bot.

---

```
def make_bet(self, turn_order, trump):
    ...
    return hands_to_make

```

This function takes in `turn_order`, which is a list of the names of all bots in order of when they will play, and `trump`, which is a string representing the trump suit for the round. It must return `hands_to_make`, which is the number of hands the bot expects to win this round. `self.hand`will be automatically updated to contain your current hand.

---

```
play_card(self, current_board):
    ...
    return card_played

```

This function takes in the list of cards played so far this hand in the form `("bot_name", Card)`, and returns `card_played`, which is the card from your hand to play.

---

```
update_round(self, current_scores, rounds_left):
    ...
    return None

```

This function gets called right before every round (including at the very beginning for initializing you bot). It takes `current_score` which is a dictionary of `bot_name: current_score`, and `rounds_left`, which is the number of rounds left to be played.

---

```
update_play(self, final_board, winner):
    ...
    return None

```

This function gets called right after each hand. `final_board` is the list of cards played that hand in the form `("bot_name", Card)`, and `winner` is a string indicating which bot won the hand.

---

The classes have the following specs

**Card**:

* self.suit accesses the suit (S,H,D, or C)
* self.rank accesses the rank (int from 2 -\> 14)
* self.get\_rank() accesses the rank in str form (2-10,J,Q,K,A)

**Bot**:

* self.hand accesses the hand (List\[Card\])
* self.name accesses the name of the bot. Alternatively, str(self) works as well.
* self.all\_bets accesses a dictionary of bets placed by all bots.
* You can store other information you want to store by create self. class variables.

As a basic example, consider the following bot:

# Basic Bot

```
def basic_make_bet(self, turn_order, trump):
    return len(self.hand)

def basic_play_card(self, current_board):
    if current_board:
        for card in self.hand:
            if card.suit == current_board[0].suit:
                return card
    return self.hand[0]

def basic_update_round(self, current_scores, rounds_left):
    pass

def basic_update_play(self, final_board, winner):
    pass

basic_bot = ("basic", basic_make_bet, basic_play_card, basic_update_round, basic_update_play)

```

The Colab link above contains an easy to use template for submissions, so I recommend using that! I will also try to update the Colab link with new bots as soon as they are posted.

# Requirements

* You can only use libraries available in Google Colab. These are the libraries present in the Anaconda distribution of Python 3.
* self.hand, the variable to access to see one's hand, must be treated as read only. Modifying the variable will mess up the game, so please avoid this.
* Bots must run in a reasonable amount of time. I'm not going to provide any strict bounds but I'll remove any serious offenders.
* The competition will be run June 6th, and the winner will receive a bounty + a check mark.
* To judge the bots, I'll pick random groupings of up to 7 bots and play the game thousands of times, and evaluate the average score of the bots per game.

# Current Averages

Each bot has played a total of 100 rounds. This table should be updated semi-regularly. (PlanBot is currently too slow to run 10000 rounds)

| Bot | Average |
| --- | --- |
| PlanBot | 6.71 |
| Conservative | 6.30 |
| BasicCardStrat | 4.77 |
| Half | 4.28 |
| Random | 4.15 |
| sans. | 3.19 |
| Basic | 0.00 |

# Answer
## PlanBot

Plans one step ahead and then simulates a random game. Tries to sabotage its opponents once it goes bust.

```
    import random

    def valid_plays(hand, suit):
        if suit is None:
            return list(range(len(hand)))
        follows_suit = [i for i, card in enumerate(hand) if card.suit == suit]
        if follows_suit:
            return follows_suit
        return list(range(len(hand)))

    def pick_random(hand, suit):
        if suit is None:
            return random.randrange(len(hand))
        follows_suit = [i for i, card in enumerate(hand) if card.suit == suit]
        if follows_suit:
            return random.choice(follows_suit)
        return random.randrange(len(hand))

    def simulate_random_game(hands, trump, starting_player, current_trick):
        tricks_won = [0] * len(hands)
        current_trick = list(current_trick)
        current_suit = current_trick[0].suit if current_trick else None
        while hands[starting_player]:
            i = 0
            while len(current_trick) < len(hands):
                player = (starting_player + i) % len(hands)
                hand = hands[player]
                card_index = pick_random(hand, current_suit)
                card = hand[card_index]
                current_suit = current_suit or card.suit
                hand[card_index] = hand[-1]
                hand.pop()
                current_trick.append(card)
                i += 1
            winner_offset = max(enumerate(current_trick), key=lambda t: (t[1].suit == trump, t[1].suit == current_trick[0].suit, t[1].rank))[0]
            current_suit = None
            starting_player = (starting_player + winner_offset) % len(hands)
            tricks_won[starting_player] += 1
            current_trick.clear()
        return tricks_won

    def dirichlet_score(counts):
        sampled_counts = [random.gammavariate(n, 1) for n in counts]
        return max(sum(i * n for i, n in enumerate(counts_prime)) / sum(counts_prime) for counts_prime in (counts, sampled_counts))

    INITIAL_DECK = Deck().cards

    def as_tuple(card):
        return (card.suit, card.rank)

    def deal(out, initial_dead_cards, hand_sizes):
        num_attempts = 4
        order = sorted(range(len(hand_sizes)), key=lambda i: len(out[i]), reverse=True)
        for attempt in range(num_attempts):
            result = [[] for _ in hand_sizes]
            failed = False
            deck = INITIAL_DECK
            dead_cards = set(initial_dead_cards)
            for i in order:
                o = out[i]
                n = hand_sizes[i]
                if not n:
                    result[i] = []
                    continue
                deck = [card for card in deck if as_tuple(card) not in dead_cards]
                if o and attempt != (num_attempts - 1):
                    possible_cards = [card for card in deck if card.suit not in o]
                else:
                    possible_cards = deck
                if len(possible_cards) < n:
                    failed = True
                    break
                hand = random.sample(possible_cards, n)
                result[i] = hand
                dead_cards |= {as_tuple(card) for card in hand}
            if failed:
                continue
            return result

    def plan_make_bet(self, turn_order, trump):
        scores = [0 for _ in range(8)]
        self.tricks_won = {bot.name: 0 for bot in turn_order}
        self.turn_order = [bot.name for bot in turn_order]
        self.my_index = next(i for i, bot in enumerate(turn_order) if bot == self)
        self.hand_sizes = {bot.name: 7 for bot in turn_order}
        self.trump = trump
        hand_sizes = [7 * (i != self.my_index) for i, _ in enumerate(turn_order)]
        self.dead_cards = {as_tuple(card) for card in self.hand}
        self.out = {bot.name: set() for bot in turn_order}
        for _ in range(1500):
            hands = deal([[] for _ in turn_order], self.dead_cards, hand_sizes)
            hands[self.my_index] = list(self.hand)
            tricks_won = simulate_random_game(hands, trump, 0, [])[self.my_index]
            scores[tricks_won] += 1
        bet = max(enumerate(scores), key=lambda t: (10 + t[0]) * t[1])[0]
        self.bet = bet
        return self.bet

    def plan_play_card(self, current_trick):
        hand_sizes = dict(self.hand_sizes)
        for bot, card in current_trick:
            self.dead_cards.add(as_tuple(card))
            hand_sizes[bot] -= 1
        hand_sizes[self.name] = 0
        current_suit = current_trick[0][1].suit if current_trick else None
        for bot, card in current_trick[1:]:
            if card.suit != current_suit:
                self.out[bot].add(current_suit)
        out = [self.out[bot] for bot in self.turn_order]
        plays = list(valid_plays(self.hand, current_suit))
        bust = ((self.tricks_won[self.name] + len(self.hand)) < self.bet) or (self.tricks_won[self.name] > self.bet)
        if len(plays) == 1:
            return self.hand[plays[0]]
        if bust:
            a = 1. / (len(self.turn_order) - 1)
            outcomes = [[a] * (len(self.turn_order) - 1) for _ in plays]
        else:
            outcomes = [[1, 1] for _ in plays]
        hand_sizes = [hand_sizes[bot] for bot in self.turn_order]
        current_trick = [card for _, card in current_trick]
        all_bets = {k.name: v for k, v in self.all_bets.items()}
        for _ in range(1500):
            current_trick_copy = list(current_trick)
            hands = deal(out, self.dead_cards, hand_sizes)
            my_hand = hands[self.my_index] = list(self.hand)
            scores = [dirichlet_score(counts) for counts in outcomes]
            chosen_play = scores.index(max(scores))
            current_trick_copy.append(my_hand[chosen_play])
            my_hand[chosen_play] = my_hand[-1]
            my_hand.pop()
            tricks_won = simulate_random_game(hands, self.trump, (self.my_index + 1) % len(hands), current_trick_copy)
            if bust:
                outcome = -(1 + sum(self.tricks_won[bot] + trick_count == all_bets[bot] for bot, trick_count in zip(self.turn_order, tricks_won)))
            else:
                outcome = (self.tricks_won[self.name] + tricks_won[self.my_index]) == self.bet
            outcomes[chosen_play][outcome] += 1
        best_play = max(enumerate(plays), key=lambda t: sum(outcomes[t[0]]))[1]
        return self.hand[best_play]

    def plan_update_round(self, current_scores, rounds_left):
        pass

    def plan_update_play(self, final_trick, winner):
        for bot in self.hand_sizes:
            self.hand_sizes[bot] -= 1
        lead_suit = final_trick[0][1].suit
        for bot, card in final_trick[1:]:
            self.dead_cards.add(as_tuple(card))
            if card.suit != lead_suit:
                self.out[bot].add(lead_suit)
        winner = max(final_trick, key=lambda t: (t[1].suit == self.trump, t[1].suit == final_trick[0][1].suit, t[1].rank))[0]
        self.tricks_won[winner] += 1

    plan_bot = ("PlanBot", plan_make_bet, plan_play_card, plan_update_round, plan_update_play)

```
> 2 votes

# Answer
# Half

```
def half_make_bet(self, _, trump):
    self.trump = trump
    self.wins = 0
    self.bet = len([i for i in self.hand if i.rank > 8]) // 2
    return self.bet

def half_play_card(self, current_board):
    if not current_board:
        return min(self.hand,key=lambda card: card.rank)
    valid = [i for i in self.hand if i.suit == current_board[0][1].suit]
    if valid:
        return max(valid,key = lambda i: i.rank)
    if self.wins > self.bet:
        return self.hand[0]
    if self.bet - self.wins >= len([i for i in self.hand if i.rank > 8 or i.suit == self.trump]):
        return max(self.hand, key = lambda i: i.rank + 1000 * (i.suit == self.trump))
    return min(self.hand, key = lambda i: i.rank + 1000 * (i.suit == self.trump))

def half_update_round(self, a, b):
    pass

def half_update_play(self, a, w):
    self.wins += w == self.name

half_bot = ("Half", half_make_bet, half_play_card, half_update_round, half_update_play)

```
> 2 votes

# Answer
# Conservative Bot

This bot always bets 0, and tries its best to get rid of the biggest cards it has.

```

def conservative_make_bet(self, turn_order, trump):
    self.trump = trump
    return 0
def conservative_play_card(self,current_board):
    suit_count = {s:len([c for c in self.hand if c.suit == s]) for s in ["S","H","D","C"]}
    if current_board == []:
        if all(card.suit == self.trump for card in self.hand):
            return min(self.hand, key=lambda c: c.rank)
        return min([c for c in self.hand if c.suit != self.trump], key = lambda c: c.rank)
    trump_on_board = any(c[1].suit == self.trump for c in current_board)
    valid_cards = [c for c in self.hand if c.suit == current_board[0][1].suit]
    if valid_cards:
        if trump_on_board:
            return max(valid_cards, key = lambda c: c.rank)
        winning_card = max([c for c in current_board if c[1].suit == current_board[0][1].suit], key = lambda c: c[1].rank)
        losing_cards = [c for c in valid_cards if c.rank < winning_card[1].rank]
        if losing_cards:
            return max(losing_cards, key = lambda c: c.rank)
        return min(valid_cards, key = lambda c: c.rank)
    if trump_on_board:
        winning_card = max([c for c in current_board if c[1].suit == self.trump], key = lambda c: c[1].rank)
        small_trumps = [c for c in self.hand if c.rank < winning_card[1].rank and c.suit == self.trump]
        if any(card.suit != self.trump for card in self.hand) and not small_trumps:
            return max([c for c in self.hand if c.suit != self.trump], key = lambda c: c.rank * 8 + suit_count[c.suit])
        if small_trumps:
            return max(small_trumps, key = lambda c: c.rank)
        return min(self.hand, key = lambda c: c.rank)
    if all(card.suit == self.trump for card in self.hand):
        return min(self.hand, key = lambda c: c.rank)
    return max([c for c in self.hand if c.suit != self.trump], key = lambda c: c.rank * 8 + suit_count[c.suit])
def conservative_update_round(self, current_scores, rounds_left):
    pass
def conservative_update_play(self, final_board, winner):
    pass

conservative_bot = ("Conservative", conservative_make_bet,conservative_play_card,conservative_update_round,conservative_update_play)

```
> 2 votes

# Answer
# BasicCardStrat

```
def bcs_make_bet(self, turn_order, trump):
    self.wins = 0
    self.trump = trump
    self.played = []
    winners_by_suit = {"C": 14, "D": 14, "H": 14, "S": 14}
    for card in self.hand:
        if winners_by_suit[card.suit] == card.rank:
            winners_by_suit[card.suit] -= 1
    winner_count = 56 - winners_by_suit["C"] - winners_by_suit["D"] - winners_by_suit["H"] - winners_by_suit["S"]
    threshold = 3 + len(turn_order)
    face_count = sum(1 for x in self.hand if x.rank > threshold) - winner_count
    trump_count = sum(1 for x in self.hand if x.rank <= threshold and x.suit == self.trump)
    self.bet = int(winner_count * 0.75 + face_count * 0.33 + trump_count * 0.5)
    return self.bet

def bcs_play_card(self, current_board):
    # Check if we're winning more than projected
    winners_by_suit = {"C": 14, "D": 14, "H": 14, "S": 14}
    for card in self.hand:
        if winners_by_suit[card.suit] == card.rank:
            winners_by_suit[card.suit] -= 1
    winner_count = 52 - winners_by_suit["C"] - winners_by_suit["D"] - winners_by_suit["H"] - winners_by_suit["S"]
    face_count = sum(1 for x in self.hand if x.rank > 10) - winner_count
    trump_count = sum(1 for x in self.hand if x.rank <= 10 and x.suit == self.trump)
    ahead = int(winner_count * 0.75 + face_count * 0.33 + trump_count * 0.5) + self.wins - self.bet

    # Determine which cards are guaranteed winners (barring trump)
    winners_by_suit = {"C": 14, "D": 14, "H": 14, "S": 14}
    played_by_suit = {"C": 0, "D": 0, "H": 0, "S": 0}
    all_played = sorted(self.played, key=lambda x: -x.rank)
    for card in all_played:
        played_by_suit[card.suit] += 1
        if winners_by_suit[card.suit] == card.rank:
            winners_by_suit[card.suit] -= 1
    if not current_board:
        winners = [x for x in self.hand if winners_by_suit[x.suit] == x.rank]
        if len(winners):
            return next((x for x in winners if x.suit == self.trump), winners[0])
        if ahead > 0:
            return max(self.hand, key=lambda x: x.rank - (15 if x.suit == self.trump else 0))
        # Get rid of others' trump
        trump_cards = [x for x in self.hand if x.suit == self.trump]
        if trump_cards:
            return min(trump_cards, key=lambda x: x.rank)
        return min(self.hand, key=lambda x: x.rank + played_by_suit[x.suit])
    lead_suit = current_board[0][1].suit
    valid = [x for x in self.hand if x.suit == lead_suit]
    is_trumped = lead_suit != self.trump and any(x[1].suit == self.trump for x in current_board)
    current_winner = max([x.rank for (_,x) in current_board if (x.suit == lead_suit and not is_trumped) or (x.suit == self.trump)])

    # If I have more winners than tricks I want to take, try to slough one
    if ahead > 0:
        if valid:
            if is_trumped:
                current_winner = 15
            return max(valid, key=lambda x: -x.rank if x.rank > current_winner else x.rank)
        if is_trumped:
            trump_cards = [x for x in self.hand if x.suit == self.trump and x.rank < current_winner]
            if trump_cards:
                return max(trump_cards, key=lambda x: x.rank)
        return max(self.hand, key=lambda x: x.rank - (15 if x.suit == self.trump else 0))

    if not is_trumped:
        if valid:
            # If I want to win and I have a winner for this suit, play it.
            winner = next((x for x in valid if winners_by_suit[x.suit] == x.rank), None)
            if winner:
                return winner
            # Play my lowest winning card
            winners = [x for x in valid if (x.rank > current_winner)]
            if len(winners):
                return min(winners, key=lambda x: x.rank)
            return min(valid, key=lambda x: x.rank)
        winners = [x for x in self.hand if x.suit == self.trump]
        if len(winners):
            return min(winners, key=lambda x: x.rank)
    if is_trumped:
        # Have to follow suit if possible
        if len(valid):
            return min(valid, key=lambda x: x.rank)
        winners = [x for x in self.hand if x.rank > current_winner and x.suit == self.trump]
        if len(winners):
            return min(winners, key=lambda x: x.rank)

    # Finally, play my worst card
    if valid:
        return min(valid, key=lambda x: x.rank)
    return min(self.hand, key=lambda x: x.rank + (15 if x.suit == self.trump else 0))

def bcs_update_round(self, a, b):
    pass

def bcs_update_play(self, final_board, winner):
    self.played += [x[1] for x in final_board]
    if self.name == winner:
        self.wins += 1

bcs_bot = ("BasicCardStrat", bcs_make_bet, bcs_play_card, bcs_update_round, bcs_update_play)

```

Some very simple card game strategy. Play winners, try to win with trump, slough when needed. Feel free to adapt this into other bots.
> 1 votes

# Answer
# sans.

sans has arrived to pass Judgement. However, being sans, he aims low and plays lazily.

```
def sans_make_bet(self,turn_order,trump):
    return 1

def sans_play_card(self,current_board):
    if current_board:
        for card in self.hand:
            if card.suit == current_board[0][1].suit:
                return card
    return self.hand[-1]

def sans_update_round(self, current_scores, rounds_left):
    pass
def sans_update_play(self, final_board, winner):
    pass

sans = ("sans.", sans_make_bet, sans_play_card, sans_update_round, sans_update_play)

```
> 1 votes

# Answer
# Random Bot

Simulates a random game and guesses the number of hands it wins in that random game. It always chooses a random card.

<pre><code>from random import sample

def make_random_bot():

  def pick_random(hand, suit):
    if suit is None:
      return sample(hand, 1)[0]
    shuffled = sample(hand, len(hand))
    for card in shuffled:
      if card.suit == suit:
        return card
    return shuffled[0]

  def simulate_random_game(hands, trump):
    hands = [[c for c in hand] for hand in hands]
    hands_won = [0] * len(hands)

    last_won = 0
    for h in range(7):
      last_suit = None
      cards = []
      for i in range(len(hands)):
        player = (i + last_won) % len(hands)
        card = pick_random(hands[player], last_suit)
        last_suit = card.suit
        hands[player].remove(card)
        cards.append(card)
      winner_i = max(range(i), key=lambda i: (cards[i].suit == trump, cards[i].suit == cards[0].suit, cards[i].rank))
      last_won = (winner_i + last_won) % len(hands)
      hands_won[last_won] += 1
    return hands_won

  def make_bet(self,turn_order,trump):
    cards = list(set(Deck().cards) - set(self.hand))

    other_cards = sample(cards, k=7*(len(turn_order) - 1))
    hands = []
    i = 0
    for bot in turn_order:
      if bot == self:
        hands.append(self.hand)
      else:
        hands.append(other_cards[i * 7: (i+1)*7])
        i += 1
    result = simulate_random_game(hands, trump)

    return result[turn_order.index(self)]

  def play_card(self,current_board):

    hand = sample(self.hand, k=len(self.hand))

    if current_board:
        for card in hand:
            if card.suit == current_board[0][1].suit:
                return card

    return hand[0]

  def nop(self, a, b):
    pass

  return ('Random', make_bet, play_card, nop, nop)

random_bot = make_random_bot()
```
</code></pre>
> 0 votes

---
Tags: king-of-the-hill, python, card-games
---


title: Optimal addition subtraction chain

text:
# Question
Title: Optimal addition subtraction chain
An addition-subtraction chain, is a sequence \\$a\_1, a\_2, a\_3, ... ,a\_n\\$, such that \\$a\_1=1\\$ and for all \\$i \> 1\\$, there exist \\$j,k\<i\\$ such that \\$a\_i = a\_j \pm a\_k\\$.

Your task, is given a number \\$x\\$, find the shortest addition-subtraction chain, such that \\$a\_n = x\\$.

## Rules

* You can assume the input is a valid integer
* In case there are multiple optimal addition-subtraction chains, you can print any non-empty subset of them
* You may use any reasonable I/O method (you can output it reversed, with any separator you want, in any base you want, ect.)

## Test cases

(these are one solution, you can output anything valid with the same length)

these are all the numbers with a addition subtraction chain of length 6 or less

```
-31 -> [1, 2, 4, 8, 16, -15, -31]
-30 -> [1, 2, 4, 8, 16, -15, -30]
-28 -> [1, 2, 4, 8, -6, -14, -28]
-24 -> [1, 2, 4, -2, -6, -12, -24]
-23 -> [1, 2, 4, 8, 12, 24, -23]
-22 -> [1, 2, 4, 6, -5, -11, -22]
-21 -> [1, 2, 3, 6, 12, -9, -21]
-20 -> [1, 2, 4, 6, -5, -10, -20]
-19 -> [1, 2, 4, 8, -3, -11, -19]
-18 -> [1, 2, 4, -1, 8, -9, -18]
-17 -> [1, 2, 4, -3, 7, -10, -17]
-16 -> [1, 2, 3, -1, -4, -8, -16]
-15 -> [1, 2, 4, 8, 16, -15]
-14 -> [1, 2, 4, 8, -7, -14]
-13 -> [1, 2, 4, 6, -3, -7, -13]
-12 -> [1, 2, 4, -3, -6, -12]
-11 -> [1, 2, 4, 6, -5, -11]
-10 -> [1, 2, 4, -2, -6, -10]
-9 -> [1, 2, 4, 8, -1, -9]
-8 -> [1, 2, 4, 8, 0, -8]
-7 -> [1, 2, 4, -3, -7]
-6 -> [1, 2, 4, 8, -6]
-5 -> [1, 2, 4, -3, -5]
-4 -> [1, 2, 4, 8, -4]
-3 -> [1, 2, -1, -3]
-2 -> [1, 2, 4, -2]
-1 -> [1, 0, -1]
0 -> [1, 0]
1 -> [1]
2 -> [1, 2]
3 -> [1, 2, 3]
4 -> [1, 2, 4]
5 -> [1, 2, 4, 5]
6 -> [1, 2, 4, 6]
7 -> [1, 2, 4, -3, 7]
8 -> [1, 2, 4, 8]
9 -> [1, 2, 3, 6, 9]
10 -> [1, 2, 4, 5, 10]
11 -> [1, 2, 4, 6, 5, 11]
12 -> [1, 2, 4, 6, 12]
13 -> [1, 2, 3, 5, 10, 13]
14 -> [1, 2, 4, 6, 10, 14]
15 -> [1, 2, 3, 6, 9, 15]
16 -> [1, 2, 4, 8, 16]
17 -> [1, 2, 4, 8, 9, 17]
18 -> [1, 2, 4, 8, 9, 18]
19 -> [1, 2, 4, 8, 9, 17, 19]
20 -> [1, 2, 4, 5, 10, 20]
21 -> [1, 2, 4, 8, 16, 5, 21]
22 -> [1, 2, 4, 8, 12, 24, 22]
23 -> [1, 2, 4, 8, 16, -15, 23]
24 -> [1, 2, 3, 6, 12, 24]
25 -> [1, 2, 4, 8, 12, 13, 25]
26 -> [1, 2, 4, 6, 10, 16, 26]
27 -> [1, 2, 4, 5, 9, 18, 27]
28 -> [1, 2, 4, 8, 12, 14, 28]
30 -> [1, 2, 4, 5, 10, 20, 30]
31 -> [1, 2, 4, 8, 16, -15, 31]
32 -> [1, 2, 4, 8, 16, 32]
33 -> [1, 2, 4, 8, 16, 32, 33]
34 -> [1, 2, 4, 8, 16, 17, 34]
36 -> [1, 2, 3, 6, 9, 18, 36]
40 -> [1, 2, 4, 8, 12, 20, 40]
48 -> [1, 2, 4, 8, 12, 24, 48]
64 -> [1, 2, 4, 8, 16, 32, 64]

```

you can find a list of all optimal addition subtraction chains for each of them here

This is code golf, so the shortest answer in bytes in each language wins.

# Answer
> 10 votes
# Brachylog, ~~19~~ 17 bytes

```
∧≜;1⟨∋{+|-}∋⟩ᵃ⁽?t

```

Try it online!

I guess I shouldn't be too surprised, but funnily enough this produces the exact same outputs as xash's solution--up to \\$n = 13\\$ after which both time out. Takes input through the output variable and outputs through the input variable.

```
   1                 Starting with 1,
             ᵃ       repeat on the list of previous results
∧≜;           ⁽      as few times as necessary:
       +             add
      { |-}          or subtract
    ⟨∋     ∋⟩        one element and another (not necessarily distinct),
               ?     such that the final list of results is the input variable
                t    and its last element is the output variable.

```

# Answer
> 7 votes
# Python 3, ~~88~~ 87 bytes

-1 byte thanks to dingledooper!

```
f=lambda n,x=[1],*a:x*(n in x)or f(n,*a,*[x+[a+c]for a in x for b in x for c in(b,-b)])

```

Try it online!

# Answer
> 7 votes
# JavaScript (ES6), 104 bytes

A very basic and quite long implementation. But it does solve all test cases in ~20 seconds on TIO.

```
f=(n,l)=>(g=([...a],x)=>a.push(x)<l?a.some(x=>a.some(y=>g(a,x+y)||g(a,x-y))):r=x==n&&a)([],1)?r:f(n,-~l)

```

Try it online!

# Answer
> 4 votes
# Haskell, 59 bytes

```
head.(`filter`a).elem
a=[1]:do h<-a;i<-h;j<-h;[i-j:h,i+j:h]

```

Try it online!

`a` is the infinite list of all the addition-subtraction chains, sorted by length. The function `head.(`filter`a).elem` takes an integer (say `n`) and returns the first chain in `a` which contains `n`.

# Answer
> 4 votes
# Husk, ~~18~~ 17 bytes

```
`ḟ¡SṀ:S×+S+m_;;1€

```

Try it online!

*-1 thanks to Leo*

The longer I look at this, the less I have any idea why it seems to work. Probably something to do with the `iterL` overload that I didn't even know existed. I need coffee

# Answer
> 3 votes
# Jelly, 23 bytes

```
1+;_ɗþ`FQ;€Ʋ€Ẏ$Fċ³¬Ɗ¿ċƇ

```

Try it online!

A full program taking a single argument and returning a list of all optimal addition subtraction chains, each in reverse order.

## Explanation

```
1                       | Start with 1
                   Ɗ¿   | While the following is true:
               F        | - Flatten list
                ċ³      | - Count the number of occurrences of the input
                  ¬     | - Not (i.e. = 0)
             $          | Do the following:
          Ʋ€            | - For each member of the list, do the following:
    ɗþ`                 |   - Do the following as a dyad mapping over the sublist for both left and right arguments
 +                      |     - Add
  ;                     |     - Concatenated to:
   _                    |       - Subtract
       F                |   - Flatten
        Q               |   - Uniquify
         ;€             |   - Concatenate each value to the original sublist
             Ẏ          | - Join lists together
                     ċƇ | Finally, keep only those list where the input appears

```

# Answer
> 2 votes
# Brachylog, 31 bytes

```
1g|g;Lc,1↔a₀ᵇb{kgj∋ᵐ{+|-}~t?}ᵐt

```

Try it online!

### How it works

`?` is the input of the current scope.

```
1g|g;Lc,1↔a₀ᵇb{kgj∋ᵐ{+|-}~t?}ᵐt
1g                              if ? is 1, return [1].
  |                             else
   g;L                          [[?], L]
      c                         [?, L0, L1, …] (try shorter lists first)
       ,1↔                      [1, L0, L1, …, ?]
              {             }ᵐ  map every
          a₀ᵇb                  prefix except the first ([1]):
                                f.e. [1, L0, L1]
               k                [1, L0]
                gj              [[1, L0], [1, L0]]
                  ∋ᵐ            select any element of each list, f.e.
                                [L0, 1]
                    {+|-}       try L0 + 1 and L0 - 1
                         ~t?    is equal to L1
                              t return the last prefix (which is the list)

```

# Answer
> 1 votes
# Charcoal, 42 bytes

```
Ｎθ⊞υ⟦¹⟧ＦυＦ¬⊙υ№κθＦιＦ⁻⁺⁺ιλ⁻ιλι⊞υ⁺ι⟦μ⟧Ｉ⊟Φυ№ιθ

```

Try it online! Link is to verbose version of code. Very¹ slow, so only try it with single-digit integers. Explanation:

```
Ｎθ

```

Input `x`.

```
⊞υ⟦¹⟧

```

Start a breadth-first search with the trivial chain of length 1.

```
ＦυＦ¬⊙υ№κθ

```

Loop over the search results until a chain is found that includes `x`.

```
ＦιＦ⁻⁺⁺ιλ⁻ιλι

```

Loop over all the sums and differences that aren't already in the chain.

```
⊞υ⁺ι⟦μ⟧

```

Push a new chain to the search list.

```
Ｉ⊟Φυ№ιθ

```

Print a chain that includes `x`.

¹Struggles to complete solutions requiring chains of length 6. At a cost of 6 bytes it's possible to speed it up by avoiding pushing duplicate chains to the search list but that's still only enough for it to find all chains of length 6.

# Answer
> 0 votes
# Ruby, 77 bytes

```
->n,*r{*a=1;(a.product(a){|x,y|r|=[a|[x+y],a|[x-y]]};a,*r=r)until a[-1]==n;a}

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 22 bytes

```
X¸¸[ćD©Iå#ãDOsÆ«ε®sª}«

```

Try it online!

Very slow, the performance can be improved a bit by adding three bytes:

```
X¸¸[ćD©Iå#ãDOsÆ«®KÙε®sª}«

```

Try it online!

---
Tags: code-golf, math
---


title: Simple integer operation calculator

text:
# Question
Title: Simple integer operation calculator
## Implement a simple integer operation scriptable calculator.

**Concept**

The accumulator starts at 0 and has operations performed on it. At the end of the program output the value of the accumulator.

**Operations:**

* `+` adds `1` to the accumulator
* `-` subtracts `1` from the accumulator
* `*` multiplies the accumulator by `2`
* `/` divides the accumulator by `2`

**Sample script**

The input `++**--/` should give the output `3`.

**Example implementation**

```
def calc(s)
    i = 0
    s.chars.each do |o|
        case o
            when '+'
                i += 1
            when '-'
                i -= 1
            when '*'
                i *= 2
            when '/'
                i /= 2
        end
    end
    return i
end

```

## Rules

* This is , so lowest answer in bytes wins, but is not selected.
* Creative implementations are encouraged.
* Standard loopholes are prohibited.
* You get the program via stdin or arguments, and you can output the answer via return value or stdout.
* Have fun.
* Division truncates down because it is integer division.
* The program `-/` returns `-1`.

**Test cases**

```
*///*-*+-+
-1
/*+/*+++/*///*/+-+//*+-+-/----*-*-+++*+**+/*--///+*-/+//*//-+++--++/-**--/+--/*-/+*//*+-*-*/*+*+/+*-
-17
+++-+--/-*/---++/-+*-//+/++-*--+*+/*/*/++--++-+//++--*/***-*+++--+-*//-*/+*/+-*++**+--*/*//-*--**-/-*+**-/*-**/*+*-*/--+/+/+//-+*/---///+**////-*//+-+-/+--/**///*+//+++/+*++**++//**+**+-*/+/*/*++-/+**+--+*++++/-*-/*+--/++*/-++/-**++++/-/+/--*/-/+---**//*///-//*+-*----+//--/-/+*/-+++-+*-*+*+-/-//*-//+/*-+//+/+/*-/-/+//+**/-****/-**-//+/+-+/*-+*++*/-/++*/-//*--+*--/-+-+/+/**/-***+/-/++-++*+*-+*+*-+-//+/-++*+/*//*-+/+*/-+/-/*/-/-+*+**/*//*+/+---+*+++*+/+-**/-+-/+*---/-*+/-++*//*/-+-*+--**/-////*/--/*--//-**/*++*+/*+/-+/--**/*-+*+/+-*+*+--*///+-++/+//+*/-+/**--//*/+++/*+*////+-*-//--*+/*/-+**/*//+*+-//+--+*-+/-**-*/+//*+---*+//*/+**/*--/--+/*-*+*++--*+//+*+-++--+-*-*-+--**+/+*-/+*+-/---+-*+-+-/++/+*///*/*-+-*//-+-++/++/*/-++/**--+-////-//+/*//+**/*+-+/+/+///*+*///*-/+/*/-//-*-**//-/-+--+/-*--+-++**++//*--/*++--*-/-///-+/+//--+*//-**-/*-*/+*/-*-*//--++*//-*/++//+/-++-+-*/*-+++**-/-*++++**+-+++-+-***-+//+-/**-+/*+****-*+++*/-*-/***/-/*+/*****++*+/-/-**-+-*-*-++**/*+-/*-+*++-/+/-++*-/*-****-*
18773342

```

# Answer
## Python 2, 48 bytes

```
i=0
for c in input():exec"i=i%s2&-2"%c
print i/2

```

Does `+2`, `-2`, `*2`, or `/2`. By doing `+2` and `-2` rather than `+1` and `-1`, we're working in doubled units, so the final output needs to be halved. Except, the floor-division `/` now needs to round down to a multiple of 2, which is done with `&-2`.
> 28 votes

# Answer
# Jelly, ~~18~~ 17 bytes

```
‘

’

:2
Ḥ
O0;ṛĿ/

```

Try it online!

### How it works

The first six lines define helper links with indices ranging from **1** to **6**; they increment, do nothing, decrement, do nothing, halve (flooring), and double.

The main link – `O0;ṛĿ/` – converts the input characters to their code points (`O`), prepends a **0** (initial value) to the array of code points `0;`, then reduces the generated array as follows.

The initial value is the first element of the array, i.e., the prepended **0**. The quicklink `ṛĿ` is called for every following element in the array, with the last return value as left argument and the current element as right one. It inspects its right argument () and evaluates the link with that index monadically (`Ŀ`), thus applying the desired operation.
> 12 votes

# Answer
## Haskell, 51 bytes

```
x#'+'=x+1
x#'-'=x-1
x#'*'=x*2
x#_=div x 2
foldl(#)0

```

Usage example: `foldl(#)0 $ "++**--/"` -\> `3`.
> 12 votes

# Answer
# Python 2, 54 bytes

```
i=0
for c in input():exec"i=i"+c+`~ord(c)%5%3`
print i

```

Input is taken as a string literal. `~ord(c)%5%3` maps the operators to the corresponding right operands.

Previously, I used `hash(c)%55%3` which didn't yield consistent results between different versions of Python. This encouraged me to explore other formulas.
> 10 votes

# Answer
# S.I.L.O.S, ~~133~~ 211 bytes

```
:s
def : lbl G GOTO
readIO
i-46
if i a
i+2
if i b
i+2
if i c
i+1
if i d
G e
:a
G v
:p
a-1
a/2
G o
:v
a+1
if a p
a-1
j=a
j/2
k=j
k*2
k-a
a/2
if k t
G o
:t
a-1
:o
G s
:b
a-1
G s
:c
a+1
G s
:d
a*2
G s
:e
printInt a

```

Takes the ASCII codes of operators.

Try it online with test cases:
`-/`
`++**--/`
`*///*-*+-+`
> 10 votes

# Answer
# Turing Machine - 23 states (684 bytes)

Try it here - permalink

```
0 * * r 0
0 _ . l 1
1 * * l 1
1 _ * l 2
2 * 0 r 3
3 _ * r 3
3 + _ l +
3 - _ l -
3 x _ l x
3 / _ l /
+ _ * l +
+ * * * 4
4 - * l 5
4 _ 1 r 6
4 0 1 l 7
4 1 0 l 4
- _ * l -
- * * * 5
5 - * l 4
5 _ * r 8
5 0 1 l 5
5 1 0 l 7
x * * l x
x 1 0 l 9
x 0 0 l a
9 _ 1 r 6
9 1 1 l 9
9 0 1 l a
a _ _ r 6
a 1 0 l 9
a 0 0 l a
/ _ * l /
/ * * l b
b * * l b
b _ * r c
c 0 0 r d
c 1 0 r e
d * * l 7
d 0 0 r d
d 1 0 r e
e _ * l 7
e - * l 4
e 0 1 r d
e 1 1 r e
8 * * r 8
8 - _ r 3
8 _ - r 3
7 * * l 7
7 _ * r f
f 0 _ r f
f 1 * r 6
f * _ l g
g * 0 r 6
6 * * r 6
6 _ * r 3
3 . _ l h
h _ * l h
h - _ l i
h * * l halt
i * * l i
i _ - r halt

```

Input should not contain any '\*' since it is a special character in Turing machine code. Use 'x' instead. Outputs the answer in binary.

**Unobfuscated Code**

```
init2 * * r init2
init2 _ . l init0
init0 * * l init0
init0 _ * l init1
init1 * 0 r readop
readop _ * r readop
readop + _ l +
readop - _ l -
readop x _ l x
readop / _ l /
+ _ * l +
+ * * * inc
inc - * l dec
inc _ 1 r return
inc 0 1 l zero
inc 1 0 l inc
- _ * l -
- * * * dec
dec - * l inc
dec _ * r neg
dec 0 1 l dec
dec 1 0 l zero
x * * l x
x 1 0 l x1
x 0 0 l x0
x1 _ 1 r return
x1 1 1 l x1
x1 0 1 l x0
x0 _ _ r return
x0 1 0 l x1
x0 0 0 l x0
/ _ * l /
/ * * l //
// * * l //
// _ * r div
div 0 0 r div0
div 1 0 r div1
div0 * * l zero
div0 0 0 r div0
div0 1 0 r div1
div1 _ * l zero
div1 - * l inc
div1 0 1 r div0
div1 1 1 r div1
neg * * r neg
neg - _ r readop
neg _ - r readop
zero * * l zero
zero _ * r zero1
zero1 0 _ r zero1
zero1 1 * r return
zero1 * _ l zero2
zero2 * 0 r return
return * * r return
return _ * r readop
readop . _ l fin
fin _ * l fin
fin - _ l min
fin * * l halt
min * * l min
min _ - r halt

```

**Explanation of the states:**

*Initialization:*
*These states are visited once at the beginning of each run, starting with init2*

* init2: Move all the way to the right and put a '.'. That way the TM knows when to stop. Change to 'init0'.
* init0: Move all the back to the left until the head reads a space. Then move one cell to the left. Change to 'init1'.
* init1: Put a zero and move one cell to the right and change to 'readop'.

*Reading instructions:*
*These states will be visited multiple times throughout the program*

* readop: Moves all the way to the right until it reads an operator or the '.'. If it hits an operator, change to the corresponding state (+,-,x,/). If it hits a '.', change to state 'fin'.
* return: Returns the head to the empty space between the running total and the operators. Then changes to 'readop'.

*Operations:*
*These operations do the actual dirty work*

* +: Move to the left until the head reads any non- whitespace character. If this character is a '-', move left and change to 'dec'. Otherwise, change to 'inc'.
* -: Similar to '+', except change to 'inc' if there is a '-' and 'dec' otherwise.
* inc: If the digit under the head is a 0 (or a whitespace), change it to 1 and change to 'zero'. If the digit is a 1, change it to 0, then repeat on the next digit.
* dec: Similar to inc, except 1 goes to 0, 0 goes to 1, and if the head reads a whitespace, change to 'neg'.
* x, x0, x1: Bitshift the number one to the left. Change to 'return'.
* /, //, div, div0, div1: Move all the way to the right of the number, then bitshift one to the right. If there is a '-', change to 'inc'. This simulates rounding down negative numbers. Otherwise, change to 'zero'
* neg: Place a '-' after the number then change to 'readop'
* zero, zero1, zero2: Remove leading zeros and change to 'readop'

*Cleanup:* *Makes the output presentable*

* fin, min: Move the '-' in front of the number if necessary. Halt.
> 10 votes

# Answer
# Perl 6,  ~~53~~  52 bytes

~~```
{([Ro] %(<+ - * />Z=>*+1,*-1,* *2,*div 2){.comb})(0)}

```~~
```
{[Ro](%(<+ - * />Z=>*+1,*-1,*×2,*div 2){.comb})(0)}

```

## Explanation:

```
# bare block lambda that has one implicit parameter ｢$_｣
{
  (
    # reduce the code refs using ring operator ｢∘｣ in reverse ｢R｣
    [R[o]]

      # produce a hash from:
      %(

        # list of pairs of "operator" to code ref
        # ( similar to ｢'+' => { $^a + 1 }｣ )

          # keys
          < + - * / >

        # keys and values joined using infix zip operator ｢Z｣
        # combined with the infix Pair constructor operator ｢=>｣
        Z[=>]

          # values (Whatever lambdas)
          * + 1,
          * - 1,
          * × 2, # same as ｢* * 2｣
          * div 2,

      ){

        # split the block's argument into chars
        # and use them as keys to the hash
        # which will result in a list of code refs
        .comb

      }

  # call composed code ref with 0
  )(0)
}

```

## Usage:

```
my $input = '++**--/'
my $output = {[Ro](%(<+ - * />Z=>*+1,*-1,*×2,*div 2){.comb})(0)}.( $input );
say $output; # 3
say $output.^name; # Int

```
> 8 votes

# Answer
# C, ~~63~~ ~~62~~ 57 bytes

```
s,t;c(char*x){for(;*x;s+=t<4?t?2-t:s:-s>>1)t=*x++%6;s=s;}

```

Wandbox
> 8 votes

# Answer
# 05AB1E, 20 bytes

*Thanks to **Emigna** for fixing the `-/`-bug!*

For 16 bytes if it wasn't integer division: `Î"+-*/""><·;"‡.V`.

```
Î…+-*"><·"‡'/"2÷":.V

```

Explanation:

```
Î                      # Push 0, which is our starting variable, and input
 …+-*                  # Push the string "+-*"
     "><·"             # Push the string "><·"
          ‡            # Transliterate. The following changes:
                           "+" -> ">"
                           "-" -> "<"
                           "*" -> "·"
           '/"2÷":     # Replace "/" by "2÷"
                  .V   # Evaluate the code as 05AB1E code...
                           '>' is increment by 1
                           '<' is decrement by 1
                           '·' is multiply by 2
                           '2÷' is integer divide by two
                       # Implicitly output the result

```

Uses the **CP-1252** encoding. Try it online!
> 6 votes

# Answer
# JavaScript ES6, ~~80~~ 68 bytes

```
k=>[...k].reduce((c,o)=>+{"+":c+1,"-":c-1,"*":c*2,"/":c/2|0}[o],0)

```

Saved a whopping 12 bytes thanks to Neil!
> 5 votes

# Answer
# Ruby, ~~48~~ ~~44~~ 42 + 1 = 43 bytes

+1 byte for `-n` flag. Takes input on STDIN.

```
i=0
gsub(/./){i=i.send$&,"+-"[$&]?1:2}
p i

```

See it on ideone (uses `$_` since ideone doesn't take command line flags): http://ideone.com/3udQ3H
> 5 votes

# Answer
# PHP 76 Bytes

```
for(;$c=$argv[1][$n++];)eval('$s=floor($s'.$c.(2-ord($c)%11%3).');');echo$s;

```
> 5 votes

# Answer
# Mathematica, ~~83~~ ~~73~~ 70 bytes

<sup>*10 bytes saved due to @MartinEnder.*</sup>

```
(#/*##2&@@#/.Thread[{"+","-","*","/"}->{#+1&,#-1&,2#&,⌊#/2⌋&}])@0&

```

Anonymous function. Takes a list of characters as input and returns a number as output. Golfing suggestions welcome.
> 4 votes

# Answer
# Python 2, ~~58~~ 56 bytes

-2 bytes thanks to @Lynn

```
r=0
for c in input():exec'r=r'+c+`2-ord(c)%11%3`
print r

```

The ordinals of the characters `+-*/` are `43,45,42,47` modulo 11 these are `10,1,9,3` modulo 3 those are `1,1,0,0`, 2 less those are `1,1,2,2` giving the amounts we need for each operation: `r=r+1`, `r=r-1`, `r=r*2`, and `r=r/2`

---

Previous:

```
r=0
for c in input():exec'r=r'+c+`(ord(c)%5==2)+1`
print r

```
> 4 votes

# Answer
# S.I.L.O.S, ~~175~~ 164 bytes

```
loadLine
a=256
o=get a
lbla
a+1
o-42
p=o
p-1
p/p
p-1
r-p
s=o
s-3
s/s
s-1
r+s
m=o
m/m
m-2
m|
r*m
t=r
t%2
d=o
d-5
d/d
d-1
t*d
d-1
d|
r-t
r/d
o=get a
if o a
printInt r

```

Try it online!

Sane input method. Correct integer division (round towards -infinity).
> 4 votes

# Answer
## 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

```
> 4 votes

# Answer
# C#, ~~87~~ 81 bytes

```
int f(string s){int i=0;foreach(var c in s)i=c<43?i*2:c<46?i+44-c:i>>1;return i;}

```

Ungolfed:

```
int f(string s)
{
    int i = 0;

    foreach (var c in s)
        i = c < 43 ? i * 2
          : c < 46 ? i + 44 - c
          : i >> 1;

    return i;
}

```

Input is assumed to be valid. Division by two is done by shifting right one bit, because regular division always rounds towards zero, and bit shifting always rounds down. Increment and decrement make handy use of the 1 distance between the ASCII codes for `+` and `-`.
> 4 votes

# Answer
# JavaScript (ES6), 57

```
a=>[...a].map(c=>a=c<'+'?a<<1:c<'-'?-~a:c<'/'?~-a:a>>1)|a

```

Note: the initial value for accumulator is the program string, using bit operations (~, \>\>, \<\<, |) it is converted to 0 at first use.

As a side note, the clever answer of @xnor would score 40 ported to javascript:

```
a=>[...a].map(c=>a=eval(~~a+c+2))&&a>>1

```

(if you like this, vote for him)

**Test**

```
f=a=>[...a].map(c=>a=c<'+'?a<<1:c<'-'?-~a:c<'/'?~-a:a>>1)|a

function update() {
  O.textContent = f(I.value);
}

update()
```

```
<input value='++**--/' id=I oninput='update()'><pre id=O></pre>
```
> 3 votes

# Answer
## GNU sed, ~~65~~ ~~59~~ 57 bytes

**Edit:** 2 bytes shorter thanks to Toby Speight's comments

```
s/[+-]/1&/g
s/*/2&/g
s:/:d0>@2&:g
s/.*/dc -e"0[1-]s@&p"/e

```

**Run:**

```
sed -f simple_calculator.sed <<< "*///*-*+-+"

```

**Output:**

```
-1

```

The `sed` script prepares the input for the `dc` shell call at the end, the latter accepting the input in Reverse Polish notation. On division, if the number is negative (`d0>`), the `[1-]` decrement command stored in register `@` is called. Conversion example: `+ - * /` --\> `1+ 1- 2* d0>@2/`.
> 3 votes

# Answer
# PHP, 75 bytes

This uses a modified version of Jörg Hülsermann's answer.

```
eval(preg_replace('~.~','$s=($s\0(2-ord("\0")%11%3))|0;',$argv[1]));echo$s;

```

It heavily relies on string substitution, using a simple regular expression (`~.~`).

The variable `$s` is re-assigned with the new value for each character. At the end, it outputs the result.

---

**Note**: This is meant to be executed using the `-r` flag.

---

Try it here:

```
if('\0' == "\0")
{
 $argv = Array($s = 0, prompt());
 function preg_replace($pattern, $replacement, $subject)
 {
  $regexp = new RegExp($pattern.replace(new RegExp('~', 'g'), ''), 'g');
  return $subject.replace($regexp, $replacement.split('\0').join('$&'));
 }

 function printf($string)
 {
  console.log($string);
 }

 function ord($chr)
 {
  return $chr.charCodeAt(0);
 }
}
else
{
    if(!isset($argv))
    {
        $argv = array('', '++*+');
    }
}

eval(preg_replace('~.~','$s=($s\0(2-ord("\0")%11%3))|0;',$argv[1]));printf($s);
```

Or try on: http://sandbox.onlinephpfunctions.com/code/7d2adc2a500268c011222d8d953d9b837f2312aa

Differences:

* Instead of `echo$s`, I'm using `sprintf($s)`. Both perform the same action on numbers. Since this is just for testing, it is fine.
* In case there's no passed argument, it will run as if you passed `++*+` as the first argument, which should show `5`.
> 3 votes

# Answer
# Java, 77 bytes

```
int f(String s){return s.chars().reduce(0,(r,c)->c<43?r*2:c<46?r+44-c:r>>1);}

```

Uses java 8 streams.
> 3 votes

# Answer
# Python 3, ~~98~~ ~~66~~ 60 bytes

Thanks Tukkax!

Not as golfy as the other answer, but I can't compete with them without plagiarism.

```
i=0
for c in input():i+=[1,-i//2,-1,i][ord(c)%23%4]
print(i)

```

Also, I have a recursive lambda solution as well

**~~73~~ 67 bytes** (improved!)

```
s=lambda x,z=0:s(x[1:],z+[1,-z//2,-1,z][ord(x[0])%23%4])if x else z

```
> 2 votes

# Answer
## Pyke, ~~24~~ 22 bytes

```
\*\}:\/\e:\+\h:\-\t:0E

```

Try it here!

### Or 12 bytes (noncompetitive)

```
~:"ht}e".:0E

```

Try it here!

Add `translate` node - basically multiple find and replace.

```
~:           -   "+-*/"
        .:   -  input.translate(^, V)
  "ht}e"     -   "ht}e"
          0E - eval(^, stack=0)

```
> 2 votes

# Answer
## Batch, 61 bytes

```
@set n=
@for %%a in (%*)do @set/an=n%%a2^&-2
@cmd/cset/an/2

```

Translation of @xnor's xcellent Python answer.
> 2 votes

# Answer
# PHP, ~~104~~ ~~102~~ 82 bytes

First version with eval:

```
$i=0;while($c<9999)eval('$i'.['+'=>'++','-'=>'--','*'=>'*=2','/'=>'>>=1'][$argv[1]{$c++}].';');echo$i;

```

Second version with ternary operators:

```
while($o=ord($argv[1]{$c++}))$i=$o<43?$i*2:($o<44?$i+1:($o<46?$i-1:$i>>1));echo$i;

```

Takes the input string as first argument from the command line.

~~This "only" works for input strings shorter than 10,000 characters - which should be plenty. Tested with all the test cases, unfortunately can't save on the initialization in the beginning.~~ Second version works with strings of any length and without initialization. :-)

The main element is the eval function which manipulates `$i` based on a map of arithmetic operations, which are pretty straightforward except for the division. PHP returns a float when using `/` and `intdiv` is too many bytes, so we do a right-shift.

## Updates

1. Saved 2 bytes by shortening `$i=$i>>1` to `$i>>=1` for integer division.
2. Threw out eval in favor of ternary operators.
> 2 votes

# Answer
# R, 201 bytes

**Golfed**

```
p=.Primitive;"-"="+"=function(x)p("+")(x,1);body(`-`)[[1]]=p("-");"*"="/"=function(x)p("*")(x,2);body(`/`)[[1]]=p("%/%");Reduce(function(f, ...)f(...),rev(mget(strsplit(scan(stdin(),""),"")[[1]])),0,T)

```

**Commented**

```
p = .Primitive                       # Redefine
"-" = "+" = function(x)p("+")(x,1)   # Define - and +
body(`-`)[[1]] = p("-")              # Change the body, what we do to save a byte
"*" = "/" = function(x)p("*")(x,2)   # Same as above
body(`/`)[[1]] = p("%/%")            # Same as above
Reduce(function(f, ...)f(...),       # Function wrapper to evaluate list of func.
  rev(mget(strsplit(scan(stdin(),""),"")[[1]])), # Strsplit input into list of functions
  init = 0,                                      # Starting Arg = 1
  right = T)                                     # Right to left = True

```

Strategy is to refine the `+, -, %` operators. Split the string then parse the string into a long list of functions, to be fed into `Reduce()'s` accumulator.

Couldn't golf it anymore. If someone can get `b=body<-` to work, there could be a few bytes of savings (refine every function with `b` after `"-"="+"="/"="*"`). Initially tried to substitute and parse eval, but the order of operations and parentheses were terrifying.
> 2 votes

# Answer
# Python3, 98 85 74 bytes

```
C=lambda s,n:s and C(s[1:],{3:n+1,5:n-1,2:n*2,7:n/2}[ord(s[0])%10])or n//1

```

A recursive solution that loops over the string and takes the (modulo 10) from the ASCII value of the iterated character and treats the carried number accordingly. The dictionary keys are the last digits of the possible ASCII values that may occur (+, -, \*, /) and the values are the corresponding results for the symbol.We pass the input string `s` forward by taking everything onward from the next character with `s[1:]` (thanks to @Destructible Watermelon!).

Could be shortened even more, by picking the actions from a list and moduloing to keep the index in range, but that feels like plagiarism at this point, so unless I find my own method for that, it won't happen.

Called like: `C("+-+**+/",0)` ==\> 2.0

(Ps. Is it allowed to return `-1.0` from input `-/`?)
> 1 votes

# Answer
## PHP, 79 bytes

```
<?$i=0;switch($_POST['a']){case"+":$i+1;case"-":$i-1;case"/":$i/2;case"*":$i*2}

```
> 1 votes

# Answer
# Lex + C, ~~78~~, ~~74~~, 73 bytes

The first character is a space.

```
 c;F(){yylex(c=0);return c;}
%%
\+ c++;
- c--;
\* c*=2;
\/ c=floor(c/2.);

```

Reads from `stdin`, returns result.

Compile with `lex golfed.l && cc lex.yy.c main.c -lm -lfl`, test main:

```
int main() { printf("%d\n", F()); }

```
> 1 votes

# Answer
# PHP, 146 138, 133, 131 bytes

```
$a=$_POST['s'];$i=0;while($a){$c=substr($a,0,1);$i=$c=='+'?$i+=1:($c=='-'?$i-1:($c=='*'?$i*2:round($i/2)));$a=substr($a,1);}echo$i;

```
1. Takes argument from $\_POST\['s'\].
2. Uses ternary operator as "if's".
3. Takes one character at a time, parse that char in operation, then continue reading next char
4. EDIT 1: Shortened "*while(strlen($a))*" to "*while($a)*"
5. EDIT 2: Removed some useless paranthesis
6. EDIT 3. Removed extra space after last "*echo*"
> 1 votes

# Answer
# Javascript (ES5), 127 bytes

```
function(b){for(a=c=0;a<b.length;++a)switch(b[a]){case"+":++c;break;case"-":--c;break;case"*":c*=2;break;case"/":c/=2}return c}

```

Ungolfed:

```
function c(a){
  c=0;
  for(var i=0;i<a.length;++i){
    switch(a[i]){
      case "+":++c;break;
      case "-":--c;break;
      case "*":c*=2;break;
      case "/":c/=2;break;
    }
  }
  return c;
}

```
> 1 votes

# Answer
# Pyth, 23 bytes

```
FNQ=Z.v%".&%sZ2_2"N;/Z2

```

A full program that takes input as a string and prints the result.

This is a port of @xnor's Python answer.

Try it online

**How it works**

```
FNQ=Z.v%".&%sZ2_2"N;/Z2   Program. Input: Q. Z initialised as 0
FNQ                       For. For N in Q:
        ".&%sZ2_2"         String. Literal string ".&%sZ2_2"
       %          N        String format. Replace %s with the current operator N
           %sZ2            Operator. Yield Z*2, Z//2, Z+2, Z-2 as appropriate
         .&    _2          Bitwise and. Result of above & -2
     .v                    Evaluate. Yield the result of the expression
   =Z                      Assignment. Assign result of above to Z
                   ;      End. End for loop
                    /Z2   Integer division. Yield Z//2
                          Print. Print the above implicitly

```
> 1 votes

# Answer
# Ruby, 37 bytes

```
#!ruby -n
gsub(/./){eval"$.=$./2*2#$&2"}
p$./2

```

The shebang counts as 1 byte. This program uses xnor's creative approach. We avoid the need to initialise an accumulator variable by using `$.`. As it has a value of 1 after the input is read, we have to clear the LSB before applying each operator. This also requires changing `&-2` to `/2*2` for the correct precedence.
> 1 votes

# Answer
# Java 7, 73 bytes

```
int c(char[]i){int r=0;for(int c:i)r=c<43?r*2:c<46?r+44-c:r>>1;return r;}

```

Shamelessly stolen from *@Scepheo*'s amazing C# answer and implemented in Java 7.

**Ungolfed & test cases:**

Try it here.

```
class M{
  static int c(char[] i){
    int r = 0;
    for(int c : i) {
      r = c < 43
           ? r * 2
           : c < 46
              ? r+44 - c
              : r >> 1;
    }
    return r;
  }

  public static void main(String[] a){
    System.out.println(c("*///*-*+-+".toCharArray()));
    System.out.println(c("/*+/*+++/*///*/+-+//*+-+-/----*-*-+++*+**+/*--///+*-/+//*//-+++--++/-**--/+--/*-/+*//*+-*-*/*+*+/+*-".toCharArray()));
    System.out.println(c("+++-+--/-*/---++/-+*-//+/++-*--+*+/*/*/++--++-+//++--*/***-*+++--+-*//-*/+*/+-*++**+--*/*//-*--**-/-*+**-/*-**/*+*-*/--+/+/+//-+*/---///+**////-*//+-+-/+--/**///*+//+++/+*++**++//**+**+-*/+/*/*++-/+**+--+*++++/-*-/*+--/++*/-++/-**++++/-/+/--*/-/+---**//*///-//*+-*----+//--/-/+*/-+++-+*-*+*+-/-//*-//+/*-+//+/+/*-/-/+//+**/-****/-**-//+/+-+/*-+*++*/-/++*/-//*--+*--/-+-+/+/**/-***+/-/++-++*+*-+*+*-+-//+/-++*+/*//*-+/+*/-+/-/*/-/-+*+**/*//*+/+---+*+++*+/+-**/-+-/+*---/-*+/-++*//*/-+-*+--**/-////*/--/*--//-**/*++*+/*+/-+/--**/*-+*+/+-*+*+--*///+-++/+//+*/-+/**--//*/+++/*+*////+-*-//--*+/*/-+**/*//+*+-//+--+*-+/-**-*/+//*+---*+//*/+**/*--/--+/*-*+*++--*+//+*+-++--+-*-*-+--**+/+*-/+*+-/---+-*+-+-/++/+*///*/*-+-*//-+-++/++/*/-++/**--+-////-//+/*//+**/*+-+/+/+///*+*///*-/+/*/-//-*-**//-/-+--+/-*--+-++**++//*--/*++--*-/-///-+/+//--+*//-**-/*-*/+*/-*-*//--++*//-*/++//+/-++-+-*/*-+++**-/-*++++**+-+++-+-***-+//+-/**-+/*+****-*+++*/-*-/***/-/*+/*****++*+/-/-**-+-*-*-++**/*+-/*-+*++-/+/-++*-/*-****-*".toCharArray()));
  }
}

```

**Output:**

```
-1
-17
18773342

```
> 1 votes

# Answer
# ARM Machine Code, 30 bytes

Hex Dump (little endian):

```
2000 f811 2b01 b14a 2a2a bf08 0040 d0f8 2a2e bf3a 3a2c 1a80 1040 e7f2 4770

```

This is a function that takes in a string, and returns the accumulated result. In C, the function would be declared int sioc(int dummy, char\* string) where the dummy argument is ignored. Tested on the Raspberry Pi 3. No libraries or system calls are used.

Ungolfed assembly:

```
.syntax unified
.text
.global sioc
.thumb_func
sioc:
    @Input: r0 - dummy argument
    @r1 - string of operations
    @Output: r0 - result of those operations
    movs r0,#0 @Initialize accumulator to 0
    loop:
        ldrb r2,[r1],#1 @r2=*r1++
        cbz r2,end @If (r2==0), goto end
    mul:
        cmp r2,#42
        it eq @if r2==42
        lsleq r0,r0,#1 @r0<<=1
        beq loop @continue
    addsub: @else
        cmp r2,#46
        itte lo @If r2<46, then r2 is either + or -
        sublo r2,r2,#44
        sublo r0,r0,r2 @Add 1 if r2 is +, subtract 1 if r0 is -
        asrhs r0,r0,#1 @else arithmatically shift right by 1
        b loop @while (true)
    end:
        bx lr

```

Testing script (also assembly):

```
.syntax unified
.text
.global main
.thumb_func
main:
    ldr r1,[r1,#4] @r0=argv[1]
    bl sioc
    mov r1,r0
    adr r0,msg
    bl printf
    movs r7,#1
    swi #0
.balign 4
msg:
    .asciz "%d\n"

```
> 1 votes

# Answer
# Java 8, 56 bytes

```
s->s.chars().reduce(0,(r,c)->c<43?r*2:c<46?r+44-c:r>>1);

```
> 1 votes

# Answer
# Haskell - 70 bytes

```
f x=foldl1(flip(.))[[(*2),succ,id,pred,id,(`div`2)]!!(ord n-42)|n<-x]0

```

64 if I may take the input in RPN:

```
f x=foldl1(.)[[(*2),succ,id,pred,id,(`div`2)]!!(ord n-42)|n<-x]0

```

In addition to `+` `-` `*` `/` my implementation also support `,` and `.`, both of which does nothing. It crashes for any other input.
> 1 votes

# Answer
## Racket 116 bytes

```
(λ(s)(let((l(string->list s))(a 0))(for((i l))(set! a(match i[#\+(+ a 1)][#\-(- a 1)][#\*(* a 2)][#\/(/ a 2)])))a))

```

Ungolfed version:

```
(define f
  (lambda(s)
    (let ((l (string->list s))
          (a 0))
      (for ((i l))
        (set! a (match i
                  [#\+ (+ a 1)]
                  [#\- (- a 1)]
                  [#\* (* a 2)]
                  [#\/ (/ a 2)]
                )))
      a)))

```

Testing:

```
(f "++**--/")

3

```
> 1 votes

# Answer
# GolfScript \- 45 bytes

```
{1+}:"+";{1-}:"-";{2/}:"/";{2*}:"*";0\1/{`~}/

```

### Explanation

```
{1+}:"+";  # Creates aliases for operators
{1-}:"-";
{2/}:"/";
{2*}:"*";
0\1/       # Pushes 0 and splits the string in bytes
{`~}/      # Executes each character

```
> 1 votes

# Answer
# TSQL, 115 bytes

After some golfing I was finally able to replace `-IIF(@<0,@,@+1)/2` with `(@+ABS(@%2))/-2` saving 2 bytes.

**Golfed:**

```
DECLARE @i varchar(max)='*///*-*+-+'
,@ INT=0WHILE @i>''SELECT @+=CHOOSE(CHARINDEX(LEFT(@i,1),'+-*/'),1,-1,@,(@+ABS(@%2))/-2),@i=STUFF(@i,1,1,'')PRINT @

```

**Ungolfed:**

```
DECLARE @i varchar(max)='*///*-*+-+'

,@ INT=0
WHILE @i>''
  SELECT @+=CHOOSE(CHARINDEX(LEFT(@i,1),'+-*/'),1,-1,@,(@+ABS(@%2))/-2),
  @i=STUFF(@i,1,1,'')
PRINT @

```

**Fiddle**
> 0 votes

# Answer
# MMIX, 64 bytes (16 instrs)

```
00000000: e3010000 f000000b 31ff022f 5aff0003  ẉ¢¡¡ṅ¡¡¿1”£/Z”¡¤
00000010: 3d010101 f0000007 31ff022a 5aff0003  =¢¢¢ṅ¡¡¬1”£*Z”¡¤
00000020: 39010101 f0000003 34ff2c02 200101ff  9¢¢¢ṅ¡¡¤4”,£ ¢¢”
00000030: 81ff0000 e7000001 5b02fff4 f8020000  ¹”¡¡ḃ¡¡¢[£”ṡẏ£¡¡

```

```
clc SET  $1,0           // acc = 0
    JMP  1F             // goto load
0H  CMP  $255,$2,'/'
    PBNZ $255,2F        // loop: if(c != '/') goto notdiv
    SR   $1,$1,1        // acc /= 2
    JMP  1F             // goto load
2H  CMP  $255,$2,'*'
    PBNZ $255,2F        // notdiv: if(c != '*') goto notmul
    SL   $1,$1,1        // acc *= 2
    JMP  1F             // goto load
2H  NEG  $255,',',$2
    ADD  $1,$1,$255     // notmul: acc += ',' - c
1H  LDB  $255,$0
    INCL $0,1           // load: c = *s++
    PBNZ $255,0B        // if(c) goto loop
    POP  2,0            // return acc

```
> 0 votes

# Answer
# Stax, 12 bytes

```
î┴$'▌>bå╦♦\‼

```

Run and debug it

14 bytes unpacked.
> 0 votes

---
Tags: code-golf, math, number, arithmetic
---