title: Escape a chessboard

text:
# Question
Title: Escape a chessboard
You find yourself on a chessboard, as one does. You can see the exit but it is awfully far away and you would rather not walk all the way. Luckily some locals have offered you a ride. A Knight, a Rook, a Bishop and a King are all willing to take you to your destination, but seeing how this is a chessboard they must each abide by the rules of chess on the way to your destination. You would like to get out of here as soon as possible, whose offer do you accept?

# Task

Given a arbitrarily shaped and sized chessboard and two points on the chess board, output the chess piece that can move between the two locations in as few moves as possible. Boards will not necessarily be continuous meaning that there could be gaps between sections of the board. Each of the four pieces (King, Rook, Knight, and Bishop) can move according to their standard rules in chess. The Queen and pawn pieces have been intentionally left out of this challenge.

# I/O

You may take input in any reasonable format and you may output in whatever format you choose as well. Your input and output must be self-consistent. If multiple pieces can make it to the destination in the same number of moves you must output all of the pieces that can get there in the minimum amount of time. If none of the four pieces can make it to the end you may output anything as long as it is distinct from all other possible outputs. This could include outputting nothing or throwing an error.

# Test Cases

A square indicates the starting point and a circle indicates the ending point.

---

Bishop

---

Knight

---

King

---

Rook

---

King, Knight

---

None

# Answer
> 8 votes
# Haskell, ~~447~~ ~~439~~ ~~437~~ 432 bytes

```
t=[1,2]
p=[(+),(-)]
f=filter
a=abs
(#)=elem
x?y=[min x y..max x y]
f&g=(\x->g x>>=f)
(b!1)(c,r)=f(#b)[(c!d,r#s)|(!)<-p,(#)<-p,d<-t,s<-t,d/=s]
(b!2)(c,r)=f(\(d,s)->(c==d&&all(#b)[(c,z)|z<-r?s])||r==s&&all(#b)[(z,r)|z<-c?d])b
(b!3)(c,r)=f(\(d,s)->a(c-d)==a(r-s)&&all(#b)(zip(c?d)$r?s))b
(b!4)(c,r)=f(\(d,s)->a(c-d)<2&&a(r-s)<2)b
(b%p)n s=[s]>>=foldr(&)(:[])(replicate n$b!p)
g b s e=head$f(not.null)[[p|p<-[1..4],e#(b%p)n s]|n<-[0..]]

```

Call using `g <board> <start> <end>` where `<board> :: [(Int, Int)]`, `<start> :: (Int, Int)` and `<end> :: (Int, Int)`. Returns a list containing `1` for Knight, `2` for Rook, `3` for Bishop, and `4` for King. If no solutions are found, it consistently overflows the stack (that counts as throwing an error, right?).

Inspiration taken from LYAH's chapters on Monads—`(%)` is just a generalized and golfed `inMany`, with `(&)` equivalent to `(Control.Monad.<=<)`. Everything else should be more-or-less self-explanatory.

This can probably be golfed a lot more, but I've had enough fun for now.

Ungolfed:

```
data Piece = Knight | Rook | Bishop | King deriving (Show)
type Place = (Int, Int)
type Board = [Place]

x `to` y = [min x y..max x y]

f <=< g = (\x -> g x >>= f)

moves
    :: Board    -- available spaces
    -> Piece    -- type of piece
    -> Place    -- starting place
    -> [Place]  -- places available in one move
moves b Knight (c,r) =
    filter (`elem` b) [(c!d, r#s) |
                       (!) <- [(+),(-)], (#) <- [(+),(-)],
                       d <- [1,2], s <- [1,2], d/=s]
moves b Rook   (c,r) =
    filter (\(d,s) -> (c == d && all (`elem` b) [(c,z) | z <- r `to` s])
                    || r == s && all (`elem` b) [(z,r) | z <- c `to` d]) b
moves b Bishop (c,r) =
    filter (\(d,s) -> abs(c-d) == abs(r-s)
                && all (`elem` b) (zip (c `to` d) (r `to` s))) b
moves b King   (c,r) =
    filter (\(d,s) -> abs(c-d) <= 1 && abs(r-s) <= 1) b

canGoIn
    :: Board    -- available spaces
    -> Piece    -- type of piece
    -> Int      -- number of moves
    -> Place    -- starting place
    -> [Place]  -- places available in the specified number of moves
canGoIn b p n s =
    return s >>= foldr (<=<) return (replicate n (moves b p))

quickestPieces
    :: Board    -- available spaces
    -> Place    -- starting place
    -> Place    -- ending place
    -> [Piece]  -- quickest pieces
quickestPieces b s e =
        head $ filter (not.null)
            [[p | p <- [Knight, Rook, Bishop, King], elem e (canGoIn b p n s)] |
                n<-[0..]]

```

# Answer
> 5 votes
# Mathematica, ~~326~~ 325 bytes

*Thanks to masterX224 for pointing out a byte savings!*

```
f[g_,w_,x_]:=(c={{1,1},{-1,1}};s=c.c/2;e=#<->#2&@@@#&;j=Join;h=FindShortestPath;t=#~Tuples~2&;a@d_:=e@Select[t@g,#-#2&@@#==d&];y@k=j@@(a/@j[s,c]);y@n=j@@(a/@{{1,2},{2,1},{-2,1},{-1,2}});v=Flatten[e@t@#&/@ConnectedComponents@a@#&/@#]&;y@r=v@s;y@b=v@c;Pick[p={b,k,n,r},z=Length[h[y@#,w,x]/.h@__->0]&/@p,Min[z~Complement~{0}]]);

```

Defines a function `f` taking three arguments: `g` is a list of ordered pairs of integers representing the board, and `w` and `x` ordered pairs representing the start and end squares. The output is the subset of `{b, k, n, r}` (representing bishop, king, knight, and rook, respectively) which have a minimal-moves path between the two squares. For example, the third test case is invoked by `f[{{0, 0}, {1, 1}, {1, 2}, {0, 3}}, {0, 0}, {0, 3}]` and returns `{k}`; the last two test cases return `{k, n}` and `{}`, respectively.

The strategy is to translate the squares of the board into vertices of a graph, where the edges are determined by each piece's moves, and then use built-in graph routines.

More user-friendly version of the code:

```
 1  f[g_, w_, x_] := ( c = {{1, 1}, {-1, 1}}; s = c.c/2;
 2    e = # <-> #2 & @@@ # &; j = Join; h = FindShortestPath; t = #~Tuples~2 &;
 3    a@d_ := e@Select[t@g, # - #2 & @@ # == d &];
 4    y@k = j @@ (a /@ j[s, c]);
 5    y@n = j @@ (a /@ {{1, 2}, {2, 1}, {-2, 1}, {-1, 2}});
 6    v = Flatten[e@t@# & /@
 7         ConnectedComponents@a@# & /@ #] &;
 8    y@r = v@s; y@b = v@c;
 9    Pick[p = {b, k, n, r},
10      z = Length[h[y@#, w, x] /. h@__ -> 0] & /@ p,
11      Min[z~Complement~{0}]]
12  );

```

In line 3, `Select[g~Tuples~2, # - #2 & @@ # == d` finds all ordered pairs of vertices whose difference is the vector `d`; `e` then transforms each such ordered pair into an undirected graph edge. So `a` is a function that creates edges between all vertices that differ by a fixed vector.

That's enough to define, in lines 4 and 5, the king's graph `y@k` (which takes the union of edges generated by the vectors `{1, 1}`, `{-1, 1}`, `{0, 1}`, and `{-1, 0}`) and the knight's graph `y@n` (which does the same with `{1, 2}`, `{2, 1}`, `{-2, 1}`, and `{-1, 2}`).

In line 7, `ConnectedComponents@a@#` takes one of these neighbor graphs and then finds its connected components; this corresponds to grouping all line segments of vertices in the given direction (so that a rook or bishop doesn't have to move through them one by one). Then `e@t@#` on line 6 puts edges between every pair of vertices in the same connected component, which are then `Flatten`ed into a single graph. Thus lines 6 through 8 define the rook's graph `y@r` and the bishop's graph `y@b`.

Finally, lines 9 through 11 choose the elements of `{b, k, n, r}` that yield the shortest path between the two target vertices. `FindShortestPath` will throw an error and return unevaluated if a target vertex doesn't appear in the graph (which will happen if no edges emanate from it), so we use `h@__ -> 0` to return `0` in those cases instead. And the lack of a path between valid vertices returns a list of length `0`, so `Min[z~Complement~{0}]` calculates the length of the smallest path that actually exists, ignoring the bad cases above.

---
Tags: code-golf, chess
---


title: Name the Brag Hand

text:
# Question
Title: Name the Brag Hand
**Background**

Brag is a card game similar in concept to, but simpler than, poker. A hand in brag consists of three cards and is ranked as follows from highest to lowest:

* Three of a kind - all three cards the same rank. Named as "three Kings" etc.
* Running flush aka straight flush. All three cards of same suit and of consecutive ranks. The hand is named by the three cards in ascending order followed by the words "on the bounce" to distinguish from a simple run/straight, eg "ten-jack-queen on the bounce". Note an ace is either high or low but not both - "king-ace-two" is not a run.
* Run aka straight. As above but without the requirement to match suits. Named simply as eg "ten-jack-queen".
* Flush - all three cards the same suit, named after the highest rank eg "Ace flush".
* Pair - two cards the same rank together with a third of another version rank. Named as "pair of threes" etc.
* Any other combination, named after the highest rank eg "ace high".

**Challenge**

Given three playing cards, output the name of the brag hand they output.

The cards will be input either as three 2-character strings or concatenated as a single 6-character string (whichever your implementation prefers), where the first of each pair is the rank (2...9, T, J, Q, K, A) and the second signifies the suit (H, C, D, S).

Standard golfing rules apply - write a program or function which accepts this input and outputs the name of the hand as detailed above.

You can assume the input will be valid (ranks and suits in the above range, no repeated card) and in whatever case you prefer, but will not be in any particular order.

Output must be either in all capitals, all lower case, or a sensible capitalisation eg title case or sentence case. Numeric ranks should be spelled out eg "tens" not 10s.

Sample inputs & outputs:

```
2H3C2D => "pair of twos"

TD8C9C => "eight-nine-ten"

4SKS9S => "king flush"

4D4H4S => "three fours"

5H3H2C => "five high"

2D3DAD => "ace-two-three on the bounce"

6D6C6H => "three sixes"

```

This is my first attempt at a challenge on this site, please do suggest improvements but be gentle :)

# Answer
> 2 votes
## Ruby, ~~384~~, 320

Accepts an array of two-char strings.

Translates the pip values into hex values and identifies hands based on how many distinct pip values there are.

```
->*d{u=d.map{|x|*u=x[1]}==u*3
g=d.map{|x|(x[0].tr'TJQKA','ABCDE').hex}.sort
g=1,2,3if[2,3,14]==g
_,l,h=a=g.map{|x|%w{king queen jack ten nine eight seven six five four three two ace}[-x%13]}
[*g[0]..2+g[0]]==g ?a*?-+(u ?' on the bounce':''):u ?h+' flush':[h+' high','pair of '+l+=l[?x]?'es':?s,'three '+l][-g.uniq.size]}

```

Annotated:

```
->*d{
    # u is "Is this a flush?"" (see if you have more than one suit)
    u=d.map{|x|u=x[1]}==[u]*3

    # g is the sorted card values in integer (convert to base 16)
    g=d.map{|x|x[0].tr('TJQKA','ABCDE').hex}.sort

    # use Ace == 1 if we have a low straight
    g=[1,2,3]if[2,3,14]==g

    # a is the names of all the cards
    a=g.map{|x|%w{ace two three four five six seven eight nine ten jack queen king ace}[x-1]}

    # l is for "plural" - just choose the middle card because we
    #                     only care about plurals for 2s or 3s
    l=a[1].sub(?x,'xe')+?s

    # if [g[0],g[0]+1,g[0]+2] == g, we have a run
    # possibly "on the bounce"
    ([*g[0]..g[0]+2]==g) ? (a * ?-) + (u ? ' on the bounce' : '') :

    # if we have a flush, we can't have three-of-a-kind, so try that first
    u ? a[2]+' flush' :

    # otherwise, dedupe your hand. if there's:
    # 3 values, x high; 2 values, pair; 1 value, three
    [a[2]+' high','pair of '+l,'three '+l][-g.uniq.size]
}

```

# Answer
> 3 votes
# Python 2, 788, 715, 559, 556, 554, 546, 568, 522 bytes

\*now passes the 'sixes' * thanks to Ben Frankel for saving 46 Bytes!

---

```
import re
d,m,n=dict(zip('JQKA',range(10,15))),'pair of %ss','%s-%s-%s'
C=lambda s:int(d.get(s[0],s[0]))
z,x,c=sorted(re.findall('..',raw_input()),key=C)
q,w,e=C(z),C(x),C(c)
A=[0,0,'two','three','four','five','six','seven','eight','nine','ten','jack','queen','king','ace']
I,O,U=A[e],A[w],A[q]
a,k='%s high'%I,e-w+q
if k==13:a=n%(I,U,O)
if k==w:a=n%(U,O,I)
if q==w or e==w or e==q:a=m%O
if k==e==w:a='three %ss'%I
if'x'in a:a=a[:-1]+'es'
if z[-1]==x[-1]==c[-1]:
 if'-'in a:a+=' on the bounce'
 else:a='%s flush'%I
print a

```

Try it online!

Thanks for a cool first challenge!

# Answer
> 2 votes
# PHP, ~~413~~ ~~405~~ ~~398~~ ~~409~~ ~~408~~ ~~406~~ 398 bytes

Unfortunately, PHP does not support nested array referencing inside strings;
that would have saved another ~~6~~ 5 bytes.

```
for(;$a=$argn[$i++];)$i&1?$v[strpos(_3456789TJQKA,$a)]++:$c[$a]++;$k=array_keys($v);sort($k);$n=[two,three,four,five,six,seven,eight,nine,ten,jack,queen,king,ace];echo($m=max($v))<2?($k[!$d=count($c)]+2-($h=$k[2])?$k[1]>1|$h<12?"$n[$h] ".[flush,high][$d++/2]:"ace-two-three":$n[$k[0]]."-".$n[$k[1]]."-$n[$h]").[" on the bounce"][$d^1]:($m<3?"pair of ":"three ").$n[$v=array_flip($v)[$m]].e[$v^4].s;

```

Run with `echo <hand> | php -nR '<code>` or test it online.

**breakdown**

```
for(;$a=$argn[$i++];)$i&1?      # loop through input
    $v[strpos(_3456789TJQKA,$a)]++  # count values on even positions [0,2,4]
    :$c[$a]++;                      # count colors on odd positions [1,3,5]
$k=array_keys($v);sort($k);     # $k=ascending values
$n=[two,three,four,five,six,seven,eight,nine,ten,jack,queen,king,ace];
echo($m=max($v))<2              # three different values:
?($k[!$d=count($c)]+2-($h=$k[2])    # test normal straight ($d=color count, $h=high card)
    ?$k[1]>1|$h<12                      # test special straight
        ?"$n[$h] ".[flush,high][$d++/2]     # flush if one color, high card if not
                                            #   ($d++ to avoid " on the bounce")
        :"ace-two-three"                    # special straight
    :$n[$k[0]]."-".$n[$k[1]]."-$n[$h]"  # normal straight
).[" on the bounce"][$d^1]          # if straight: straight flush if one color
:($m<3?"pair of ":"three ")     # pair or triplet
    .$n[$v=array_flip($v)[$m]]      # card name
    .e[$v^4].s                      # plural suffix
;

```

Requires PHP\>=5.6 (for `e[...]`)

# Answer
> 1 votes
## Python 2 - 583 bytes

I'm too new to be able to comment posts, so I just post my version of python solusion.

Fixed issue with 'es' for pair and three of sixes. Thanks to Not that Charles

```
d={'A':['ace',14],'2':['two',2],'3':['three',3],'4':['four',4],'5':['five',5],'6':['six',6],'7':['seven',7],'8':['eight',8],'9':['nine',9],'T':['ten',10],'J':['jack',11],'Q':['queen',12],'K':['king',13]}
r=input()
j=1
i=lambda x:d[x][j]
v=sorted(r[::2],key=i)
z,y,x=v
s=r[1::2]
e='es'if i(y)==6else's'
j=0
a=i(x)
if z==y or y==x:r="pair of %s"%i(y)+e
if s[0]*3==s:r="%s flush"%a
t="%s-%s"%(i(z),i(y))
j=1
u=" on the bounce"if r[-1]=='h'else ""
if i(z)+i(x)==2*i(y):r=t+"-%s"%a+u
if ''.join(v)=="23A":r="%s-"%a+t+u
if [z]*3==v:r="three %s"%d[z][0]+e
if len(r)==6:r="%s high"%a
print r

```

A bit more readable with some comments

```
# first of all we don't need to keep suits
d={'A':['ace',14],'2':['two',2],'3':['three',3],'4':['four',4],'5':['five',5],'6':['six',6],'7':['seven',7],'8':['eight',8],'9':['nine',9],'T':['ten',10],'J':['jack',11],'Q':['queen',12],'K':['king',13]}
r=input()                           # input placed in r, to safely check r[-1] later in code
j=1                                 # j toggles reading from dictionary: 0-string, 1-value
i=lambda x:d[x][j]                  # lambda used to access dictionary
v=sorted(r[::2],key=i)              # take values from input and sort
z,y,x=v                             # variables to compact code
s=r[1::2]                           # take suits from input
e='es'if i(y)==6else's'             # choose ending 'es' for six and 's' for others (for pair and three)
j=0                                 # toggle reading from dictionary to string
a=i(x)                              # get string of top most value
if z==y or y==x:                    # check only two pairs as values are sorted
    r="pair of %s"%i(y)+e
if s[0]*3==s:                       # compact check if all string characters are equal to detect flush
    r="%s flush"%a
t="%s-%s"%(i(z),i(y))               # part of straight output - first two values
j=1                                 # toggle reading from dictionary to values
u=" on the bounce"\                 # addon to output in case of possible straight flush
if r[-1]=='h'else ""                # detected by checking last character in r
                                    # which would be 'h' if flush was detected
if i(z)+i(x)==2*i(y):               # check straight - three sorted numbers a,b,c would be in line if a+c == 2*b
    r=t+"-%s"%a+u
if ''.join(v)=="23A":               # check special case with straight, started from Ace
    r="%s-"%a+t+u
j=0                                 # toggle reading from dictionary to string
if [z]*3==v:                        # check three equal values (almost the same as flush check)
    r="three %s"%d[z][0]+e
if len(r)==6:                       # if r was never modified, then it's just one high card
    r="%s high"%a
print r                             # output r

```

---
Tags: code-golf, game, card-games
---


title: Electron Configuration Diagrams

text:
# Question
Title: Electron Configuration Diagrams
## Challenge

Given an element name, output its electron configuration.

## Input

Your input will be the full name of each element (the range being from Hydrogen, 1, to Calcium, 20) with some exceptions - you should be able to account for the following inputs:

```
Natrium - This is sodium
Kalium - This is potassium

```

Note that inputs "sodium" and "potassium" must still be valid.

The first letter will always be capitalised.

## Output

You can refer to this webpage for guidance on how to generate an electron configuration diagram.

The following list shows the maximum number of electrons in each shell:

* **1st shell** \- 2 electrons
* **2nd shell** \- 8 electrons
* **3rd shell** \- 8 electrons
* **4th shell** \- 14 electrons (although the maximum number of electrons in this shell required is 2)

An example output of the electron configuration is the following:

In the centre of the diagram must be the element's one to two letter symbol.

Either dots or crosses may be used and where they are placed does not matter.

The output does not have to be exactly like this but it does have to be an ASCII graphic. The one thing it cannot be is in the form `2.8.8.1` or any other form like this.

The circles are not necessary

Built in functions which access the periodic table of elements or produce diagrams or electron configurations are hereby disallowed.

## Winning

The shortest program in bytes wins.

# Answer
# MATLAB, 360 363 290 304 295 bytes

*See at the bottom of the post for how to test the old code with Octave.*

This code takes the name of the element (including Kalium, etc.) and displyas the output in ascii format now that the rules have changed.

```
f=input('');e=1;a=['CPACxxSAMSNxxxxxBLHxCKACSPSAMNNFONCBBLHH';'aorhxxilaoexxxxxeiexa rl  ilgae     eie '];for s=a;n=s(s~=32);if strncmpi(n,f,nnz(n));break;end;e=mod(e,20)+1;end;s=spiral(10);p=[8,18,33,28,23,39,60,53,46,95];p=[p;p+1];o=s*0;o(ismember(s,p(1:21-e)))='x';o(45:46)=a(:,e+20);char(o')

```

The rules changed since I wrote the code to require an ASCII output. I have updated my code to do this at the expense of 14 bytes. I have saved 9 bytes by getting rid of the reshape() and just making the `a` matrix the right shape to begin with.

Here is an explanation of how it works:

```
%Get the name - actually we only need at most the first two characters, but the whole thing will do
f=input('');
e=1;
%This bit makes a map which allows us to find the element (including with
%the names like Kalium. All of the elements appear twice, with the actual
%symbols being the second set. The first set gets all those whose names are
%either more than one character, or don't begin with the first two
%characters of the short for (e.g. Sodium). The string is reshaped into a
%2x40 array. 'Natrium' is a pain in the neck as it as it would get caught
%by 'N' for 'Nitrogen'. I have reversed the element order - so that all the
%ones beginning with N come before N. Some maths is done later on to
%correct for the number of electrons - basically 21-e so 1 becomes 20.
a=['CPACxxSAMSNxxxxxBLHxCKACSPSAMNNFONCBBLHH';'aorhxxilaoexxxxxeiexa rl  ilgae     eie '];

%For each group of 2 in the array of elements
for s=a

    %Remove any spaces from the name
    n=s(s~=32);

    %Do a comparison of the first one or two characters of the requested string
    if (strncmpi(n,f,nnz(n)))

        %break once the element is found
        break;
    end

    %If not this element add another electron. We wrap around after 20 as there are two copies of each
    e=mod(e,20)+1;
end
%e is now number of electrons

%Generate an array of points for each electron
s=spiral(10);
p=[8,18,33,28,23,39,60,53,46,95];p=[p;p+1];

%make an output array
o=s*0;

%Plot all the points in is up to and including the number of electrons (see the notes above for why 21-e)
o(ismember(s,p(1:21-e)))='x';

%And add the text in the centre - we extract the element name from the second group appearance in the 'a' array, hence adding 20.
o(45:46)=a(:,e+20);

%Display the result
char(o')

```

This is the output for Hydrogen (ignore the dots, they are to avoid the lines being removed when showing here):

```
          .
          .
          .
          .
   xH     .
          .
          .
          .
          .
          .

```

And here is the output for Calcium.

```
          .
    xx    .
    xx    .
          .
 xxxCa xxx.
 xxx   xxx.
          .
    xx    .
    xx    .
          .

```

And the output for Natrium, which now works properly (before Natrium it would result in Nitrogen!).

```
          .
     x    .
    xx    .
          .
  xxNa x  .
  xx   x  .
          .
    xx    .
          .
          .

```

---

The new version of the code doesn't work with Octave as it uses `spiral()` which is only present in MATLAB.

You can however test the old code using the Octave online interpreter:

```
f=input('');e=1;a=['CPACxxSAMSNxxxxxBLHxCKACSPSAMNNFONCBBLHH';'aorhxxilaoexxxxxeiexa rl  ilgae     eie '];for s=a;n=s(s~=32);if strncmpi(n,f,nnz(n));break;end;e=mod(e,20)+1;end;u=14:(34-e);r=floor(u/8);t=u*pi/4;polar(t,r,'o');text(0,0,a(:,e+20)','horizontalalignment','c')

```

Run that, then enter a string like: 'Hydrogen' (including the quote marks). Once it is done, you will have to click the expand plot button (looks like a little graph symbol in the top right corner of the interpreter) to get it to show the full thing. In Octave it unfortunately add lines joining the points, this does not happen in MATLAB. But at least it allows you to test the logic behind it. As I say, this is still a graphical output, but you get the idea of how the elements are looked up.
> 2 votes

# Answer
## Python 3, 529 bytes

*thanks Thomas and Beta for pointing out some things that should've been obvious to me, saving me some bytes*

*massive improvement: using string slicing instead of dict lookup*

```
s="""    {18}
    {10}{14}
    {2}{6}
    {0}{1}
 {17}{9} %s {3}{11}
 {13}{5}    {7}{15}

    {8}{4}
    {16}{12}
    {19}"""
e="H HeLiBe B C N O F NeNaMgAlSiP S ClArK Ca"
r="hydrogen   helium     lithium    beryllium  boron      carbon     nitrogen   oxygen     fluorine   neon       natrium    sodium     magnesium  aluminium  silicon    phosphoroussulfur     chlorine   argon      kalium     potassium  calcium    "
n=r.find(input().lower())//11
n-=(n>10)+(n>18)
print(s.format(*[' *'[i<=n]for i in range(20)])%e[n*2+1:n*2+3])

```

Not the prettiest of programs or outputs, but hey, we needed something to kick this challenge off. Try it online.
> 2 votes

# Answer
```
j=0
do
{
if(elnum=1)
{
draw_circle(100,100,50)
draw_sprite_ext(spr_electron,sprite num,100,100+50,direction,c_white,c_alpha)

}
else
{
if(elnum=2)
{
draw_circle(100,100,50)
draw_sprite_ext(spr_electron,sprite num,100,100+50,direction,c_white,c_alpha)
draw_sprite_ext(spr_electron,sprite num,100,100+50,direction,c_white,c_alpha)
}
if(j>1&&j<=8)
{
if(j>5)
angdeviation=5
else
angdeviation=-5
draw_circle(100,100,100)
draw_sprite_ext(spr_electron,sprite num,100+length_dirx(j*100+angdeviation),100+length_diry(j*100+angdeviation),direction,c_white,c_alpha)
}
}

}until(j<=enum)

```
> 0 votes

---
Tags: code-golf, ascii-art, chemistry
---


title: True and false and true

text:
# Question
Title: True and false and true
Challenge is to write a function/program which outputs a truthy or falsey value alternately each time you call it. No input.

It can start with either true or false.

# Answer
> 8 votes
# Jelly, 3 bytes

```
®¬©

```

Try it online!

### How it works

```
®¬©  Main link. No arguments.

®    Retrieve the value stored in the register.
 ¬   Negate it.
  ©  Copy the result to the register.

```

# Answer
> 4 votes
# JavaScript ES6, 11 bytes

```
f=i=_=>i=!i

```

```
f=i=_=>i=!i

console.log(f());
console.log(f());
console.log(f());
```

# Answer
> 4 votes
# Python 2, 30 bytes

```
def f():f.n^=1;print f.n
f.n=0

```

Try it online!

# Answer
> 4 votes
# Python 2, ~~34~~ ~~33~~ 32 bytes

<sup>-1 byte thanks to Cyoce</sup>

```
def f(x=[]):x+=0,;print len(x)%2

```

Try it online!

This works because the list used as (optional) argument is kept between function calls.
It's not a bug, it's a feature

# Answer
> 3 votes
# Java 7, ~~36~~ 35 bytes

```
int f=0;boolean c(){return++f%2<1;}
// OR
boolean f;boolean c(){return f=!f;}     // Thanks to @Poke

```

Old answer: `int f=0;boolean c(){return(f^=1)<1;}`

Extremely short for a Java 7 answer. :D (Although still the longest of all submissions of course)

**Explanation:**

```
int f=0;              // Integer flag on class level
boolean c(){          // Method with no parameters and a boolean return-type
  return ++f % 2 < 1  //  return whether `f` modulo 2 is 0 (but increase `f` first)
}                     // End of method

```

**Test code:**

Try it here.

```
class M{
  int f=0;boolean c(){return++f%2<1;}

  public static void main(String[] a){
    M m = new M();
    System.out.println(m.c());
    System.out.println(m.c());
    System.out.println(m.c());
    System.out.println(m.c());
    System.out.println(m.c());
  }
}

```

**Output:**

```
false
true
false
true
false

```

# Answer
> 2 votes
## CJam, 6 bytes

```
{T!:T}

```

Try it online!

Pushes `T` (initially `0`, falsy), negates it (toggling between `1`, truthy, and `0`), stores the result in `T` for the next invocation and leaves it on the stack.

# Answer
> 2 votes
# Octave, 4 bytes

```
i=~i

```

`i` is initially `sqrt(-1)`. Everything that's not `0` is considered `true` in Octave (note, this doesn't work in MATLAB).

`i=~i` assigns `not(true)` to `i`, making it `false`, The next iteration it will be `false` again.

This is a full program, that can be called using the file name. Example from octave-online with a file name called `inverter.m`:

```
octave:1> source("inverter.m")
i = 0
octave:1> source("inverter.m")
i =  1
octave:1> source("inverter.m")
i = 0
octave:1> source("inverter.m")
i =  1

```

# Answer
> 2 votes
# Python 3, 31 bytes

```
def f(x=[]):x+=print(len(x)&1),

```

Try it online!

# Answer
> 1 votes
# C, ~~39~~ ~~30~~ ~~26~~ ~~19~~ 18 Bytes

Using a Macro now

```
i;
#define f i++%2

```

Thanks for the help i=!i

~~i;f(){return i=!i;}~~

~~i;f(){return i++?i=0,1:0;}~~

~~i;f(){putchar(i++?i=0,70:84);}~~

~~f(){static i=0;putchar(i++?i=0,70:84);}~~

```
main()
{
    putchar(48+f);puts("");
    putchar(48+f);puts("");
    putchar(48+f);puts("");
    putchar(48+f);puts("");
}

```

Output

```
0
1
0
1

```

# Answer
> 1 votes
## Mathematica, 12 bytes

Either of these works:

```
(x=x=!=1>0)&
(x=x===0>1)&

```

I would love to express the `True` or `False` at the end using only `x` and `=` or maybe `!` as well, but unfortunately, that gets longer.

In the notebook environment we can also use this 8-byte solution:

```
%=!=1>0&

```

But it only works if the call to the function is the only thing on its line and there are no other function calls in between, so I won't count this one.

# Answer
> 1 votes
# Ruby, ~~15 14~~ 12 bytes

```
->{0>$.^=-1}

```

# Answer
> 1 votes
# PHP, ~~31~~ 25 bytes

*Thanks to user63956 for golfing 6 bytes*

```
function(){echo$_GET^=1;}

```

Try it online!

This is an anonymous function.

# Answer
> 1 votes
# Bash, 11 bytes

```
f()((n^=1))

```

Output is via the function's status code.

Try it online!

# Answer
> 0 votes
# Bash, 25 bytes

```
sed -i y/TF/FT/ $0
echo T

```

Try it online!

This is a full program. You must have write access to the file in addition to execute.

# Answer
> 0 votes
# Java, 32 bytes

Not competing because ints aren't truth and false values in Java and an answer like that already exists.

```
int a;int f(){return a=a>0?0:1;}

```

Ungolfed(barely anything to ungolf):

```
int a;
int f() {
    return a = a > 0 ? 0 : 1;
}

```

# Answer
> 0 votes
# Applescript, 25

```
property i:0
set i to 1-i

```

Applescript properties are persistent. The result of the last assignment is implicitly given as the program result.

# Answer
> 0 votes
## Haskell, 52 bytes

```
import Control.Monad.State
execState(modify not)True

```

This uses the State monad to store a boolean value which is initially set to `True`. Additional calls must also run within the State monad, e.g.

```
 execState(modify not>>modify not>>modify not)True

```

which evaluates to `False`.

# Answer
> 0 votes
# Scala, 25 bytes

```
var b=8<9
def f={b= !b;b}

```

### Explanation:

```
var b = 8 < 9 // define a variable b as false
def f = {     // define a function f wothout parameters
  b = !b      // invert the state of b
  b           // return b
}

```

There needs to be a space in `b= !b`, so scala doesn't want to invoke the method `=!` on b, which doesn't exists.

---
Tags: code-golf
---


title: Transpile WordMath

text:
# Question
Title: Transpile WordMath
We've all seen those online "maths hax" that look like this:

```
Think of a number, divide by 2, multiply by 0, add 8.

```

And, by magic, everyone ends up with the number 8!

---

## Language

Let's define a programming language which uses the syntax of the text above, called "WordMath". WordMath scripts follow this template:

```
Think of a number, <commandlist>.

```

Which basically means: Take a number (as input from STDIN) as the initial accumulator, perform all commands on it, and output the result.

The commands are seperated by the delimiter `,` (comma + space). The valid commands are *(note that `#` represents a non-negative integer:)*:

* `add #` / `subtract #` \- Add/subtract the value from the accumulator.
* `divide by #` / `multiply by #` \- **floordiv** / multiply the accumulator by the given value.
* `subtract from #` \- Similar to `subtract`, but does `acc = # - acc` instead of `acc = acc - #`
* `repeat` \- do last command again. This cannot be the 1st command, but **you must support multiple consecutive repeats.**

---

## The Challenge

Your task is to create a program or function which takes a valid WordMath script as input and transpiles it into a valid full program - in the same language your code is in.

For example, if my code is in Python 2 and the script is:

```
Think of a number, subtract from 10, add 10, multiply by 2.

```

The outputted program can be:

```
a = input()
a = 10 - a
a += 10
a *= 2
print(a)

```

Or alternatively:

```
print(((10-input())+10)*2)

```

As long as it is a **full program** which takes input from `STDIN` and prints to `STDOUT`, or the language's nearest equivalents.

---

## Rules

* Your original program may assume that the input is always a valid WordMath script.
* The transpiled programs do not have to handle mathematical errors such as division by 0.
* The transpiled programs may assume that the input represents a valid signed integer, within your language's standard integer range.
* This is , so the shortest solution (in bytes) wins.
* Only the byte count of your original program matters - the outputted code can be as long as you want!

---

## Example Scripts

**Example 1:**

```
Think of a number.

```

Take input, do nothing, display it: WordMath's cat program.

**Example 2:**

```
Think of a number, divide by 5, subtract from 9.

```

Remember that "divide" is floor division, so for this program `6 -> 8`, and `29 -> 4`.

**Example 3:**

```
Think of a number, add 5, add 10, multiply by 2, subtract 15, repeat, divide by 2.

```

The extended cat program!

**Example 4:**

```
Think of a number, subtract 1, repeat, repeat.

```

Takes a number and subtracts 3.

# Answer
> 6 votes
# 05AB1E, ~~59~~ ~~56~~ ~~54~~ 52 bytes

```
„, ¡¦vyDþs.AJá'bK"dmas""/*+-"‡„-f„s-.:«D'rQi®}©}J'rK

```

Try it online!

My brain hurts like hell after that... It outputs in 05AB1E code as follows:

* `Think of a Number` is removed, due to implicit input.
* `Subtract From #` coverts to `#s-` (swap `a` and `b` and perform operation).
* `Subtract #` converts to `#-`.
* `Add #` converts to `#+`.
* `Multiply by #` converts to `#*`.
* `Divide by #` converts to `#/`.
* `Repeat` grabs whatever was last stored in the register and concatenates it.

**Explained:**

```
„, ¡                                                 # Split on ', '.
    ¦                                                # Remove the 'Think of a number'.
     vy                                        }     # Loop through chunks.
       Dþs                                           # Dupe, push only digits, swap.
          .AJá                                       # Acronymify without digits.
              'bK                                    # Remove the `b`.
                 "dmas""/*+-"‡                       # Replace letters with OPs.
                              „-f„s-.:               # Replace '-f' with 's-'.
                                      «              # Concat # with OP.
                                       D'rQ          # Dupe, push 1 if OP='r'.
                                           i®}       # If 'r', push last #OP.
                                              ©      # Store current OP.
                                                J'rK # Join, remove remaining r's.

```

**Example:**

Input:

```
Think of a number, divide by 2, multiply by 10, add 8, subtract 6, subtract from 9, repeat, repeat, subtract 41.

```

Output:

```
2/10*8+6-9s-9s-9s-41-

```

Try solution with input of 10:

Try it online!

See it on google:

Here's a link to the same equation typed into google.

# Answer
> 13 votes
# C Preprocessor, 362 Bytes

I ALMOST got this working in JUST the C preprocessor, but the repeat command turns out to be far too difficult to implement. So instead I used the preprocessor to turn the input into an array that is then interpreted by some additional code.

```
main(){int c[]={
#define Think
#define of
#define a
#define number 0
#define add 1,
#define subtract 2,
#define from 0,3,
#define multiply 4,
#define divide 5,
#define by
#define repeat 6, 0
#include "input.wm"
,'$'};int _,l,v;scanf("%d", &_);for(int i=1;c[i]-'$';++i){c[i]!=6?l=c[i],v=c[++i]:++i;l==1?_+=v:l==2?_-=v:l==3?_=v-_:l==4?_*=v:_/=v;}printf("%d",_);}

```

The input must be provided in "input.wm" or just dumped in the source at that line. I included its bytes in my count because I figure its a bit hacky and slightly against the rules of the challenge, so it is only fitting.

Anyways, once you dump your WordMath source into input.wm where a compiler can find it, you should be able to just compile this, as is, with warnings to produce an executable that does what the WordMath source says.

# Answer
> 7 votes
# Retina, 170 bytes

**Because who wouldn't want to see this?!**

I thought of how awesome it'd be to see a Retina solution, and I decided to create it quick. It only took an hour. As usual, byte count assumes ISO 8859-1 encoding.

```
S`,
\.

T.*
.*¶$$*
\;+`(.*)¶rep.*(¶?)
$1¶$1$2
\d+
$*
.*f.* (1*)
1¶x¶$¶$1¶+`x1¶
m.*
1¶
di.* (1*)
^¶$1 ¶^(1+) (\1)+1*$¶x$$#+¶1+ 1*¶x0¶x\d+¶$$*
s.* (1*)
^$1¶
a.*
^¶
\z
¶1

```

**Try it online**

Output has a trailing newline that should not be copied when testing the resulting program. The program does not support negatives, because Retina's *standard integer range* (in unary) does not.

**Explanation:**

```
S`,                 # Split input on ", " putting each command on its own line
\.                  # Remove the period

T.*                 # Think of a number -> .*\n$* (replaces input with unary)
.*¶$$*
\;+`(.*)¶rep.*(¶?)  # Loop, replacing "repeat" with the line before it
$1¶$1$2
\d+                 # Replace all numbers with their unary representation
$*
.*f.* (1*)          # Replace "subtract from " with a subtract from program
1¶x¶$¶$1¶+`x1¶
m.*                 # Replace "multiply by " with a multiply program
1¶
di.* (1*)           # Replace "divide by " by my integer division program
^¶$1 ¶^(1+) (\1)+1*$¶x$$#+¶1+ 1*¶x0¶x\d+¶$$*
s.* (1*)            # Replace "subtract " with a subtraction program
^$1¶
a.*                 # Replace "add " with an addition program
^¶
\z                  # At the end, add a stage to change unary into decimal
¶1

```

---

### Math programs:

**Add:**

Add the number of ones to the beginning. Add 5:

```
^
1111

```

**Subtract:**

Remove the number of ones from the beginning. Subtract 5:

```
^11111

```

**Subtract from:**

Replace input `1`s with `x`s. Put next to the fixed number. Repeatedly remove `x1`. Subtract from 10:

```
1
x
$
1111111111
+`x1

```

**Multiply by:**

Replace every `1` with a certain number of them. Multiply by 3:

```
1
111

```

**Divide by:**

This uses my Retina program for Integer Division. Divide by 2:

```
^                   # Place the fixed divisor before the dividend
11
^(.+) (\1)+.*$      # Match the divisor, followed by each occurrence in the dividend.
x$#+                # Replace with the number of matches. Trailing ones are dropped
.+ .*               # If there are still two numbers, the result is zero
x0
x\d+                # Replace result (marked with an 'x') with unary
$*

```

# Answer
> 4 votes
# Python 2, ~~263~~ ~~258~~ ~~260~~ 221 bytes

This could probably *still* be much shorter.

```
def r(s,o="",p=""):c=s.pop(0);c=[c,p]['re'in c];n=c.split()[-1];o=[[o+[['+-'['s'in c],'//']['v'in c],'*']['m'in c]+n,n+'-'+o]['f'in c],'input()']['T'in c];return s and r(s,"(%s)"%o,c)or o
lambda s:"print "+r(s.split(','))

```

**Try it online**

I use `//` instead of `/`, because the last instruction will have a `.` at the end, making any number a float. So in order to keep division consistent, I use integer division.

**Test cases output:**

```
print input()
print 9.-((input())//5)
print ((((((input())+5)+10)+10)-15)-15)//2.
print (((input())-1)-1)-1

```

# Answer
> 4 votes
# GNU awk, 139 bytes

```
BEGIN{RS="[,.]";c="{}{";ORS=";"}
/ad/{c="+="$2}
/c/{c="-="$2}
/om/{c="="$3"-$0"}
/l/{c="*="$3}
/v/{c="=int($0/"$3")"}
!NF{c="}1"}
$0="$0"c

```

Invocation:

```
$> awk `awk -f wordmath <<< "Think of a number, add 1, repeat, repeat."` <<< 0
$> 3

```

Test cases:

```
$> awk -f wordmath <<< "Think of a number."
$> $0{}{;$0}1;

$> awk -f wordmath <<< "Think of a number, divide by 5, subtract from 9."
$> $0{}{;$0=int($0/5);$0=9-$0;$0}1;

$> awk -f wordmath <<< "Think of a number, add 5, add 10, multiply by 2, subtract 15, repeat, divide by 2."
$> $0{}{;$0+=5;$0+=10;$0*=2;$0-=15;$0-=15;$0=int($0/2);$0}1;

```

# Answer
> 4 votes
## Haskell, ~~232~~ 231 bytes

Of course a functional programmer would prefer to return a function rather than a string representing a program, but here we go:

```
t l="main=getLine>>=print."++""%words l++"(0+).read"
x%((o:_):f:n:r)|o=='m'=h"*"n r|o=='d'=h"`div`"n r|f=="from"=h"(-)"n r
x%(s:n:r)|s=="add"=h"+"n r|s!!0=='s'=h s(' ':n)r
x%(_:r)=x%r++x
_%_=""
h s n r|x<-'(':s++init n++")."=x%r++x

```

Remarks: We always start with adding zero, otherwise the transpilation of the trivial WordMath program wouldn't give enough information to infer the type at which `read` is used. `subtract from n` could be implemented as `(n-)`, but I use `((-)n)` for more uniformity. In the case of `subtract n` I copy the `subtract` from the input so I don't have to write it, but I need to compensate for the missing space at the end. `repeat` is used as default operation; together with an empty initial previous operation this allows for easy ignoring of the first four words.

Usage example:

```
*Main> t "Think of a number. "
"main=getLine>>=print.(0+).read"

```

The other examples give the following results:

```
"main=getLine>>=print.((-)9).(`div`5).(0+).read"
"main=getLine>>=print.(`div`2).(subtract 15).(subtract 15).(*2).(+10).(+5).(0+).read"
"main=getLine>>=print.(subtract 1).(subtract 1).(subtract 1).(0+).read"

```

# Answer
> 4 votes
# Befunge, ~~342~~ 305 bytes

```
>~$1 +:89+`#v_801p
  v_^#`+85~$<
1+>~:5+88+/3-!#v_$
v`"/":~p8p10+1<>>:"/"`!|
 "+"\5+8p4+:1+^:p11:g10<  >:"+"\2+8p:"*"\3+8p:
_$7%:01g\!#v_\2-7g\:1+:01v^p8+1\"5":p8\"5":g10
#8\"\"$#:0#<^v<p8p8\<g80p<>\#+$#12#p
-/+* >:#,_@  #^p8g10<
".@"<^"&"
10<v0<\g8-\g11:<:p1>#1+g11:p10+g
-:^>1g\-8p1-::#^_$8g^  >$$01g11g

```

Try it online!

**Output**

The code it generates starts with a `&` (input value) command, and finishes with `.` (output value) and `@` (exit) commands. In between we have the various calculations in the form `<number><operation>`, where the *operation* can be `+` (add), `-` (subtract), `/` (divide by), `*` (multiply by), and `\-` (subtract from).

The *number* itself is a bit complicated, because Befunge only supports numeric literals in the range 0 to 9, so anything larger than that needs to be manually calculated. Since we are already reading the numbers in character by character, we simply build up the number as each digit is read, so for example, 123 becomes `155+*2+55+*3+`, i.e. `(((1 * 10) + 2) * 10) + 3`.

**Examples**

```
Input:  Think of a number.
Output: &.@

Input:  Think of a number, divide by 5, subtract from 9.
Output: &5/9\-.@

Input:  Think of a number, add 5, add 10, multiply by 2, subtract 15, repeat, divide by 2.
Output: &5+155+*0++2*155+*5+-155+*5+-2/.@

Input:  Think of a number, subtract 1, repeat, repeat.
Output: &1-1-1-.@

```

**Explanation**

Befunge doesn't have the ability to manipulate strings as such, so most of the parsing is handled by counting characters. We start just by skipping the first 18 characters, which gets us past the *Think of a number* phrase (plus either a comma or period). Then if the next character is some form of newline or EOF we go straight to the output routine, otherwise we continue looking for a command list.

To parse a command, we just keep counting characters until we reach a digit or separator. If it's a separator, it must have been the repeat command which we handle as a special case. If it's a digit we add it to our output buffer, and continue looking for more digits. Each time a digit is output, we prefix it with `55+*` (to multiply the total so far by 10) and suffix it with `+` (to add it to the total). Once the digits are finished we add the command character.

As for how the command is determined, we take the count of characters up to the first digit modulo 7. For *add* this is 4 (including the following space), for *subtract* it's 2, for *divide by* it's 3, for *multiply by* it's 5, and for *subtract from* it's 0. The *subtract from* requires a little additional handling since it needs the `\-` command combo, but the others just use their value to lookup the appropriate command character in a table.

This process is repeated for each command, building up the output into a preconstructed string on line 8. Each time an additional command is added, we also add a closing quote to the string to make sure it's always properly terminated. Then when we eventually reach the end of our input, we simply "execute" this string to push it onto the stack, then follow that with a standard output sequence to write it all out.

# Answer
> 3 votes
# JavaScript (ES6), 163 bytes

```
w=>w.split`, `.map(l=>(o={a:'+',s:'-',m:'*',d:'/'}[a=l[0]])?p=(x=l.split` `.pop(),l[9]=='f'?x+`-n`:`n`+o+x+`|0`):a<'r'?'n=+prompt()':p).join`
n=`+`
console.log(n)`

```

Try it:

```
f=w=>w.split`, `.map(l=>(o={a:'+',s:'-',m:'*',d:'/'}[a=l[0]])?p=(x=l.split` `.pop(),l[9]=='f'?x+`-n`:`n`+o+x+`|0`):a<'r'?'n=+prompt()':p).join`
n=`+`
console.log(n)`

const program = f('Think of a number, add 5, add 10, multiply by 2, subtract 15, repeat, divide by 2.')
document.write('<pre>' + program + '</pre>' )

eval(program)

/*
Outputs:

n=+prompt()
n=n+5|0
n=n+10|0
n=n*2|0
n=n-15|0
n=n-15|0
n=n/2.|0
console.log(n)
*/
```

# Answer
> 3 votes
# Vim ~~208~~ ~~171~~ 168 bytes

Added the ability to do multiple repeats in a row as per @Flp.Tkc but golfed off enough bytes that I could still lower the byte count.

```
:map s :s;\v
c4wcw="s, s\w* \w+ (\d+); *-1+\1);g
s, ([adms]).{-}(\d+); \1\2);g
qws(\S+), r\w+;\1 \1
@wq@ws.*;\=tr(submatch(0),'adms','+/*-')
qq])T=i(@qq@qx$xA

```

TryItOnline

Unprintable characters:

```
:map s :s;\v
c4wcw^V^R=^V^R"^[s, s\w* \w+ (\d+); *-1+\1);g
s, ([adms]).{-}(\d+); \1\2);g
qws(\S+), r\w+;\1 \1
@wq@ws.*;\=tr(submatch(0),'adms','+/*-')
qq])T=i(^[@qq@qx$xA
^V^[^[

```

Test cases output:

1. `cw^R=^R"
^[` TryItOnline
2. `cw^R=((^R" /5) *-1+9)
^[` TryItOnline
3. `cw^R=((((((^R" +5) +10) *2) -15) -15) /2)
^[` TryItOnline

# Answer
> 2 votes
# Pyth, ~~69~~ 67 bytes

```
J\QVtcQ\,Iq@N1\r=NZ)=Jjd+@"+-/*"x"asdm"@N1.>,J-ecN)\.qh@cN)1\f=ZN)J

```

A program that takes input of a `"quoted string"` and prints the result.

Test suite

**How it works**

Pyth has prefix operators, so the basic arithmetical operations are performed using `(operator)(operand1)(operand2)`, while the pre-initialised variable `Q` gives the input. Hence, a transpiled WordMath program is constructed by starting with the string `'Q'`, and at each stage, prepending the operator, and then prepending or appending the operand as neccessary.

`J\Q` Set `J`, the transpiled program string, to the string `'Q'`

`tcQ\,` Split the input on commas, and discard the first element (which is '`Think of a number'`)

`V` For `N` in that:

* `Iq@N1\r` If the character at `N[1]` is `'r'` (repeat):
    + `=NZ` Set `N`to `Z` (previous value of `N`, set at end of for loop)
* `x"asdm"@N1` Find the index of `N[1]` in `"asdm"` (add, subtract, divide, multiply)
* `@"+-/*"` Index with that into `"+-/*"`, giving the required operator
* `,J-eCN)\.` Yield the two-element list `[J, -eCN)\.]`, where the second element is the last element of `N` split on whitespace with any `'.'` characters removed (operand)
* `qh@cN)1\f` If the first character of the second element of `N` split on whitespace is `'f'` (subtract from):
    + `.>` Swap the elements of the two-element list
* `+` Merge the operator and two-element list into one list
* `=Jjd` Set `J` to that joined on spaces
* `=ZN` Set `Z` to `N`

`J` Print `J`

# Answer
> 2 votes
# lex, 246 bytes

```
%{
#define P printf
#define O P("n%s%d;",c,v);
int v;char*c;
%}
%%
T {P("%%%%\n.* {int n=atoi(yytext);");}
ad {c="+=";}
fr {c="=-n+";}
s {c="-=";}
v {c="/=";}
l {c="*=";}
re {O}
[0-9]+ {v=atoi(yytext);O}
\. P("printf(\"%%d\",n);}\n%%%%");
. ;
%%

```

lex targets to C, so a C compiler would need to compile it into something executable. The lexer library (`ll`) would also need to be linked. This may add a byte-penalty, but I'm not sure how many bytes if so.

The program outputs a lex program (per specification) that evaluates the transpiled wordmath expression. The code between `%{` and `%}` is for the "transpiler" only:

```
#define P printf              /* for brevity */
#define O P("n%s%d;",c,v)     /* expression builder, calls P = printf */
int v;char*c;                 /* v=most recent integer read */
                              /* c=the expression infix */

```

Between the two `%%` lines is the regex/action portion. The first rule to be matched would be `T` ("Think...") which builds the preamble (lex programs must start contain the rule section at the least, and `yytext` is last matching text, so the rule essentially seeds the accumulator with the user's input).

The program discards all input except for that which is matched, and the other rules (`ad`, `fr`, up to `re`) handle the wordmath expression clauses with as minimal a match as possible to be unique. In most of these, it sets `c` to an expression infix, which gets concatenated between `n` and the last integer read when `O` gets called (so for example, reading "add 9" will set the infix to `+=`, v to `9`, and the call to `O` will output `n+=9;`). (An interesting aside is that "subtract from 8" will cause both the `s` and the `fr` rules to get matched, but since `O` is called only at the number, the proper rule `n=-n+8;` is the only expression that gets output). The `re` rule for "repeat" just calls `O` again, which outputs the last created expression (and since subsequent matches will clobber `yytext`, supporting "repeat" is why the integer conversion in the `[0-9]+` rule was required). Finally, a period causes the program trailer to be output, which just outputs the accumulator and closes with the `%%` pair denoting the end of the output lex program.

**Note:** Neither the main transpiler program or the output program will terminate. Piping input in would work, or providing EOF (ctrl-D). If termination is required after the first input, exit()s can be added.

To build/run:

```
Build the main program:
% lex -o wordmath.yy.c wordmath.l
% cc -o wordmath wordmath.yy.c -ll

Execute to create a specific transpiled program:
% echo "This is a number, add 8, subtract 5, repeat." | ./wordmath > program.l

Build the transpiled program:
% lex -o program.yy.c program.l
% cc -o program program.yy.c -ll

Execute the transpiled program (with input 3, called via a pipe or inline):
% echo 3 | ./program
1
% ./program
3
1
^D
%

```

Test 1:

```
%%
.* {int n=atoi(yytext);printf("%d",n);}
%%

```

Test 2:

```
%%
.* {int n=atoi(yytext);n/=5;n=-n+9;printf("%d",n);}
%%

```

Test 3:

```
%%
.* {int n=atoi(yytext);n+=5;n+=10;n*=2;n-=15;n-=15;n/=2;printf("%d",n);}
%%

```

Test 4:

```
%%
.* {int n=atoi(yytext);n-=1;n-=1;n-=1;printf("%d",n);}
%%

```

# Answer
> 2 votes
# Pip, 58 bytes

Too bad I haven't implemented that reverse-subtraction operator yet.

```
{p:a:sNa?ap['Y("-y+  y- y// y+ y* "^sa@?Y`\d`)|'qa@y]}Mq^k

```

The program takes a WordMath script from stdin and outputs Pip code to stdout. The code that is output, similarly, takes a number from stdin and outputs the result to stdout. Try it online!

### Strategy

For input like this:

```
Think of a number, multiply by 3, add 1.

```

we want output like this:

```
YqYy*3Yy+1

```

which works as follows:

```
Yq    Yank a line of stdin into y
Yy*3  Compute y*3 and yank result into y
Yy+1  Compute y+1 and yank result into y
      Last expression is autoprinted

```

### Ungolfed + explanation

```
{
 p : a : sNa ? a p
 [
  'Y
  ("-y+  y- y// y+ y* "^s a@?Y`\d`) | 'q
  a@y
 ]
} M q^k

```

The basic structure of the program is `{...}Mq^k`, which splits `q` (a line of stdin) on `k` (comma-space) and `M`aps a function to each element.

Inside the function, we start by handling the `repeat` case. The shortest test in Pip seems to be `sNa` (is there a space in the command). If so, we want to use `a`; if not, use `p`, which stores the previous command. Assign that value back to `a` and also to `p` (for next time).

For our return value, we use a list, which is fine because the default output format for lists is to concatenate everything together. The result always starts with `Y`. Next, we need a lookup table for the operations.

Observe that the lengths of `add`  (4), `subtract`  (9), `divide by`  (10), `multiply by`  (12), and `subtract from`  (14) are all distinct. Further observe that they are still distinct when taken mod 7. Thus, we can use them to index into a seven-element list (containing five code snippets and two placeholders) to map each WordMath command to the appropriate Pip code (designed so the number can simply be concatenated to the end):

* 0: `-y+` (`subtract from`)
* 1: placeholder
* 2: `y-` (`subtract`)
* 3: `y//` (`divide by`)
* 4: `y+` (`add`)
* 5: `y*` (`multiply by`)
* 6: placeholder

For the indices, we use regex to get the index of the first digit in the command: `a@?`\d``. We also yank the regex into `y` for future use. The lookup table is generated by splitting the string `"-y+ y- y// y+ y* "` on `s` (space).

We still have to handle the first entry, which should translate into the code `Yq`. Since `Think of a number` does not contain any digits, the `@?` operator returns nil. Using nil as an index into the lookup table also returns nil. Nil is falsy, so all we need to do is add `|'q` to use `q` instead of an operation for this case.

The final element of the returned list is the number itself. We obtain this via `a@y` (find all matches in the command of the digit regex we yanked earlier). This returns a list of digits, but again, it's not a problem because all lists will be concatenated when output. For the first entry, `a@y` matches no digits and gives empty list, which doesn't add anything to the output.

### For example

With input

```
Think of a number, subtract from 20, add 2, repeat.

```

the map expression gives the list

```
[["Y";"q";[]]; ["Y";"-y+";[2;0]]; ["Y";"y+";[2]]; ["Y";"y+";[2]]]

```

which, when concatenated, outputs

```
YqY-y+20Yy+2Yy+2

```

# Answer
> 2 votes
# Python 2, ~~154~~ ~~153~~ 146 bytes

Fixed, and even saved several bytes in the process. ^\__^

```
for c in input()[9:-1].split(","):s=c.rfind(" ");p=o=s and"x="+"-x+ input() x- x// x+ x*".split()[s%7]+c[s:]*(c[0]<"a")or p;print o
print"print x"

```

Try it online!

Based on the same strategy as my Pip answer. Python-specific features:

* `Think of`  and the closing `.` are removed from the string before splitting (`input()[9:-1]`). The period was too pesky to handle in the main loop. Removing the first nine characters helps for a different reason (see below).
* Instead of getting each command's length by regex-searching for a digit (expensive in Python because `import re`), we use `rfind(" ")` to find the last space in the command. We can also use this to check for the `repeat` case.
* Python doesn't have Pip's cyclical indexing, so we have to take the index mod 7 explicitly. On the other hand, this means that we can remove the last dummy value in the lookup table, since the index mod 7 is never 6.
* The "command" the first time through is `a number`, in which the index of the space is `1`. This index conveniently fills the other hole in the lookup table. The other problem with processing the input stage in the main loop was the `+c[s:]` part, which would result in `x=input() number`. To resolve that problem, we string-multiply by `c[0]<"a"`: `1` for all regular commands, in which `c` starts with a space, but `0` for the initial `a number`.

# Answer
> 1 votes
# WinDbg, ~~449~~ 388 bytes

```
as, }@$t1
as. }0;?@$t0
asThink n10;ed8<<22;r$t0=dwo(8<<22);r$t1=0;.do{
aSa " "
asQ .printf";r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0
as/c add Q +"
aSby " "
as/c divide Q /"
asfrom 0;r$t0=-@$t0+
as/c multiply Q *"
aSnumber " "
aSof " "
asrepeat +1
as/c subtract Q -"
.for(r$t9=1;by(@$t0);r$t0=@$t0+1){j44!=by(@$t0) .printf"%c",by(@$t0);.if116!=by(@$t0-1){.printf" , "}};.printf"\b ."

```

*-61 bytes by defining alias for repeated code*

Inspired by LambdaBeta's use of `#define`. This approach modifies the WordMath syntax slightly (`,` and `.` must be space-delimited like the other words, and `,` does not follow `repeat`), and creates alias such that the modified WordMath syntax is valid WinDbg code. The last line does what the question asks and transpiles by converting the input into the modified syntax.

Input is taken by setting a string at a memory address and setting the pseudo-register `$t0` to that address. Note: this will overwrite the `int` at `0x2000000`, so if you start your string there, it'll be partly overwritten. `$t0` will also be overwritten.

Because it creates aliases, depending on whether this code has run before or after setting teh string, the output code will be different (either aliased or not). Unfortunately, I didn't find a way to get the aliases to properly expand without being whitespace delimited (meaning the WordMath script could not just be executed directly without being transformed first).

How it works:

```
* $t1 is used for repeating and $t0 is used to read the input and hold the accumulator
* Alias , to }@$t1 -- closing do-while loop and allowing repeat
as , }@$t1

* Alias . to }0;?@$t0 -- close do-while loop and evaluate $t0 (accumulator)
as . }0;?@$t0

* Alias Think to (note this is one line)
as Think n10;               * Set base 10
         ed 8<<22;          * Read ints to address 0x2000000. Enter nothing to exit input mode
         r$t0 = dwo(8<<22); * Set $t0 = first int
         r$t1=0;.do{        * Open do-while

* Alias a to nothing
aS a " "

* Alias add to (note one line):
as add ;                       * Close previous statement
       r$t1=1;.do{r$t1=@$t1-1; * Open do-while (once) loop
       r$t0=@$t0+              * Add number to $t0

* Alias by to nothing
aS by " "

* Alias divide to (note one line):
as divide ;                       * Close previous statement
          r$t1=1;.do{r$t1=@$t1-1; * Open do-while (once) loop
          r$t0=@$t0/              * Divide next number from $t0

* Alias from to (note one line):
as from 0;         * Preceding subtract statement subtracts 0
       r$t0=-@$t0+ * Subtract $t0 from next number

* Alias multiply to (note one line):
as multiply ;                       * Close previous statement
            r$t1=1;.do{r$t1=@$t1-1; * Open do-while (once) loop
            r$t0=@$t0*              * Multiply next number with $t0

* Alias number to nothing
aS number " "

* Alias of to nothing
aS of " "

* Alias repeat to +1 making do-while (once) loops into do-while (once)+1
as repeat +1

* Alias subtract to (note one line):
as subtract ;                       * Close previous statement
            r$t1=1;.do{r$t1=@$t1-1; * Open do-while (once) loop
            r$t0=@$t0-              * Subtract next number from $t0

.for (r$t9=1; by(@$t0); r$t0=@$t0+1) * Enumerate the string
{
    j 44!=by(@$t0)                   * If not comma
        .printf "%c",by(@$t0);       * Print the char
    * implicit else
        .if 116!=by(@$t0-1)          * Else if the previous char is not t
        {
          .printf " , "              * Print the comma with spaces around it
        }
};
.printf "\b ."                       * Replacing ending "." with " ."

```

Sample output, entering the string before running this code once (the resulting program resembles WordMath):

```
0:000> r$t0=8<<22
0:000> eza8<<22"Think of a number, add 5, add 10, multiply by 2, subtract 15, repeat, divide by 2."
0:000> as, }@$t1
0:000> as. }0;?@$t0
0:000> asThink n10;ed8<<22;r$t0=dwo(8<<22);r$t1=0;.do{
0:000> aSa " "
0:000> asadd ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0+
0:000> aSby " "
0:000> asdivide ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0/
0:000> asfrom 0;r$t0=-@$t0+
0:000> asmultiply ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0*
0:000> aSnumber " "
0:000> aSof " "
0:000> asrepeat +1
0:000> assubtract ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0-
0:000> .for(r$t9=1;by(@$t0);r$t0=@$t0+1){j44!=by(@$t0) .printf"%c",by(@$t0);.if116!=by(@$t0-1){.printf" , "}};.printf"\b ."
Think of a number ,  add 5 ,  add 10 ,  multiply by 2 ,  subtract 15 ,  repeat divide by 2 }0;?@$t0

0:000> Think of a number ,  add 5 ,  add 10 ,  multiply by 2 ,  subtract 15 ,  repeat divide by 2 }0;?@$t0
base is 10
02000000 6e696854 18
18
02000004 666f206b

Evaluate expression: 18 = 00000012

```

Sample output, entering the string after after this code has run once (the aliases are expanded when entering the string so the resulting program is not as pretty):

```
0:000> r$t0=8<<22
0:000> eza8<<22"Think of a number, add 5, add 10, multiply by 2, subtract 15, repeat, divide by 2."
0:000> as, }@$t1
0:000> as. }0;?@$t0
0:000> asThink n10;ed8<<22;r$t0=dwo(8<<22);r$t1=0;.do{
0:000> aSa " "
0:000> asadd ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0+
0:000> aSby " "
0:000> asdivide ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0/
0:000> asfrom 0;r$t0=-@$t0+
0:000> asmultiply ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0*
0:000> aSnumber " "
0:000> aSof " "
0:000> asrepeat +1
0:000> assubtract ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0-
0:000> .for(r$t9=1;by(@$t0);r$t0=@$t0+1){j44!=by(@$t0) .printf"%c",by(@$t0);.if116!=by(@$t0-1){.printf" , "}};.printf"\b ."
n10;ed8<<22;r$t0=dwo(8<<22);r$t1=0;.do{     number ,  ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0+ 5 ,  ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0+ 10 ,  ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0*   2 ,  ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0- 15 ,  repeat ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0/   2 }0;?@$t0

0:000> n10;ed8<<22;r$t0=dwo(8<<22);r$t1=0;.do{     number ,  ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0+ 5 ,  ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0+ 10 ,  ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0*   2 ,  ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0- 15 ,  repeat ;r$t1=1;.do{r$t1=@$t1-1;r$t0=@$t0/   2 }0;?@$t0
base is 10
02000000 3b30316e 26
26
02000004 3c386465

Evaluate expression: 26 = 0000001a

```

Some more sample output, just using the slightly modified WordMath syntax:

```
0:000> Think of a number , add 1 , repeat repeat repeat divide by 3 .
base is 10
02000000 0000001a 3
3
02000004 3c386465

Evaluate expression: 2 = 00000002

0:000> Think of a number , divide by 5 , subtract from 9 .
base is 10
02000000 00000003 29
29
02000004 3c386465

Evaluate expression: 4 = 00000004

```

# Answer
> 0 votes
# Scala, 338 bytes

## Try it yourself at ideone

```
s=>{val n=(_:String)filter(_.isDigit)toInt;(Seq("").tail/:s.split(",").tail)((a,&)=> &match{case&if&contains "v"=>a:+"x/="+n(&)
case&if&contains "d"=>a:+"x+="+n(&)
case&if&contains "y"=>a:+"x*="+n(&)
case&if&contains "f"=>a:+"x="+n(&)+"-x"
case&if&contains "s"=>a:+"x-="+n(&)
case p=>a:+a.last})mkString("var x=readInt;",";",";print(x)")}

```

### Explanation:

```
// define a function with a parameter s
s => {
    // define a function with a String parameter to extract a number from a string
    val n =
        // filter out the chars that arent't digits
        (_: String) filter (_.isDigit)
        // and parse the number
        toInt;
    // take the tail of a list with an empty string,
    // which is the empty list of type Seq[String].
    // This is the start value for the fold...
    (Seq("").tail /:
        // ... of the tail of the sentence splitted at commas
        s.split(",").tail
    ) (
        // This is the function for the fold.
        // a is the accumulator (the list), and the current element is called &
        (a, &) => & match {
            // if & contains a "v", append "x/=" + n(&) to a.
            case & if & contains "v" => a :+ "x/=" + n(&)
            // the other cases are similar
            case & if & contains "d" => a :+ "x+=" + n(&)
            case & if & contains "y" => a :+ "x*=" + n(&)
            case & if & contains "f" => a :+ "x=" + n(&) + "-x"
            case & if & contains "s" => a :+ "x-=" + n(&)
            // for the repeat, apppend the last value of a to a
            case p                   => a :+ a.last
        }
     )
     // make a string out of the parts by joining them with semicolons,
     // prepending "var x=readInt;" and appending ";print(x)"
     mkString("var x=readInt;", ";", ";print(x)")
}

```

---
Tags: code-golf, arithmetic, parsing, interpreter, code-generation
---