title: Find the Missing Letter

text:
# Question
Title: Find the Missing Letter
# Guidelines

## Task

Write a method that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array (lists in some languages).

---

## Rules

* This is code golf so the shortest answer in bytes wins!
* You will always get a valid array
* There will always be exactly one letter missing
* The length of the array will always be at least 2.
* The array will always contain letters in only one case (uppercase or lowercase)
* You must output in the same case (uppercase or lowercase) that the input is
* The array will always only go one letter a time (skipping the missing letter)
* The array length will be between 2 and 25
* The first or last element of the array will never be missing

---

# Examples

`['a','b','c','d','f'] -> 'e'`

`['O','Q','R','S'] -> 'P'`

`['x','z'] -> 'y'`

`['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','w','x','y','z'] -> 'v'`

# Answer
# Pyth, 5 bytes

```
-rhQe

```

Try it online!
> 5 votes

# Answer
# C# (.NET Core), 48 47 46 bytes, input as char array

```
s=>{for(int i=0;s[++i]==++s[0];);return s[0];}

```

Try it online!

Explanation: the first element in the array is incremented as well as a pointer iterating the following elements. When both the first element and the current element are different, it returns the first element.

# C# (.NET Core), 58 56 50 bytes, input as string

```
s=>{var c=s[0];while(s.IndexOf(++c)>=0);return c;}

```

Try it online!

Previous 58-byte solution (referenced in the first comment):

```
s=>{for(int i=1;;i++)if(s[i]-s[0]>i)return(char)(s[i]-1);}

```

### Algorithms using System.Linq

The following algorithms must add `using System.Linq;` (18 bytes) to the byte count and therefore are longer.

I quite liked this one (52+18 bytes):

```
s=>{int i=0;return(char)(s.First(c=>c-s[0]>i++)-1);}

```

And you also have a one-liner (45+18)-byte solution:

```
s=>(char)(s.Where((c,i)=>c-s[0]>i).First()-1)

```

And a very clever (37+18)-byte solution, courtesy of Ed'ka:

```
s=>s.Select(e=>++e).Except(s).First()

```
> 12 votes

# Answer
## Alice, 10 bytes

```
/X.
\ior@/

```

Try it online!

### Explanation

This is just a framework for linear programs that operate entirely in Ordinal (string processing) mode:

```
/...
\.../

```

The actual linear code is then:

```
i.rXo@

```

Which does:

```
i   Read all input.
.   Duplicate.
r   Range expansion. If adjacent letters don't have adjacent code points, the
    intermediate code points are filled in between them. E.g. "ae" would turn
    into "abcde". For the inputs in this challenge, this will simply insert
    the missing letter.
X   Symmetric set difference. Drops all the letters that appear in both strings,
    i.e. everything except the one that was inserted by the range expansion.
o   Output the result.
@   Terminate the program.

```
> 8 votes

# Answer
# Haskell, ~~33~~ 30 bytes

```
f a=until(`notElem`a)succ$a!!0

```

Try it online!
> 7 votes

# Answer
# Java 8, ~~70~~ ~~57~~ ~~56~~ ~~48~~ 46 bytes

```
a->{for(int i=0;++a[0]==a[++i];);return a[0];}

```

-14 (70 → 56) and -2 (48 → 46) bytes thanks to *@CarlosAlejo*.
-8 (56 → 48) bytes thanks to *@Nevay*.

**Explanation:**

Try it here.

```
a->{            // Method with char-array parameter and char return-type
  for(int i=0;  //  Start index-integer at 0 and loop as long as
    ++a[0]      //   the previous character + 1 (by modifying the character at index 0)
    ==a[++i];   //   equals the next character (by raising the index by 1 before checking)
  );            //  End of loop
  return a[0];  //  Return the now modified character at index 0 in the array
}               // End of method

```
> 7 votes

# Answer
# Ruby, 21 characters

```
->a{[*a[0]..a[-1]]-a}

```

Returns a single element array, according to question owner's comment.

Sample run:

```
irb(main):001:0> ->a{[*a[0]..a[-1]]-a}[['a','b','c','d','f']]
=> ["e"]

```

Try it online!
> 7 votes

# Answer
# C (gcc), 33 ~~35~~ ~~36~~ ~~48~~ ~~60~~ bytes

All optimizations should be turned off and only on 32-bit GCC.

```
f(char*v){v=*v+++1-*v?*v-1:f(v);}

```

Take input as a string.

Try it online!
> 6 votes

# Answer
# Python 3, ~~74~~ ~~62~~ ~~58~~ ~~44~~ 40 bytes

*-12 bytes thanks to Erik the Outgolfer. -18 bytes thanks to Leaky Nun. -4 bytes thanks to musicman523.*

Takes input as a bytestring.

```
lambda s:chr(*{*range(s[0],s[-1])}-{*s})

```

Try it online!

Another cool solution:

```
lambda s:chr(*{*range(*s[::~-len(s)])}-{*s})

```
> 5 votes

# Answer
# Mathematica, 46 bytes

```
Min@Complement[CharacterRange@@#[[{1,-1}]],#]&

```
> 4 votes

# Answer
# SWI Prolog, 124 bytes

```
m([H|T]):-n(H,N),c(T,N),!,m(T).
n(I,N):-o(I,C),D is C+1,o(N,D).
c([N|_],N).
c(_,N):-print(N),!,fail.
o(C,O):-char_code(C,O).

```

Examples:

```
?- m(['a','b','c','d','f']).
e
false.

?- m(['O','Q','R','S']).
'P'
false.

?- m(['x','z']).
y
false.

?- m(['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','w','x','y','z']).
v
false.

```

Little explanation:

The `m` is the "main" procedure,the `n` produces next expected character in the list. The `c` does comparison - if expectation matches the next item, continue, else print out expected character and jump out of the window.
> 4 votes

# Answer
# JavaScript (ES6), 70 bytes

Input as a character array

```
(a,p)=>a.some(c=>(q=p+1,p=c.charCodeAt(),p>q))&&String.fromCharCode(q)

```

*Less golfed*

```
a=>{
  p = undefined;
  for(i = 0; c = a[i]; i++)
  {
    q = p+1
    p = c.charCodeAt()
    if (p>q)
      return String.fromCharCode(q)
  }
}

```

**Test**

```
F=(a,p)=>a.some(c=>(q=p+1,p=c.charCodeAt(),p>q))&&String.fromCharCode(q)

function update() {
  var a0=A0.value.charCodeAt()
  var a1=A1.value.charCodeAt()
  if (a1>a0) {
    var r = [...Array(a1-a0+1)]
      .map((x,i)=>String.fromCharCode(a0+i))
      .filter(x => x != AX.value)
    I.textContent = r.join('') + " => " + F(r)
  }
  else {
    I.textContent=''
  }
}

update()
```

```
input { width: 1em }
```

```
Range from <input id=A0 value='O' pattern='[a-zA-Z]' length=1 oninput='update()'>
to <input id=A1 value='T' pattern='[a-zA-Z]' length=1 oninput='update()'>
excluding <input id=AX value='Q' pattern='[a-zA-Z]' length=1 oninput='update()'>
<pre id=I></pre>
```
> 3 votes

# Answer
# PHP\>=7.1, 46 bytes

Take input as string

```
<?=trim(join(range(($a=$argn)[0],$a[-1])),$a);

```

PHP Sandbox Online
> 3 votes

# Answer
# Retina, ~~33~~ 25 bytes

```
$
¶$_
T`p`_p`.*$
D`.
!`.$

```

Try it online! Works with any range of ASCII characters. Edit: Saved 8 bytes thanks to @MartinEnder. Explanation: The first stage duplicates the input. The second decreases all of the characters in the copy by 1 code point. The third stage deletes all of the characters in the copy that still appear in the original. This just leaves the original input, the character that precedes the first character of the original input and the missing character. The last stage then just matches the missing character.
> 3 votes

# Answer
# Excel, 110 + 2 = 112 bytes

```
=CHAR(CODE(LEFT(A1))-1+MATCH(0,IFERROR(FIND(CHAR(ROW(INDIRECT(CODE(LEFT(A1))&":"&CODE(RIGHT(A1))))),A1),0),0))

```

Must be entered as an array formula (`Ctrl`+`Shift`+`Enter`) which adds curly brackets `{ }` on each end, adding two bytes. Input is as a string in `A1`, which is OK per OP.

This is not the shortest answer by far (Excel rarely is) but I like seeing if it can be done.
> 3 votes

# Answer
# Husk, 6 bytes

```
→S-(ḣ→

```

Try it online!

This function takes a string (list of characters) as input, and returns a character as output.

### Explanation

```
→S-(ḣ→
    ḣ→    Get the list of all characters from the null byte to the last character of the input
 S-       Subtract the input from this list
→         Get the last element of the result

```
> 3 votes

# Answer
## C++14, standard library, generic container type (87 86 bytes)

```
[](auto a){return++*adjacent_find(begin(a),end(a),[](auto a,auto b){return a+1!=b;});}

```

Container type from namespace `::std` is assumed (e.g. `std::string`, `std::list` or `std::vector`. Otherwise `using namespace std;` or similar would be assumed.

> Thanks to @Ven, with a little bit of preprocessor hacking, you get get it **down to 82 bytes** (1 newline)
>
> ```
> #define x [](auto a,int b=0){return++
> x *adjacent_find(begin(a),end(a),x a!=b;});}
>
> ```

See it **`Live On Coliru`**

## C++14 no standard library (still generic, 64 63 bytes)

```
[](auto& a){auto p=*begin(a);for(auto c:a)if(c!=p++)return--p;}

```

Again, need to help name lookup only if container type not from namespace `::std` (or associated with it)

**`Live On Coliru`** for `std::string` e.g.

**`Live On Coliru`** for `char const[]` e.g.
> 3 votes

# Answer
# Jelly, 6 bytes

```
O‘Ọḟ⁸Ḣ

```

Try it online!

## How it works

```
O‘Ọḟ⁸Ḣ - Main link. Takes a string S on the left
O      - Convert to char codes
 ‘     - Increment each
  Ọ    - Convert from char codes

         This yields the characters that directly follow each character in S
         Call this C

    ⁸  - Yield S
   ḟ   - Remove the characters from C that are in S
     Ḣ - Return the first one

```
> 3 votes

# Answer
# Charcoal, 18 bytes

```
Ｆγ¿¬∨∨‹ι⌊θ›ι⌈θ№θιι

```

Try it online! Link is to verbose version of code. Takes input as a string. Works with any almost contiguous sequence of ASCII characters.
> 2 votes

# Answer
# Rexx (Regina), 56 bytes

```
a=arg(1)
say translate(xrange(left(a,1),right(a,1)),'',a)

```

Try it online!

Finally one that enables REXX to use its strong string-manipulation.
> 2 votes

# Answer
# C#, 104 bytes

```
using System.Linq;a=>(char)Enumerable.Range(a.Min(),a.Max()-a.Min()).Except(a.Select(c=>(int)c)).First()

```

Full/Formatted version:

```
using System.Linq;

namespace System
{
    class P
    {
        static void Main()
        {
            Func<char[], char> f = a =>
                (char)Enumerable.Range(a.Min(), a.Max() - a.Min())
                                .Except(a.Select(c=>(int)c))
                                .First();

            Console.WriteLine(f(new[] { 'a', 'b', 'c', 'd', 'f' }));

            Console.ReadLine();
        }
    }
}

```
> 2 votes

# Answer
# CJam, 6 bytes (full program) / 7 bytes (code block)

```
q),^W=

```

Try it online!

This is a full CJam program that reads the input string from standard input and prints the missing letter to standard output. CJam doesn't actually have "methods", which is what the challenge asks for, but the closest thing would probably be an executable code block, like this:

```
{),^W=}

```

Try it online!

This code block, when evaluated, takes the input as a string (i.e. an array of characters) on the stack, and returns the missing character also on the stack.

---

**Explanation:** In the full program, `q` reads the input string and places it on the stack. `)` then pops off the last character of the input string, and the range operator `,` turns it into an array containing all characters with code points below it (including all letters before it in the alphabet). Thus, for example, if the input was `cdfgh`, then after `),` the stack would contain the strings `cdfg` (i.e. the input with the last letter removed) and `...abcdefg`, where `...` stands for a bunch of characters with ASCII codes below `a` (i.e. all characters below the removed last input letter).

The symmetric set difference operator `^` then combines these strings into a single string that contains exactly those characters that appear in one of the strings, but not in both. It preserves the order in which the characters appear in the strings, so for the example input `cdfg`, the result after `),^` will be `...abe`, where `...` again stands for a bunch of characters with ASCII codes below `a`. Finally, `W=` just extracts the last character of this string, which is exactly the missing character `e` that we wanted to find (and discards the rest). When the program ends, the CJam interpreter implicitly prints out the contents of the stack.

---

# Bonus: GolfScript, 6 bytes (full program)

```
),^-1>

```

Try it online!

It turns out that nearly the same code also works in GolfScript. We save one byte in the full program version due to GolfScript's implicit input, but lose one byte because, unlike CJam's `W`, GolfScript doesn't have a handy single-letter variable initialized to -1.

Also, CJam has separate integer and character types (and strings are just arrays containing characters), whereas GolfScript only has a single integer type (and has a special string type that behaves somewhat differently from normal arrays). The result of all this is that, if we want the GolfScript interpreter to print out the actual missing letter instead of its ASCII code number, we need to return a single-character string instead of just the character itself. Fortunately, making that change here just requires replacing the indexing operator `=` with the array/string left truncation operator `>`.

Of course, thanks to GolfScript's implicit I/O, the code above can also be used as a snippet that reads a string from the stack and returns a single-character string containing the missing letter. Or, rather, any snippet that takes a single string on the stack as an argument, and returns its output as a printable string on the stack, is also a full GolfScript program.
> 2 votes

# Answer
## JavaScript (ES6), 64 bytes

Takes input as a string.

```
s=>(g=p=>(c=String.fromCharCode(n++))<s[p]?p?c:g(p):g(p+1))(n=0)

```

### How?

* Initialization: We start with ***n = 0*** and ***p = 0*** and call the recursive function ***g()***.

```
g = p =>                                   // given p
  (c = String.fromCharCode(n++)) < s[p] ?  // if the next char. c is not equal to s[p]:
    p ?                                    //   if p is not equal to zero:
      c                                    //     step #3
    :                                      //   else:
      g(p)                                 //     step #1
  :                                        // else:
    g(p + 1)                               //   step #2

```
* Step #1: We increment ***n*** until `c = String.fromCharCode(n)` is equal to the first character of the input string ***s\[0\]***.
* Step #2: Now that we're synchronized, we increment both ***n*** and ***p*** at the same time until `c = String.fromCharCode(n)` is not equal to ***s\[p\]*** anymore.
* Step #3: We return ***c***: the expected character which was not found.

### Test cases

```
let f =

s=>(g=p=>(c=String.fromCharCode(n++))<s[p]?p?c:g(p):g(p+1))(n=0)

console.log(f('abcdf'))                     // -> 'e'
console.log(f('OQRS'))                      // -> 'P'
console.log(f('xz'))                        // -> 'y'
console.log(f('abcdefghijklmnopqrstuwxyz')) // -> 'v'
```
> 2 votes

# Answer
# APL (Dyalog), 17 bytes

```
(⊃⎕AV/⍨∨\∧~)⎕AV∘∊

```

Try it online!

`⎕AV∘∊` Boolean: each character in the **A**tomic **V**ector (character set) member of the argument?

`(``)` apply the following tacit function:

the first element of

`⎕AV` the **A**tomic **V**ector (the character set)

`/⍨` which

`∨\` follows the initial (member of the argument)

but

`~` is not (a member of the argument)
> 2 votes

# Answer
# MATL, ~~8~~ 7 bytes

*1 byte saved thanks to @Luis*

```
tdqf)Qc

```

Try it at MATL Online

**Explanation**

```
      % Implicitly grab the input as a string
t     % Duplicate the string
d     % Compute the differences between successive characters
q     % Subtract 1 from each element
f     % Get the locations of all non-zero characters (1-based index)
)     % Extract that character from the string
Q     % Add one to get the next character (the missing one)
c     % Convert to character and display

```
> 2 votes

# Answer
# Python 3, 42 bytes

```
f=lambda a,*r:r[0]-a>1and chr(a+1)or f(*r)

```

Try it online!

Uses unpacked bytestring as input: `f(*b'OQRS')`
> 2 votes

# Answer
# k, ~~17~~ 13 bytes

-4 bytes thanks to coltim.

```
{*(`c$1+x)^x}

```

Try it online!

Explanation:

```
{           } /def func(x): # x should be a list of chars
      1+x     /  above  = [ord(c)+1 for c in x]
  (`c$   )    /  above  = [chr(i) for i in above]
          ^x  /  result = [e for e in above if e not in x]
 *            /  return result[0]

```
> 2 votes

# Answer
# Python 2 - 76 bytes

Loses to existing python 2 solution but it's a slightly different approach so I thought I'd post it anyway:

```
lambda c:[chr(x)for x in range(ord(c[0]),ord(c[0]+26)if chr(x)not in c][0]

```
> 2 votes

# Answer
# Husk, 3 bytes

```
-¹…

```

Try it online!

I'm slightly nervous about posting this, as it seems wierd to beat all other answers (including one in Husk) by such a significant margin... but it seems to work for the test cases, at least...

**How?**

```
-       # output elements that are different between:
 ¹      # 1. the input list, and
  …     # 2. the input list, with all the gaps filled
        #    with the missing character ranges

```
> 2 votes

# Answer
# Arturo, 21 bytes

```
$->s[--@s\0..last<=s]

```

Try it!

```
$->s[            ; a function taking an argument s
    <=s          ; duplicate s
    last         ; last letter in s
    ..           ; range
    s\0          ; first letter in s
    @            ; reify range
    --           ; set difference (between the range and duplicated s)
]                ; end function

```
> 2 votes

# Answer
# Jelly, 7 bytes

```
.ịOr/Ọḟ

```

Try it online!
> 1 votes

# Answer
# 05AB1E, ~~9~~ 7 bytes

```
Ç¤ÝsKçθ

```

Try it online!
> 1 votes

# Answer
# ES6, 125 bytes:

```
(a=>((s,f)=>(r=(i,b)=>a[i]?r(i+1,b||(s[f](i)-s[f](i-1)-1&&String.fromCharCode(s[f](i-1)+1))):b)(1,0))(a.join(""),"charCodeAt"))

```

http://jsbin.com/vasoqidawe/edit?console

The returned function needs to be called with an array

```
(["a","c"])

```

one could save another 9 bytes through removing *.join("")* and passing a string:

```
("ac")

```

---

# ES6, 108 bytes:

```
(a=>((s,f,o)=>(a.find((_,i)=>(o?++o:o=s[f](i))!==s[f](i)),String.fromCharCode(o)))(a.join(""),'charCodeAt'),0))

```

http://jsbin.com/tudiribiye/edit?console
> 1 votes

# Answer
# J, 20 bytes

```
{&a.>:I.1 0 1&E.a.e.

```
* `a.e.` boolean mask for the input letters across ascii charset
* `1 0 1&E.` new boolean mask indicating if the sequence `101` begins at that index, ie, find any place a "skip" sequence begins
* `I.` the index of that match, ie, the character before the skipped one
* `>:` increment by 1, ie, the index of the skipped char within ascii charset
* `{&a.` pick that index from the ascii charset, ie, return the skipped char

Try it online!
> 1 votes

# Answer
# Common Lisp, 88 bytes

```
(lambda(s)(loop as(x y)on s if(>(#1=char-code y)(1+(#1#x)))return(code-char(1+(#1#x)))))

```

Try it online!
> 1 votes

# Answer
# Python 2, 69 bytes

```
lambda a:chr((ord(a[0])+ord(a[-1]))*-~len(a)/2-sum(ord(x)for x in a))

```

Try it online!

**Some explanations** As we know the first and the last elements of the list, we can easily compute the sum of the codes of all the chars in the `list + the missed char` (using *summary* formulas of *arithmetic progression*). The difference between this sum and the sum of the codes of all the chars in the `list` gives the code of the missed letter.
> 1 votes

# Answer
# PHP, 43 bytes

```
for($x=$argn[0];$argn[++$i]==++$x;);echo$x;

```
> 1 votes

# Answer
# Scala, 63 chars, 63 bytes

```
for(i<-1 to t.size-1)if(t(i-1)+1!=t(i))return (t(i)-1).toChar
0

```

See TIO link for tests. `t` is the input (a String), and I output a char. I tried doing it with a string (like this) but I don't think it is correct to output the code of the missing char. This would make the code 3 bytes shorter.

Try It Online!
> 1 votes

# Answer
# 05AB1E, 5 bytes

```
ÇŸçsK

```

Uses the **05AB1E** encoding. Try it online!
> 1 votes

# Answer
# Japt, 14 bytes

```
mc
g oUo¹kU md

```

Try it online!
> 1 votes

# Answer
# PHP, 44 bytes

operating on separate command line arguments:

```
for($c=$argv[1];++$c==$argv[-~++$i];)echo$c;            # 44 bytes
for($c=$argv[$i=1];++$c==$argv[++$i];)echo$c;           # 45 bytes
<?=end(array_diff(range($argv[1],end($argv)),$argv));   # 53 bytes
<?=trim(join(range($argv[1],end($argv))),join($argv));  # 54 bytes

```
> 1 votes

# Answer
# Brain-Flak, 45 bytes

```
{([{}()]({})){{}({}<>)((<()>))}{}}{}({}[()])

```

Try it online!

44 bytes of code, and `+1` byte for the `-c` flag.

Surprisingly short for a language terrible at manipulating strings.
> 1 votes

# Answer
# Python 3, 92 bytes

```
from string import *; f=lambda s:{*[a for a in ascii_letters if a>=s[0] and a<=s[-1] ]}^{*s}

```

Try it online!

Long solution but I like how sets work, and it seemed shorter in my head.
> 1 votes

# Answer
# , 67 bytes

```
l=letters;L=LETTERS;a=scan(,'');`if`(a==l&&T,l[a!=l][1],L[a!=L][1])

```

Try it online!
> 1 votes

# Answer
# Octave, ~~34~~ 32 bytes

```
@(x)char(setdiff(x(1):max(x),x))

```

Anonymous function; returns the missing character.

Try it online!
> 1 votes

# Answer
# Clojure, 102 89 bytes

```
#(nth(filter(fn[a](not(some #{a}%)))(map char(range(int(first %))(inc(int(last %)))))) 0)

```

Anonymous function, takes a string as parameter and returns the first missing character.

Seems like clojure ain't that good for golfin'...

Edit: Stripped whitespace and used `nth ... 0` instead of `first`
> 1 votes

# Answer
# x86 Machine Code, 11 bytes

```
8A 11
41
8A 01
48
38 C2
74 F6
C3

```

The above bytes define a function in 32-bit x86 machine code that finds the missing letter. It takes a single parameter, which is a pointer to the first element of a character array. (The length of the array is not needed, and the character array need not be NUL-terminated.)

The function uses the `fastcall` calling convention, where its parameter is passed in the `ECX` register. (It isn't essential that this calling convention or `ECX` be used for the input; we just need a register-based calling convention. You could trivially modify the code to take input in any register.)

The return value (the missing character) is returned in the `AL` register (low byte of `EAX`).

Note that characters are assumed to be 1 byte in length. This is perfectly sufficient for 8-bit ASCII characters, but is obviously not guaranteed to work on Unicode characters. The challenge doesn't specify, and the sample inputs only show basic ASCII. The whole world is ASCII, right?

**Ungolfed assembly mnemonics:**

```
; char FindMissingChar(char *letters);
Top:
    mov     dl, BYTE PTR [ecx]    ; load nth character from array
    inc     ecx                   ; increment pointer
    mov     al, BYTE PTR [ecx]    ; load n+1th character from array
    dec     eax                   ; decrement AL (shorter than 'dec al')
    cmp     dl, al                ; compare these two characters
    je      L2                    ; keep looping if n+1 is the char expected to follow n
    ret                           ; otherwise, return with the missing character in AL

```

**Try it online!**
<sub>(The TIO link passes the `-m32` switch to GCC to ensure that it is compiling in 32-bit mode, and also applies an attribute to ensure the compiler uses the correct calling convention.)</sub>
> 1 votes

# Answer
# \>\<\>, 12 bytes

```
i/o;
?/1+:i-

```

Try it online!

# Explanation

```
i/o;
?/1+:i-

i/            | Push 1 byte input to the stack then move to second line
 /1+:         | Add 1 to the stack top then duplicate it
     i-       | Push 1 byte input and take from the stack top
?/            | Check stack top is 0, if not 0 move back to line 1
 /o;          | Print the stack top

```
> 1 votes

# Answer
# 8th, 99 bytes

**Rationale**

If the distance between letters is greater than two, then there is a missing letter. Letter distance is obtained by computing the difference between ASCII code of each letter.

**Code**

```
: f ' nip s:each repeat over n:- 2 n:= if n:1+ "" swap s:+ . reset 1 then depth n:1- while! reset ;

```

**Ungolfed version**

```
: f \ s -- c
  ' nip s:each    \ convert each letter into its ASCII code and put them on stack
  repeat
    over
    n:- 2 n:=     \ check if there is a missing letter
    if
      n:1+        \ compute the ASCII code of missing letter
      "" swap s:+ \ convert ASCII code into printable character
      .           \ print out the missing letter
      reset 1     \ set condition to exit from while!
    then
    depth n:1-    \ verify if there are letters to check
  while!
  reset           \ clean stack
;

```

**Usage and examples**

```
ok> "abcdf" f
e
ok> "OQRS" f
P
ok> "xz" f
y
ok> "abcdefghijklmnopqrstuwxyz" f
v
ok> "ab" f

ok> "def" f

ok>

```
> 1 votes

# Answer
# Japt `-h`, 6 bytes

```
â¡Îc+Y

```

Try it

```
â¡Îc+Y     :Implicit input of array U
â          :Setwise union with
 ¡         :Map each 0-based index Y in U
  Î        :  First element of U
   c       :  Codepoint
    +Y     :  Add Y
           :Implicit output of last element

```
> 1 votes

# Answer
# Python 3, 62 bytes

Outgolfed, but has a clean string interface :)

```
def f(s,i=0):a=chr(ord(s[0])+i);return a==s[i]and f(s,i+1)or a

```

Try it online!
> 1 votes

# Answer
# Factor \+ `math.unicode`, 29 bytes

```
[ dup minmax [a,b] swap ∖ ]

```

Try it online!
> 1 votes

# Answer
# PowerShell Core, 36 bytes

```
param($a)$a[0]..$a[-1]|?{$_-notin$a}

```

Try it online!

Takes the chars as an array of strings

```
$a[0]..$a[-1]  # creates a range from the first to the last character in the argument
|?{$_-notin$a} # keeps only the character that is not in the argument

```
> 1 votes

# Answer
# , 18 bytes

```
{.@(>:-.])&.(3&u:)

```

Same approach as many others.

Try it online!

```
{.@(>:-.])&.(3&u:)
            (3&u:)  NB. convert to char codes
    >:              NB. increment
        ]           NB. input
      -.            NB. set difference
  @                 NB. then
{.                  NB. take the head
          &.        NB. lastly, perform the inverse of 3&u:, which converts back to char

```
> 1 votes

# Answer
# Mathematica, 83 bytes

```
T=ToCharacterCode;FromCharacterCode[T@#[[Position[Differences@T@#,{2}][[1,1]]]]+1]&

```

**input**

> \[{"a","b","c","d","f"}\]
> 0 votes

# Answer
## Perl, 39 bytes

**33 bytes code + 6 for `-nalF`.**

```
print grep"@F"!~$_,$F[0]..$F[$#F]

```

### Explanation

Creates a list of `first character` to `last character` and strips out any items that exist in the source string.

Try it online!
> 0 votes

# Answer
# J,30 bytes - till I can get rid of more parentheses!

```
a.{~((([:i.#)+/a.i.{.)-.a.i.])       'abcef'

```

Returns d

```
 a.{~     take from
 ((([:i.#) number of input bytes
 +/a.i.{.) starting from 2nd input byte
 -.a.i.]) subtract all but missing character from input

```

Or, a byte longer (31), completely different method but perhaps more elegantly?

```
a.{~<:a.i.t#~0,~<:2-/\a.i.t=:|.           'STUVX'

    returns W

```
> 0 votes

# Answer
```
const missed=ar=>String.fromCharCode(ar.reduce((a,v)=>a+1!==v.charCodeAt()?a:v.charCodeAt(),ar[0].charCodeAt())+1)

```
> 0 votes

# Answer
# Vyxal `g`, 5 bytes

```
C›C?F

```

Try it Online!

#### Explanation

```
C›C?F  # Implicit input
C      # Convert to charcodes
 ›     # Increment
  C    # Convert from charcodes
   ?F  # Remove elements which are in the input
       # g flag gets minimum (first) element

```
> 0 votes

# Answer
# Thunno 2 `BM`, 3 bytes

```
⁺$ṗ

```

Attempt This Online!

Port of my Vyxal answer.

#### Explanation

```
⁺$ṗ  # Implicit input, converted to ordinals by B flag
⁺    # Increment each ordinal in the list
 $   # Push the input (as an ordinal list) again
  ṗ  # Set difference between the incremented and original lists
     # Implicit output of minimum ordinal as a character

```
> 0 votes

---
Tags: code-golf, array, alphabet
---


# Question
Title: pwaS eht tirsf dna tasl setterl fo hace dorw
Or, "Swap the first and last letters of each word"

Your challenge is to, given a string of alphabetical ASCII characters as well as one other character to use as a delimiter (to separate each word), swap the first and last letters of each word. If there is a one-character word, leave it alone.

The examples/testcases use the lowercase letters and the space as the delimiter.

You do not need to handle punctuation; all of the inputs will only consist of the letters a through z, separated by a delimiter, all of a uniform case.

For example, with the string "hello world":

```
Input string: "hello world"
Identify each word: "[hello] [world]"
Identify the first and last letters of each word: "[[h]ell[o]] [[w]orl[d]]"
Swap the first letters of each word: "[[o]ell[h]] [[d]orl[w]]"
Final string: "oellh dorlw"

```

NOTE: the delimiter does not need to be inputted separately. The delimiter is just the character used to separate words. It can be anything. I wanted to leave options open for creative golfers, so I did not want to limit it to just spaces or new lines. The delimiter is just a character that separates words in the input string.

**Test cases:**

```
"swap the first and last letters of each word" -> "pwas eht tirsf dna tasl setterl fo hace dorw"
"hello world" -> "oellh dorlw"
"test cases" -> "test sasec"
"programming puzzles and code golf" -> "grogramminp suzzlep dna eodc folg"
"in a green meadow" -> "ni a nreeg weadom"
"yay racecar" -> "yay racecar"

```

# Answer
# TeX, 216 bytes (4 lines, 54 characters each)

***Because it's not about the byte count, it's about the quality of the typeset output :-)***

```
{\let~\catcode~`A13 \defA#1{~`#113\gdef}AGG#1{~`#1 13%
\global\let}GFF\elseGHH\fiAQQ{Q}AII{\ifxQ}AEE#1#2#3|{%
I#3#2#1FE{#1#2}#3|H}ADD#1#2|{I#1FE{}#1#2|H}ACC#1#2|{D%
#2Q|#1 }ABBH#1 {HI#1FC#1|BH}\gdef\S#1{\iftrueBH#1 Q }}

```

Try it Online! (Overleaf; not sure how it works)

Full test file:

```
{\let~\catcode~`A13 \defA#1{~`#113\gdef}AGG#1{~`#1 13%
\global\let}GFF\elseGHH\fiAQQ{Q}AII{\ifxQ}AEE#1#2#3|{%
I#3#2#1FE{#1#2}#3|H}ADD#1#2|{I#1FE{}#1#2|H}ACC#1#2|{D%
#2Q|#1 }ABBH#1 {HI#1FC#1|BH}\gdef\S#1{\iftrueBH#1 Q }}

\S{swap the a first and last letters of each word}

pwas eht a tirsf dna tasl setterl fo hace dorw

\S{SWAP THE A FIRST AND LAST LETTERS OF EACH WORD}

\bye

```

Output:

>

---

For LaTeX you just need the boilerplate:

```
\documentclass{article}
\begin{document}

{\let~\catcode~`A13 \defA#1{~`#113\gdef}AGG#1{~`#1 13%
\global\let}GFF\elseGHH\fiAQQ{Q}AII{\ifxQ}AEE#1#2#3|{%
I#3#2#1FE{#1#2}#3|H}ADD#1#2|{I#1FE{}#1#2|H}ACC#1#2|{D%
#2Q|#1 }ABBH#1 {HI#1FC#1|BH}\gdef\S#1{\iftrueBH#1 Q }}

\S{swap the a first and last letters of each word}

pwas eht a tirsf dna tasl setterl fo hace dorw

\S{SWAP THE A FIRST AND LAST LETTERS OF EACH WORD}

\end{document}

```

---

## Explanation

TeX is a strange beast. Reading normal code and understanding it is a feat by itself. Understanding obfuscated TeX code goes a few steps further. I'll try to make this understandable for people who don't know TeX as well, so before we start here's a few concepts about TeX to make things easier to follow:

### For (not so) absolute TeX beginners

* First, and most important item in this list: the code does *not* have to be in rectangle shape, even though pop culture might lead you to think so.
* TeX is a macro expansion language. You can, as an example, define `\def\sayhello#1{Hello, #1!}` and then write `\sayhello{Code Golfists}` to get TeX to print `Hello, Code Golfists!`. This is called an “undelimited macro”, and to feed it the first (and only, in this case) parameter you enclose it in braces. TeX removes those braces when the macro grabs the argument. You can use up to 9 parameters: `\def\say#1#2{#1, #2!}` then `\say{Good news}{everyone}`.
* The counterpart of undelimited macros are, unsurprisingly, delimited ones :) You could make the previous definition a tad more *semantical*: `\def\say #1 to #2.{#1, #2!}`. In this case the parameters are followed by so-called *parameter text*. Such parameter text delimits the argument of the macro (`#1` is delimited by `␣to␣`, spaces included, and `#2` is delimited by `.`). After that definition you can write `\say Good news to everyone.`, which will expand to `Good news, everyone!`. Nice, isn't it? :) However a delimited argument is (quoting the *TeXbook*) “the shortest (possibly empty) sequence of tokens with properly nested `{...}` groups that is followed in the input by this particular list of non-parameter tokens”. This means that the expansion of `\say Let's go to the mall to Martin` will produce a weird sentence. In this case you'd need to “hide” the first `␣to␣` with `{...}`: `\say {Let's go to the mall} to Martin`.
* So far so good. Now things start to get weird. When TeX reads a character (which is defined by a “character code”), it assigns that character a “category code” (catcode, for friends :) which defines what that character will mean. This combination of character and category code makes a token (more on that here, for example). The ones which are of interest for us here are basically:

+ **catcode 11**, which define tokens which can make up a control sequence (a posh name for a macro). By default all letters \[a-zA-Z\] are catcode 11, so I can write `\hello`, which is one single control sequence, while `\he11o` is the control sequence `\he` followed by two characters `1`, followed by the letter `o`, because `1` is not catcode 11. If I did `\catcode`1=11`, from that point on `\he11o` would be one control sequence. One important thing is that catcodes are set when TeX first sees the character at hand, and such catcode is *frozen*... FOREVER! (terms and conditions may apply)
    + **catcode 12**, which are most of other characters, such as `0"!@*(?,.-+/` and so forth. They are the *least* special type of catcode as they serve only for writing stuff on the paper. But hey, who uses TeX for writing?!? (again, terms and conditions may apply)
    + **catcode 13**, which is hell :) Really. Stop reading and go do something out of your life. You don't want to know what catcode 13 is. Ever heard of Friday, 13th? Guess where it got its name from! Continue at your own risk! A catcode 13 character, also called an “active” character, is not just a character anymore, it is a macro itself! You can define it to have parameters and expand to something like we saw above. After you do `\catcode`e=13` you *think* you can do `\def e{I am the letter e!}`, BUT. YOU. CANNOT! `e` is not a letter anymore, so `\def` is not the `\def` you know, it is `\d e f`! Oh, choose another letter you say? Okay! `\catcode`R=13 \def R{I am an ARRR!}`. Very well, Jimmy, try it! I dare you do that and write an `R` in your code! That's what a catcode 13 is. I AM CALM! Let's move on.
* Okay, now to grouping. This is fairly straightforward. Whatever assignments (`\def` is an assignment operation, `\let` (we'll get into it) is another) done in a group are restored to what they were before that group started unless that assignment is global. There are several ways to start groups, one of them is with catcode 1 and 2 characters (oh, catcodes again). By default `{` is catcode 1, or begin-group, and `}` is catcode 2, or end-group. An example: `\def\a{1} \a{\def\a{2} \a} \a` This prints `1 2 1`. Outside the group `\a` was `1`, then inside it was redefined to `2`, and when the group ended, it was restored to `1`.
* The `\let` operation is another assignment operation like `\def`, but rather different. With `\def` you *define* macros which will expand to stuff, with `\let` you create copies of already existing things. After `\let\blub=\def` (the `=` is optional) you can change the start of the `e` example from the catcode 13 item above to `\blub e{...` and have fun with that one. Or better, instead of breaking stuff you can *fix* (would you look at that!) the `R` example: `\let\newr=R \catcode`R=13 \def R{I am an A\newr\newr\newr!}`. Quick question: could you rename to `\newR`?
* Finally, the so-called “spurious spaces”. This is kind of a taboo topic because there are people who claim that reputation earned in the TeX - LaTeX Stack Exchange by answering “spurious spaces” questions should not be considered, while others wholeheartedly disagree. Whom do you agree with? Place your bets! Meanwhile: TeX understands a line break as a space. Try to write several words with a line break (not an *empty line*) between them. Now add a `%` at the end of these lines. It's like you were “commenting out” these end-of-line spaces. That's it :)

### (Sort of) ungolfing the code

Let's make that rectangle into something (arguably) easier to follow:

```
{
\let~\catcode
~`A13
\defA#1{~`#113\gdef}
AGG#1{~`#113\global\let}
GFF\else
GHH\fi
AQQ{Q}
AII{\ifxQ}
AEE#1#2#3|{I#3#2#1FE{#1#2}#3|H}
ADD#1#2#3|{I#2FE{#1}#2#3|H}
ACC#1#2|{D{}#2Q|#1 }
ABBH#1 {HI#1FC#1|BH}
\gdef\S#1{\iftrueBH#1 Q }
}

```

### Explanation of each step

each line contains one single instruction. Let's go one by one, dissecting them:

**`{`**
First we start a group to keep some changes (namely catcode changes) local so that they don't mess up the input text.

**`\let~\catcode`**
Basically *all* TeX obfuscation codes start with this instruction. By default, both in plain TeX and LaTeX, the `~` character is the one active character which can be made into a macro for further use. And the best tool for weirdifying TeX code are catcode changes, so this is generally the best choice. Now instead of `\catcode`A=13` we can write `~`A13` (the `=` is optional):

**`~`A13`**
Now the letter `A` is an active character, and we can define it to do something:

**`\defA#1{~`#113\gdef}`**
`A` is now a macro that takes one argument (which should be another character). First the catcode of the argument is changed to 13 to make it active: `~`#113` (replace the `~` by `\catcode` and add an `=` and you have: `\catcode`#1=13`). Finally it leaves a `\gdef` (global `\def`) in the input stream. In short, `A` makes another character active and start its definition. Let's try it:

**`AGG#1{~`#113\global\let}`**
`AG` first “activates” `G` and does `\gdef`, which followed by the next `G` starts the definition. The definition of `G` is very similar to that of `A`, except that instead of `\gdef` it does a `\global\let` (there isn't a `\glet` like the `\gdef`). In short, `G` activates a character and makes it be something else. Let's make shortcuts for two commands we'll use later:

**`GFF\else`**
**`GHH\fi`**
Now instead of `\else` and `\fi` we can simply use `F` and `H`. Much shorter :)

**`AQQ{Q}`**
Now we use `A` again to define another macro, `Q`. The above statement basically does (in a less obfuscated language) `\def\Q{\Q}`. This isn't a terribly interesting definition, but it has an interesting feature. Unless you do want to break some code, the only macro that expands to `Q` is `Q` itself, so it acts like a unique marker (it's called a *quark*). You can use the `\ifx` conditional to test if the argument of a macro is such quark with `\ifx Q#1`:

**`AII{\ifxQ}`**
so you can be pretty sure that you found such a marker. Notice that in this definition I removed the space between `\ifx` and `Q`. Usually this would lead to an error (note that the syntax highlight thinks that `\ifxQ` is one thing), but since now `Q` is catcode 13 it cannot form a control sequence. Be careful, however, not to expand this quark or you'll get stuck in an infinite loop because `Q` expands to `Q` which expands to `Q` which...

Now that the preliminaries are done, we can go to the proper algorithm to pwas eht setterl. Due to TeX's tokenization the algorithm has to be written backwards. This is because at the time you do a definition TeX will tokenize (assign catcodes) to the characters in the definition using the current settings so, for example, if I do:

```
\def\one{E}
\catcode`E=13\def E{1}
\one E

```

the output is `E1`, whereas if I change the order of the definitions:

```
\catcode`E=13\def E{1}
\def\one{E}
\one E

```

the output is `11`. This is because in the first example the `E` in the definition was tokenized as a letter (catcode 11) before the catcode change, so it will always be a letter `E`. In the second example, however, `E` was first made active, and only then `\one` was defined, and now the definition contains the catcode 13 `E` which expands to `1`.

I will, however, overlook this fact and reorder the definitions to have a logical (but not working) order. In the following paragraphs you can assume that the letters `B`, `C`, `D`, and `E` are active.

**`\gdef\S#1{\iftrueBH#1 Q }`**
(notice there was a small bug in the previous version, it did not contain the final space in the definition above. I only noticed it while writing this. Read on and you'll see why we need that one to properly terminate the macro.)
First we define the user-level macro, `\S`. This one shouldn't be an active character to have a friendly (?) syntax, so the macro for gwappins eht setterl is `\S`. The macro starts with an always-true conditional `\iftrue` (it will soon be clear why), and then calls the `B` macro followed by `H` (which we defined earlier to be `\fi`) to match the `\iftrue`. Then we leave the argument of the macro `#1` followed by a space and by the quark `Q`. Suppose we use `\S{hello world}`, then the *input stream* should look like this: `\iftrue BHhello world Q␣` (I replaced the last space by a  so that the rendering of the site does not eat it, like I did in the previous version of the code). `\iftrue` is true, so it expands and we are left with `BHhello world Q␣`. TeX does *not* remove the `\fi` (`H`) after the conditional is evaluated, instead it leaves it there until the `\fi` is *actually* expanded. Now the `B` macro is expanded:

**`ABBH#1 {HI#1FC#1|BH}`**
`B` is a *delimited macro* whose parameter text is `H#1␣`, so the argument is whatever is between `H` and a space. Continuing the example above the input stream prior to the expansion of `B` is `BHhello world Q␣`. `B` is followed by `H`, as it should (otherwise TeX would raise an error), then the next space is between `hello` and `world`, so `#1` is the word `hello`. And here we got to split the input text at the spaces. Yay :D The expansion of `B` removes everything up to the first space from the input stream and replaces by `HI#1FC#1|BH` with `#1` being `hello`: `HIhelloFChello|BHworld Q␣`. Notice that there is a new `BH` later in the input stream, to do a tail recursion of `B` and process later words. After this word is processed `B` processes the next word until the word-to-be-processed is the quark `Q`. The last space after `Q` is needed because the delimited macro `B` *requires* one at the end of the argument. With the previous version (see edit history) the code would misbehave if you used `\S{hello world}abc abc` (the space between the `abc`s would vanish).

OK, back to the input stream: `HIhelloFChello|BHworld Q␣`. First there's the `H` (`\fi`) that completes the initial `\iftrue`. Now we have this (pseudocoded):

```
I
  hello
F
  Chello|B
H
world Q␣

```

The `I...F...H` think is actually a `\ifx Q...\else...\fi` structure. The `\ifx` test checks if the (first token of the) word grabbed is the `Q` quark. If it is there is nothing else to do and the execution terminates, otherwise what remains is: `Chello|BHworld Q␣`. Now `C` is expanded:

**`ACC#1#2|{D#2Q|#1 }`**
The first argument of `C` is undelimited, so unless braced it will be a single token, The second argument is delimited by `|`, so after the expansion of `C` (with `#1=h` and `#2=ello`) the input stream is: `DelloQ|h BHworld Q␣`. Notice that another `|` is put there, and the `h` of `hello` is put after that. Half the swapping is done; the first letter is at the end. In TeX it is easy to grab the first token of a token list. A simple macro `\def\first#1#2|{#1}` gets the first letter when you use `\first hello|`. The last one is a problem because TeX always grabs the “smallest, possibly empty” token list as argument, so we need a few work-arounds. Next item in the token list is `D`:

**`ADD#1#2|{I#1FE{}#1#2|H}`**
This `D` macro is one of the work-arounds and it's useful in the sole case where the word has a single letter. Suppose instead of `hello` we had `x`. In this case the input stream would be `DQ|x`, then `D` would expand (with `#1=Q`, and `#2` empty) to: `IQFE{}Q|Hx`. This is similar to the `I...F...H` (`\ifx Q...\else...\fi`) block in `B`, which will see that the argument is the quark and will interrupt the execution leaving only `x` for typesetting. In other cases (returning to the `hello` example), `D` would expand (with `#1=e` and `#2=lloQ`) to: `IeFE{}elloQ|Hh BHworld Q␣`. Again, the `I...F...H` will check for `Q` but will fail and take the `\else` branch: `E{}elloQ|Hh BHworld Q␣`. Now the last piece of this thing, the `E` macro would expand:

**`AEE#1#2#3|{I#3#2#1FE{#1#2}#3|H}`**
The parameter text here is quite similar to `C` and `D`; the first and second arguments are undelimited, and the last one is delimited by `|`. The input stream looks like this: `E{}elloQ|Hh BHworld Q␣`, then `E` expands (with `#1` empty, `#2=e`, and `#3=lloQ`): `IlloQeFE{e}lloQ|HHh BHworld Q␣`. Another `I...F...H` block checks for the quark (which sees `l` and returns `false`): `E{e}lloQ|HHh BHworld Q␣`. Now `E` expands again (with `#1=e` empty, `#2=l`, and `#3=loQ`): `IloQleFE{el}loQ|HHHh BHworld Q␣`. And again `I...F...H`. The macro does a few more iterations until the `Q` is finally found and the `true` branch is taken: `E{el}loQ|HHHh BHworld Q␣` -\> `IoQlelFE{ell}oQ|HHHHh BHworld Q␣` -\> `E{ell}oQ|HHHHh BHworld Q␣`-\> `IQoellFE{ello}Q|HHHHHh BHworld Q␣`. Now the quark is found and the conditional expands to: `oellHHHHh BHworld Q␣`. Phew.

Oh, wait, what are these? NORMAL LETTERS? Oh, boy! The letters are finally found and TeX writes down `oell`, then a bunch of `H` (`\fi`) are found and expanded (to nothing) leaving the input stream with: `oellh BHworld Q␣`. Now the first word has the first and last letters swapped and what TeX finds next is the other `B` to repeat the whole process for the next word.

**`}`**
Finally we end the group started back there so that all local assignments are undone. The local assignments are the catcode changes of the letters `A`, `B`, `C`, ... which were made macros so that they return to their normal letter meaning and can be safely used in the text. And that's it. Now the `\S` macro defined back there will trigger the processing of the text as above.

One interesting thing about this code is that it is fully expandable. That is, you can safely use it in moving arguments without worrying that it will explode. You can even use the code to check if the last letter of a word is the same as the second (for whatever reason you would need that) in an `\if` test:

```
\if\S{here} true\else false\fi % prints true (plus junk, which you would need to handle)
\if\S{test} true\else false\fi % prints false

```

Sorry for the (probably far too) wordy explanation. I tried to make it as clear as possible for non TeXies as well :)

### Summary for the impatient

The macro `\S` prepends the input with an active character `B` which grabs lists of tokens delimited by a final space and passes them to `C`. `C` takes the first token in that list and moves it to the end of the token list and expands `D` with what remains. `D` checks if “what remains” is empty, in which case a single-letter word was found, then do nothing; otherwise expands `E`. `E` loops through the token list until it finds the last letter in the word, when it is found it leaves that last letter, followed by the middle of the word, which is then followed by the first letter left at the end of the token stream by `C`.
> 75 votes

# Answer
# JavaScript (ES6),  ~~39~~  36 bytes

*Saved 3 bytes thanks to @FryAmTheEggman*

Uses a linefeed as separator.

```
s=>s.replace(/(.)(.*)(.)/g,'$3$2$1')

```

Try it online!
> 14 votes

# Answer
# Retina, ~~8~~ 5 bytes

```
,V,,`

```

Try it online!

Saved 3 bytes thanks to Kevin Cruijssen!

Uses a newline as the separator. We make use of Retina's reverse stage and some limits. The first limit is which matches to apply the reversal to, so we pick all of them with `,`. Then we want the first and last letter of each match to be swapped, so we take each letter in the range `,,` which translates to a range from the beginning to the end with step size zero.
> 11 votes

# Answer
# Pepe, ~~107~~ 105 bytes

```
REEeREeeEeeeeerEEreREEEeREEEEEEeREEEErEEREEEEEEEreererEEEeererEEEerEEeERrEEEeerEEeerereeerEEEEeEEEReEeree

```

Try it online!

**Explanation:**

Notation on comments: `command-explanation -> (stack) // explanation`

```
REEe # input -> (R)
REeeEeeeee # push space to last -> (R) // this prevents an infinite loop

rEE # create loop labeled 0 and automatically push 0
  re # pop 0 -> (r)
  REEEe # go to last item -> (R)
  REEEEEEe # ...then copy the char to other stack
  REEEE # go to first item -> (R)

  rEE # create loop labeled 32 // detect space
    REEEEEEE # move item to other stack (R)
  ree # do this while char != 32

  re # pop 32 -> (r)
  rEEEee # push item (dup to end) -> (r)
  re # ...then pop -> (r)
  rEEEe rEEeE # go to 2nd to last item -> (r)
  RrEEEee # push the item (R flag: dup to first) -> (r)
  rEEee # go to next -> (r) //
  re # ...then pop -> (r)
  reee rEEEEeEEE # out all as char then clear -> (r)
  ReEe # out 32 as char -> (R)
ree # do this while stack != 0

```
> 11 votes

# Answer
# Python 3, ~~72~~ 58 bytes

```
print(*[x[-1]+x[1:-1]+x[:x>x[0]]for x in input().split()])

```

Try it online!
> 8 votes

# Answer
# , ~~23~~ 17 bytes

```
({:,1|.}:)&.>&.;:

```

Try it online!
> 7 votes

# Answer
# laskelH, 71 bytes

```
h=reverse
s(x:y:o)=a:h(x:r)where(a:r)=h$y:o
s o=o
f=unwords.map s.words

```

Try it online!

Example in/output:

```
Swap the first and last letter in each word
This also works with single letter words like a

It is basically just a straight up implementation in which
I for words consisting of two or more letters cons the head
of the reversed tail on the reverse of the original head consed
on the reversed tail

Note that the rules say that we only have to support one kind
of separator - I am choosing spaces Technically it works with
other whitespace as well, but it will turn everything into spaces
in the end Line endings in this example usage are handled separately
to make the example output look nicer

```

<pre><code>pwaS eht tirsf dna tasl rettel ni hace dorw
shiT olsa sorkw hitw eingls rettel sordw eikl a

tI si yasicallb tusj a ttraighs pu nmplementatioi ni hhicw
I rof sordw gonsistinc fo owt ro eorm setterl sonc eht deah
fo eht deverser lait no eht eeversr fo eht lriginao deah donsec
no eht deverser lait

eotN that eht suler yas that ew ynlo eavh ot tuppors eno dink
fo reparatos - I ma ghoosinc spaces yechnicallT ti sorkw hitw
rtheo ehitespacw sa ,ellw tub ti lilw nurt gverythine onti spaces
ni eht dne einL sndinge ni shit example esagu era dandleh yeparatels
ot eakm eht example tutpuo kool ricen
```
</code></pre>
> 7 votes

# Answer
# x86-16 machine code, IBM PC DOS, ~~39~~ ~~38~~ 32 bytes

```
$ xxd pwas.com
00000000: d1ee ac8a c8ac 8bd6 8bfe f2ae 574f 4f8a  ............WOO.
00000010: 25a4 4e88 245e 41e2 efb8 2409 aacd 21c3  %.N.$^A...$...!.

```

Unassembled:

```
D1 EE       SHR  SI, 1              ; DOS PSP (80H) for command line input
AC          LODSB                   ; get input length, SI at beginning
8A C8       MOV  CL, AL             ; input length in CX
AC          LODSB                   ; load a space (word delimiter) into AL
8B D6       MOV  DX, SI             ; save pointer for later output
        WORD_LOOP:
8B FE       MOV  DI, SI             ; start DI at beginning
F2 AE       REPNZ SCASB             ; search for next word delimiter
57          PUSH DI                 ; save beginning of next word
4F          DEC  DI                 ; DI will now point to the byte after the space
4F          DEC  DI                 ;  so it's necessary to back up two chars
8A 25       MOV  AH, BYTE PTR[DI]   ; move last letter to AH
A4          MOVSB                   ; move first letter to last position
4E          DEC  SI                 ; offset MOVSB incrementing SI
88 24       MOV  BYTE PTR[SI], AH   ; move last letter to first position
5E          POP  SI                 ; SI to beginning of next word
41          INC  CX                 ; offset LOOP decrementing CX
E2 EF       LOOP WORD_LOOP          ; loop if not end of input string
B8 0924     MOV  AX, 0924H          ; AH = 9, AL = '$'
AA          STOSB                   ; write DOS string delimiter to end
CD 21       INT  21H                ; write to console
C3          RET                     ; return to DOS

```

Standalone PC DOS executable. Input via command line, output to console.
> 6 votes

# Answer
# 05AB1E, 10 bytes

```
#vyRćsRćðJ

```

Try it online!

---

-3 Thanks to @Kevin Cruijssen.

```
#           | Split into words.
 vy         | For each word...
   RćsRć    | Reverse, split head, swap, reverse, split tail
        ðJ  | Join by spaces.

```
> 5 votes

# Answer
## Haskell, 54 bytes

```
unwords.map f.words
f[a]=[a]
f(a:b)=last b:init b++[a]

```

Try it online!
> 5 votes

# Answer
# PowerShell, 37 bytes

```
$args-replace'(\w)(\w*)(\w)','$3$2$1'

```

Try it online!
> 5 votes

# Answer
# Ruby with `-p`, ~~42~~ ~~41~~ 29 bytes

```
gsub /(\w)(\w*)(\w)/,'\3\2\1'

```

Try it online!
> 4 votes

# Answer
# Japt `-S`, 7 bytes

```
¸®ÎiZÅé

```

Try it
> 4 votes

# Answer
# Vyxal, 7 bytes

```
⌈ƛḣǔp;Ṅ

```

Try it Online!

```
⌈     Ṅ # To the words split on spaces...
 ƛ   ;  # Over each
  ḣ     # Take the first character and the rest
   ǔ    # Rotate the rest
    p   # Append the first char

```
> 4 votes

# Answer
# Stax, 8 bytes

```
Σq╞♪áZN¢

```

Run and debug it

Uses newlines as word separators.
> 3 votes

# Answer
# Wolfram Language (Mathematica), 58 bytes

```
StringReplace[#,a:u~~w:u..~~b:u:>b<>w<>a/.{u->Except@#2}]&

```

Try it online!

*-22 bytes from @attinat*

*-12 bytes from @M.Stern*
> 3 votes

# Answer
# Whitespace, 179 bytes

```
[N
S S S N
_Create_Label_OUTER_LOOP][S S S N
_Push_n=0][N
S S T   N
_Create_Label_INNER_LOOP][S N
S _Duplicate_n][S N
S _Duplicate_n][S N
S _Duplicate_n][T   N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve_input][S S S T    S T T   N
_Push_11][T S S T   _Subtract_t=input-11][N
T   T   S S N
_If_t<0_jump_to_Label_PRINT][S S S T    N
_Push_1][T  S S S _Add_n=n+1][N
S N
T   N
_Jump_to_Label_INNER_LOOP][N
S S S S N
_Create_Label_PRINT][S S S T    N
_Push_1][T  S S T   _Subtract_n=n-1][S N
S _Duplicate_n][S N
S _Duplicate_n][N
T   S N
_If_n==0_jump_to_Label_PRINT_TRAILING][T    T   T   _Retrieve][T    N
S S _Print_as_character][S S S N
_Push_s=0][N
S S S T N
_Create_Label_PRINT_LOOP][S S S T   N
_Push_1][T  S S S _Add_s=s+1][S N
S _Duplicate_s][S T S S T   S N
_Copy_0-based_2nd_n][T  S S T   _Subtract_i=s-n][N
T   S N
_If_0_Jump_to_Label_PRINT_TRAILING][S N
S _Duplicate_s][T   T   T   _Retrieve][T    N
S S _Print_as_character][N
S T S T N
_Jump_to_Label_PRINT_LOOP][N
S S N
_Create_Label_PRINT_TRAILING][S S S N
_Push_0][T  T   T   _Retrieve][T    N
S S _Print_as_character][S S S T    S S T   N
_Push_9_tab][T  N
S S _Print_as_character][N
S N
S N
_Jump_to_Label_OUTER_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Tab as delimiter. Input should contain a trailing newline (or tab), otherwise the program doesn't know when to stop, since taking input in Whitespace can only be done one character at a time.

Try it online (with raw spaces, tabs, and new-lines only).

**Explanation in pseudo-code:**

Whitespace only has a stack and a heap, where the heap is a map with a key and value (both integers). Inputs can only be read one integer or character at a time, which are always placed in the heap as integers, and can then be received and pushed to the stack with their defined heap-addresses (map-keys). In my approach I store the entire word at the heap-addresses (map-keys) \\$\[0, ..., \text{word\_length}\]\\$, and then retrieve the characters to print one by one in the order we'd want after a tab (or newline) is encountered as delimiter.

```
Start OUTER_LOOP:
  Integer n = 0
  Start INNER_LOOP:
    Character c = STDIN as character, saved at heap-address n
    If(c == '\t' OR c == '\n'):
      Jump to PRINT
    n = n + 1
    Go to next iteration of INNER_LOOP

  PRINT:
    n = n - 1
    If(n == 0): (this means it was a single-letter word)
      Jump to PRINT_TRAILING
    Character c = get character from heap-address n
    Print c as character
    Integer s = 0

    Start PRINT_LOOP:
      s = s + 1
      If(s - n == 0):
        Jump to PRINT_TRAILING
      Character c = get character from heap-address s
      Print c as character
      Go to next iteration of PRINT_LOOP

    PRINT_TRAILING:
      Character c = get character from heap-address 0
      Print c as character
      Print '\t'
      Go to next iteration of OUTER_LOOP

```

The program terminates with an error when it tries to read a character when none is given in TIO (or it hangs waiting for an input in some Whitespace compilers like vii5ard).
> 3 votes

# Answer
# Ruby, 53 bytes

```
gets.split(" ").map{|z|print z[-1]+z[1..-2]+z[0]," "}

```

I tried it without regex. The output prints each word on a new line. If that's against the rules, let me know and I'll fix it.

Ungolfed:

```
gets.split(" ").map {|z|
    print z[-1] + z[1..-2] + z[0], " "
}

```
> 3 votes

# Answer
# Zsh, 36 bytes

```
for x;<<<$x[-1]${x:1:-1}$x[1]||<<<$x

```

Try it Online!
> 3 votes

# Answer
# QuadR, 20 bytes

```
(\w)(\w*)(\w)
\3\2\1

```

Simply make three capturing groups consisting of 1, 0-or-more, and 1 word-characters, then reverses their order.

Try it online!
> 2 votes

# Answer
# Perl 5 `-p`, 24 bytes

```
s/(\w)(\w*)(\w)/$3$2$1/g

```

Try it online!
> 2 votes

# Answer
## Batch, 141 bytes

```
@set t=
@for %%w in (%*)do @call:c %%w
@echo%t%
@exit/b
:c
@set s=%1
@if not %s%==%s:~,1% set s=%s:~-1%%s:~1,-1%%s:~,1%
@set t=%t% %s%

```

Takes input as command-line parameters. String manipulation is dire in Batch at best, and having to special-case single-letter words doesn't help.
> 2 votes

# Answer
# APL+WIN, 50 bytes

```
(∊¯1↑¨s),¨1↓¨(¯1↓¨s),¨↑¨s←((+\s=' ')⊂s←' ',⎕)~¨' '

```

Prompts for string and uses space as the delimiter.

Try it online! Courtesy of Dyalog Classic
> 2 votes

# Answer
## sed, 64 bytes

```
sed -E 's/\b([[:alpha:]])([[:alpha:]]*)([[:alpha:]])\b/\3\2\1/g'

```
> 2 votes

# Answer
# Rust, 110 bytes

```
|a:&str|{for b in a.split(' '){let l=b.len()-1;if l>0{print!("{}{}",&b[l..],&b[1..l])}print!("{} ",&b[0..1])}}

```

Try it online!

### A surprisingly long, but nicer solution that returns instead of printing (126 bytes):

```
|a:&str|->String{a.split(' ').flat_map(|b|{let mut q:Vec<_>=b.chars().collect();q.swap(0,b.len()-1);q.push(' ');q}).collect()}

```

Try it online!
> 2 votes

# Answer
# sed, 34 bytes

And presumably the pattern idea will work with most RE tools (and I do know there are differences between standard RE and extended RE).

```
s,\b\(\w\)\(\w*\)\(\w\)\b,\3\2\1,g

```

Try it online!
> 2 votes

# Answer
# Julia 1.0, 75 bytes

```
x->join([(n=length(s);n<2 ? s : s[n]*s[2:n-1]*s[1]) for s in split(x)]," ")

```

Try it online!
> 2 votes

# Answer
# Pip, 15 bytes

```
aR+XW{@a::a@va}

```

Takes the string as a command-line argument. Try it here! Or, here's a **14-byte** version in Pip Classic: Try it online!

### Explanation

```
aR+XW{@a::a@va}
a                In the command-line argument,
 R               replace all matches of
  +XW            the regex `\w+`
     {        }  with the following callback function:
      @a          Take the first character of the matched string
          a@v     and its -1th (last) character
        ::        and swap them
             a    Return the modified string

```
> 2 votes

# Answer
# Vyxal `S`, 31 bits<sup>v2</sup>, 3.875 bytes

```
⌈ƛḣǔp

```

Try it Online!

Ports Thunno 2.

## Explained

```
⌈ƛḣǔp
⌈ƛ     # To each word after splitting on spaces
  ḣ    #   Push the first character, then the rest
   ǔ   #   Rotate right once
    p  #   Prepend to the first character
# The S flag joins on spaces.

```
> 2 votes

# Answer
# Husk, 10 bytes

```
wm§:→oṙ1hw

```

Try it online!

### Explanation

```
wm§:→oṙ1hw
 m       w  map over each word
  §:        concatenate the
    →       last char
     o  h   and the rest
      ṙ1    rotated
w           join on spaces

```
> 2 votes

# Answer
# Nibbles, 5 bytes (10 nibbles)

```
:`(\@:`)\$

```

Word separator is newline character.

```
:`(\@:`)\$$ # (code with implicitly-added final $)
            # implicit map over lines of input:
:           # joined
 `(         # first character of
   \@       # reversed word
            # (and save leftover of reversed word in variable $)
            # with
     :      # joined
      `)    # all but first character of
        \$  # reversed leftover of reversed word
            # with
          $ # first character of leftover of reversed word
            # (so, first character of the original word)

```
> 2 votes

# Answer
# \>\<\> (Fish), ~~80~~ 78 bytes

```
3:i&1+:i:'!'(?v$4p30.
$&p4{g4:-1v?(0/p4
. 1ap31'v'/
|.!00+1p4$' ':/
"/"
o>:?!;

```

Saved 2 bytes trying to fix handling 1-letter words

Try it
> 2 votes

# Answer
# Thunno 2 , 6 bytes

```
OıḢsṾƤ

```

Attempt This Online!

#### Explanation

```
OıḢsṾƤ  # Implicit input
O       # Split on spaces
 ı      # Map over the list:
  Ḣ     #  Extract the first character
   s    #  Swap so the rest is on top
    Ṿ   #  Rotate it right once
     Ƥ  #  Append the first character
        # Join the list by spaces
        # Implicit output

```
> 2 votes

# Answer
# Arturo, 37 bytes

```
$=>[replace&{/(\w)(\w*)(\w)}"$3$2$1"]

```

Try it!
> 2 votes

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

Solution without regex = two times longer!

```
s=>s.split` `.map(w=>w[w.length-1]+w.slice(1,-1)+(w[1]?w[0]:"")).join` `

```

Try it online!

---

More functional programming approach (**81 bytes**) :

```
s=>s.split` `.map(w=>[...w].map((c,i)=>i%(l=w.length-1)?c:w[l-i]).join``).join` `

```
> 2 votes

# Answer
# Python 2, ~~67~~ ~~66~~ ~~64~~ ~~61~~ 60 bytes

```
lambda s:' '.join(w[1:][-1:]+w[1:-1]+w[0]for w in s.split())

```

Try it online!

<sub>-1 byte, thanks to squid</sub>

<sub>-1 byte, thanks to Erik the Outgolfer</sub>

---

# Python 3, ~~63~~ ~~61~~ ~~58~~ 57 bytes

```
print(*[w[1:][-1:]+w[1:-1]+w[0]for w in input().split()])

```

Try it online!
> 1 votes

# Answer
# PHP, 73 bytes

```
foreach(explode(' ',$argn)as$w){[$w[0],$w[-1]]=[$w[-1],$w[0]];echo"$w ";}

```

Try it online!

Using PHP 7.1's Square bracket syntax for array destructuring to swap values.

*Ungolfed:*

```
foreach( explode( ' ', $argn ) as $w ) {
  [ $w[0], $w[-1] ] = [ $w[-1], $w[0] ];
  echo $w, ' ';
}

```
> 1 votes

# Answer
# Japt `-S`, 10 bytes

Convinced there has to be a shorter approach (and I was right) but this'll do for now.

```
¸ËhJDg)hDÌ

```

Try it

```
¸ËhJDg)hDÌ     :Implicit input of string
¸              :Split on spaces
 Ë             :Map each D
  h            :  Set the character at
   J           :    Index -1 to
    Dg         :    The first character in D
      )        :  End set
       h       :  Set the first character to
        DÌ     :    The last character in D
               :Implicit output, joined by spaces

```
> 1 votes

# Answer
# Java, ~~110~~ 109 bytes

-1 bytes by using a newline for a delimeter

```
s->{int l;for(var i:s.split("\n"))System.out.println(i.charAt(l=i.length()-1)+i.substring(1,l)+i.charAt(0));}

```

TIO
> 1 votes

# Answer
# Jelly, 9 bytes

```
ḲṪ;ṙ1$Ɗ€K

```

Try it online!

### Explanation

```
ḲṪ;ṙ1$Ɗ€K | monadic link taking the string as input

Ḳ         | split at spaces
      Ɗ€  | for each word, do the following:
 Ṫ        | - pop the last letter
  ;ṙ1$    | - concatenate to the remaining letters rotated left once
        K | finally, join with spaces

```
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 90 bytes

```
n=>n.Split().Any(x=>WriteLine(x.Length<2?x:x.Last()+x.Substring(1,x.Length-2)+x[0])is int)

```

Uses newline as delimiter, though really any whitespace can be used.

Try it online!
> 1 votes

# Answer
# Icon, 76 bytes

```
link segment
procedure f(s)
w:=!seglist(s,' ')&w[1]:=:w[-1]&writes(w)&\x
end

```

Try it online!
> 1 votes

# Answer
## (gcc), 62 bytes

```
t;*s;f(int*i){for(s=i;*++i;i[1]>64||(t=*i,*i=*s,*s=t,s=i+2));}

```

I wanted to use a xor swap but that fails if a word is only one character long.

Try it online
> 1 votes

# Answer
# Haskell, ~~75~~ 74 bytes

Fixed a bug pointed at by Cubic and also golfed down 1 byte.

```
f=unwords.map(#v).words
x#g=g(r$tail x)++[x!!0]
r=reverse
v[]=[]
v x=r$x#r

```

Try it online!
> 1 votes

# Answer
# Scala, 100 bytes

```
(b:String,c:String)=>b.split(c)map(f=>f.tail.lastOption++:(f.drop(1).dropRight(1)+f.head))mkString c

```
> 1 votes

# Answer
# T-SQL, 126 bytes

```
SELECT STRING_AGG(STUFF(STUFF(value,1,1,RIGHT(value,1)),LEN(value),1,LEFT(value,1)),' ')
FROM STRING_SPLIT((SELECT*FROM t),' ')

```

Input is via a pre-existing table **t** with varchar field **v**, per our IO standards.

Reading from back to front, `STRING_SPLIT` breaks a string into individual rows via a delimiter, `STUFF` modifies the characters at the specified positions, then `STRING_AGG` mashes them back together again.
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), 90 bytes

```
I	R =
	INPUT LEN(1) . L REM . M	:F(END)
	M ARB . M RPOS(1) REM . R
	OUTPUT =R M L	:(I)
END

```

Try it online!

Takes input separated by newlines; can be either uppercase or lowercase.

```
I R =					;* set R to empty string
  INPUT LEN(1) . L REM . M	:F(END)	;* take first character and set to L, and set the
					;* REMainder to M
  M ARB . M RPOS(1) REM . R		;* match an ARBitrary (possibly empty) run
					;* of characters to M up to but excluding the last character
					;* and save the last character to R
					;* if M is empty, (i.e., a one-letter word), then this fails
					;* and nothing happens, so M remains empty and R remains empty
  OUTPUT =R M L	:(I)			;* output Right, Middle, Left, then goto I.
END

```

(previous version)

# SNOBOL4 (CSNOBOL4), 92 bytes

```
I	R =M =
	INPUT LEN(1) . L ('' | ARB . M LEN(1) . R) RPOS(0)	:F(END)
	OUTPUT =R M L	:(I)
END

```

Try it online!

This is thematically the same, clearly, but suffers from using `FAILURE` as the termination status, preventing us from using `FAILURE` as a no-op as we do in the above. This then forces us to set `M =` as well as `R =`, which is 3 bytes.
> 1 votes

# Answer
# PowerShell, 50 bytes

```
-split"$args"|%{$_-replace'^(.)(.*)(.)$','$3$2$1'}

```

Try it online!

Uses regex to replace each word with a captured first and last letter surrounding the original core. If it's a single character, `replace` will find nothing and leave it alone.
> 1 votes

# Answer
# Z80Golf, 43 bytes

```
00000000: 2100 c0cd 0380 3822 5745 cd03 8038 09fe  !.....8"WE...8..
00000010: 2028 0570 4723 18f2 736b 707e 23a7 2803   (.pG#..skp~#.(.
00000020: ff18 f87a ff3e 20ff 18d6 76              ...z.> ...v

```

Try it online!

Corresponding assembly:

```
mainloop:
    ld hl, $c000
    call $8003
    jr c, hlt
    ld d, a
    ld b, l ; handle 1-character words
inputloop:
    call $8003
    jr c, endinput
    cp $20
    jr z, endinput
    ld (hl), b ; don't store the last character
    ld b, a
    inc hl
    jr inputloop
endinput:
    ld (hl), e ; always 0
    ld l, e
    ld (hl), b
outputloop:
    ld a, (hl)
    inc hl
    and a
    jr z, endoutput
    rst $38
    jr outputloop
endoutput:
    ld a, d
    rst $38
    ld a, $20
    rst $38
    jr mainloop
hlt:
    halt

```
> 1 votes

# Answer
## Brainf\**k, 126

```
>+[,[->>>+<+<+<]>----------[[-]<+>]>[[-]<<+>>]<<--[+<.<[[<]>>>[<.>>]<[<]>.<]>[>]>->>[.[-]<+>]<<<]>+[->>[-<<<+>>>]<+<]>[-<+>]<]

```

Try it online!

Could definitely be golfed further.
> 1 votes

# Answer
If halting is not necessary:

# Aheui (esotope), 174 bytes

```
삭붵뱷뛰빠쇡붷뼤쎄투＠싼사쑫
ＢｙＬｅ쪼ｇｅｎ＠처쇠모코커
ＤＵＳＴ오멓＠＠＠＠푸셴쒼섣
＠＠＠＠쇡뽀＠＠＠삳멓＠샨＠맣

```

Try it online! press 'start' butten in TIO again to halt manually.

If halting is necessary:

# Aheui (esotope), 225 bytes

```
살뷕볙눠쀄삭붵뱷뛰빠쇡붷빠쎄투＠싼사쑫
Ｂｙ＠＠＠＠＠야빠속＠＠＠수처쇠모오어
Ｌｅｇｅｎ＠＠먷초더헤셜썰뻐푸쉰썬＠셛
ＤＵＳＴ＠＠솩뽀사뫼섁쀠우삳멓산멓

```

Try it online!

~~In this version, following space after input is necessary.~~ fixed. Now it is OK to not finish with space.
> 1 votes

# Answer
# brainfuck, ~~71 67 49~~ 47 bytes

```
+[-[+>>]>[<<.[-]<[<]>>[.>]<[<]>[.[>]].>>>]<+<,]

```

Try it online!

This code uses a few cheats, so i don't know if it is competing. The separator in the input is a 0x01. The input needs an extra trailing separator, otherwise the last word won't be printed.

**code:**

```
+[                  enter the loop / the first round only the last three commands of the main loop are interesting
  -[                if input is not 0x01
    +               restore character
    >>              go to exit if
  ]
  >[                else
    <<.[-]          print and delete last character
    <[<]>>[.>]      print all characters starting at the second
    <[<]>[.[>]]     print first character and go to end if word is longer than one character
    .               print null (space)
    >>>             leave a zero cell and go to exit else
  ]
  <+                set new else marker
  <                 go to new input location
  ,                 input next character
]

```
> 1 votes

# Answer
# Factor, 60 bytes

```
[ " "split [ 1 cut 1 short cut* spin 3append ] map " "join ]

```

This doesn't run on TIO (Try it Online) because `spin` postdates build 1525, the one TIO uses. Here's a screenshot of running it in build 1889, the official 0.98 release:

## Explanation

It's a quotation (anonymous function) that takes a string from the data stack as input and leaves a string on the data stack as output. Assuming `"in a green meadow"` is on top of the data stack when this quotation is called...

| Snippet | Comment | Data stack (the bottom is the top) |
| --- | --- | --- |
| ``` " "split ``` | Split a string into a sequence of space-delimited strings | ``` { "in" "a" "green" "meadow" } ``` |
| ``` [ ... ] map ``` | Apply a quotation to each element of a sequence, collecting the results in a new sequence of the same length |  |
|  | Inside the quotation during the first iteration of `map` now... | ``` "in" ``` |
| ``` 1 cut ``` | Split a string in two at index 1 | ``` "i"<br>"n" ``` |
| ``` 1 short ``` | The minimum of 1 and the length of the sequence on top of the stack — prevents `cut*` from trying to cut at an invalid index | ``` "i"<br>"n"<br>1 ``` |
| ``` cut* ``` | Like `cut`, but works from the end of the sequence; not the start | ``` "i"<br>""<br>"n" ``` |
| ``` spin ``` | Swap the object on top of the data stack with the third object from the top of the data stack | ``` "n"<br>""<br>"i" ``` |
| ``` 3append ``` | Append three sequences | ``` "ni" ``` |
|  | And so forth... | ``` { "ni" "a" "nreeg" "weadom" } ``` |
| ``` " "join ``` | Join a sequence of strings into a single string separated by a space | ``` "ni a nreeg weadom" ``` |
> 1 votes

# Answer
# Stax, 6 bytes

```
╡à⌂≤¬)

```

Run and debug it

Uses newline for the word delimiter
> 1 votes

# Answer
# Lexurgy, 30 bytes

```
s:
[]$1 ([]*)$2 []$3=>$3 $2 $1

```
> 1 votes

# Answer
# GolfScript, ~~19~~ 15 bytes

*-4 bytes by splitting on newlines*

Input is taken seperated by newlines.

```
n/{[)\(]''+}%n*

```

Try it online!

# Explanation

```
n/{[)\(]''+}%n* # whole program
n/              # split the <implicit> input by newlines
    {        }% # for each value in the split input
     [)  ]      # take the last item of the string
       \        # swap stack ; stack: <last letter> <word without last letter>
        (       # take the first item out of the string ; stack: <last letter> <word> <first letter>
          ''+    # concatenate into charcodes
              n* # join by newlines

```
> 1 votes

# Answer
# jq, ~~73~~ 68 bytes

```
./" "|map((length<2//[./""|.[-1],.[1:-1][],.[0]]|add?)//.)|join(" ")

```

Try it online!

## How?

```
  . / " "                             # Split on spaces
| map(                                # For each word...
    (
         length<2                     # If it's shorter than 2 letters, emit false
      // [   . / ""                   # Otherwise, emit the word's characters
           | .[-1], .[1:-1][], .[0]]  # ...in the order last, middle, first
      | add?                          # Then re-join the characters into an updated word. If we don't have a list of characters, (if the original was too short), emit nothing
    ) // .                            # If we didn't get a value, emit the word unchanged
  )
| join(" ")

```
> 0 votes

---
Tags: code-golf, string
---


title: Approximate e using small numbers

text:
# Question
Title: Approximate e using small numbers
Given an input integer from 1, 2, ..., n, the task to write code to make a number as close as possible (as measured by absolute distance) to `e` using only the four mathematical operations +, -, \*, / and parentheses (brackets). You can use any of the integers up to `n` once but don't have to use all the numbers and you are not allowed to stick digits together to make new numbers for example.

* The input will be single integer `n` between 1 and 20, inclusive
* The output should be an arithmetic expression which is the closest possible to `e`.

Your code should in principle be correct for `n` all the way up to `20` although of course it doesn't have to terminate in a sensible amount of time. Although not required, it would be great if it did terminate for smaller inputs at least.

# What is e?

```
2.71828182845904523536028747135266249775724709369995....

```

# Examples

* Input 1. Output 1. Distance \\$e - 1 \approx 1.7182818284590451\\$.
* Input 2. Output 1+2=3. Distance \\$3 - e \approx 0.2817181715409549\\$.
* Input 3. Output 3 - 1/2 = 2.5. Distance \\$e - 2.5 \approx 0.21828182845904509\\$.
* Input 4. Output 2 + 3/4 = 2.75. Distance \\$2.75 -e \approx 0.031718171540954909\\$.
* Input 5. Output 3+1/(2/5-4) = 2.722222222222. Distance \\$2.722222222222 - e \approx 0.00394039376\\$.
* Input 6. Output 2+((6-1/4)/(5+3)) = 2.71875. Distance \\$2.71875 - e \approx 0.00046817154\\$.

You can take `e` as input to your code if that is helpful.

# Answer
> 5 votes
# Python, ~~280~~ 229 bytes

*-51 bytes thanks to @AnttiP*

```
lambda n:min(chain(*map(g:=lambda p:["("+l+o+r+")"for i in range(1,len(p))for(l,r,o)in product(g(p[:i]),g(p[i:]),"+-*/")if eval(r)or"/"<o]+[str(p[0]+1)],permutations(range(n)))),key=lambda x:abs(eval(x)-e))
from itertools import*

```

Attempt This Online!

Similarly to @The Thonnu's answer, uses brute force and times out for \\$n\>4\\$.

# Answer
> 4 votes
# JavaScript (ES10), 160 bytes

Expects `(n)(e)`. Works up to \\$n=5\\$ on TIO.

```
n=>g=(e,...a)=>n?g(e,...a,S=m=n--):a.map(p=>a.map(q=>p!=q&&[..."+-*/"].map(o=>g(e,`(${s=p+o+q})`,...a.filter(s=>s!=p&s!=q,(d=eval(s)-e)*d<m&&(m=d*d,S=s))))))&&S

```

Try it online!

### Algorithm

We start with the list \\$a=\[1,2,\dots,n\]\\$.

For each pair \\$(p,q)\in a^2,p\neq q\\$ and for each operator \\$o\\$, we remove \\$p\\$ and \\$q\\$ from the list and append a new expression \\$(p \oplus o \oplus q)\\$.

For each new expression built this way, we compute its squared difference with \\$e\\$ and update the final output \\$S\\$ whenever we get a better score.

This process is repeated recursively until all possible expressions have been tried out. (A leaf in the search tree is reached when all elements have been combined into a single expression.)

Because the initial values are not considered as possible answers by this algorithm, we have to set the default answer to \\$1\\$ for the edge case \\$n=1\\$.

### Commented

```
n =>                        // outer function taking n
g = (e, ...a) =>            // inner function taking e and an array a[]
n ?                         // if n is not equal to 0 (step #1):
  g(                        //   do a recursive call:
    e,                      //     pass e unchanged
    ...a,                   //     pass all previous entries in a[]
    S = m = n--             //     append n (decremented afterwards)
                            //     NB: S and m are eventually set to 1
  )                         //   end of recursive call
:                           // else (step #2):
  a.map(p => a.map(q =>     //   for each pair (p, q) from a[]:
    p != q &&               //     abort if p = q
    [..."+-*/"].map(o =>    //     otherwise, for each operator o:
      g(                    //       do a recursive call:
        e,                  //         pass e unchanged
        '(' + (             //         append a new expression
          s = p + o + q     //         consisting of s = p + o + q
        ) + ')',            //         surrounded with parentheses
        ...a.filter(s =>    //         filter a[]:
          s != p & s != q,  //           remove p and q
          (d = eval(s) - e) //           d is the difference between
                            //           the evaluation of s and e
          * d < m && (      //           if d² is less than m:
            m = d * d,      //             update m to d²
            S = s           //             and update S to s
          )                 //
        )                   //         end of filter()
      )                     //       end of recursive call
    )                       //     end of inner map()
  ))                        //   end of both outer map()'s
  && S                      //   return the best expression

```

### Faster ungolfed version

This version can compute \\$n=1\\$ to \\$n=6\\$ on TIO.

Try it online!

It has a few improvements over the golfed version:

* don't bother to try both \\$a\star b\\$ and \\$b\star a\\$ if \\$\star\\$ is commutative
* return the shortest expression in case of a tie

# Answer
> 3 votes
# Charcoal, 121 bytes

```
Ｎθ⊞υＥＮ⟦Ｉ⊕ι⊕ι⟧ＦυＦＬιＦＬι«≔§ικη≔§ιλζ≔§η¹ε≔§ζ¹δ¿∧δ⁻κλＦＥ⟦∕εδ⁻εδ×εδ⁺εδ⟧⟦⪫()⁺⁺§η⁰§/-*+ν§ζ⁰μ⟧⊞υ⊞ＯΦι∧⁻κξ⁻λξμ»≔Συυ≔↔⁻Ｅυ§ι¹θη§§υ⌕η⌊η⁰

```

Attempt This Online! Link is to verbose version of code. Takes `e` as the first input and `n` as the second input. Explanation: Brute force, so as usual, times out for `n>4`.

```
Ｎθ

```

Input `e`.

```
⊞υＥＮ⟦Ｉ⊕ι⊕ι⟧Ｆυ

```

Start a breadth first search with a list of the initial integers and the expression to generate them (i.e. the value cast to string).

```
ＦＬιＦＬι«≔§ικη≔§ιλζ

```

Loop over each pair of terms from the list.

```
¿∧δ⁻κλＦＥ⟦∕εδ⁻εδ×εδ⁺εδ⟧⟦⪫()⁺⁺§η⁰§/-*+ν§ζ⁰μ⟧

```

If these are different terms and the second term is not zero then loop over the elementary operations on the pair of terms and pair the expressions with the results.

```
⊞υ⊞ＯΦι∧⁻κξ⁻λξμ

```

For each result create a new list with the two terms removed and the new result appended and add this to the lists of lists to be processed.

```
»≔Συυ≔↔⁻Ｅυ§ι¹θη§§υ⌕η⌊η⁰

```

Flatten the final list of lists and output the expression that produces the value closest to `e`.

At a cost of 20 bytes I can avoid performing the addition or multiplication in both directions which speeds the code up a little but not enough to complete `n=5`:

```
Ｎθ⊞υＥＮ⟦Ｉ⊕ι⊕ι⟧ＦυＦＬιＦκ«≔§ικη≔§ιλζＦＥ⁶Ｅη⎇π§⟦∕ξ§ζ¹⁻ξ§ζ¹×ξ§ζ¹⁺ξ§ζ¹∕§ζ¹ξ⁻§ζ¹ξ⟧μ⪫()⪫⎇÷μ⁴⟦§ζ⁰ξ⟧⟦ξ§ζ⁰⟧§/-*+μ¿‹⁰§μ¹⊞υ⊞ＯΦι∧⁻κξ⁻λξμ»≔Συυ≔↔⁻Ｅυ§ι¹θη§§υ⌕η⌊η⁰

```

Attempt This Online! Link is to verbose version of code. Takes `e` as the first input and `n` as the second input.

At a cost of a further 12 bytes I can add some code that avoids repeated values but I don't know whether this can cause some results to be skipped. It does at least just about work for `n=5` though:

```
Ｎθ⊞υＥＮ⟦Ｉ⊕ι⊕ι⟧ＦυＦＬιＦκ«≔§ικη≔§ιλζＦＥ⁶Ｅη⎇π§⟦∕ξ§ζ¹⁻ξ§ζ¹×ξ§ζ¹⁺ξ§ζ¹∕§ζ¹ξ⁻§ζ¹ξ⟧μ⪫()⪫⎇÷μ⁴⟦§ζ⁰ξ⟧⟦ξ§ζ⁰⟧§/-*+μ¿‹⁰§μ¹¿¬№ＥΣυ§ν¹§μ¹⊞υ⊞ＯΦι∧⁻κξ⁻λξμ»≔Συυ≔↔⁻Ｅυ§ι¹θη§§υ⌕η⌊η⁰

```

Attempt This Online! Link is to verbose version of code. Takes `e` as the first input and `n` as the second input.

# Answer
> 2 votes
# Pyth, 53 bytes

```
hoa.n1.xvNZss.ussmmms.i[\(k\)-db)bs_MB.cd2"+-*/"NtQ]S

```

Try it online!

Uses brute force and times out for \\$n\>4\\$ on TIO. It will prefer short answers given a tie.

### Explanation

```
hoa.n1.xvNZss.ussmmms.i[\(k\)-db)bs_MB.cd2"+-*/"NtQ]SQ    # implicitly add Q
                                                          # implicitly assign Q = eval(input())
                                                   ]SQ    # list [[1... Q]]
             .u                                  tQ       # cumulative reduce lambda N,Y along [0... Q-2] with [[1... Q]] as the starting value
                 m                              N         #   map lambda d over N
                  m                       "+-*/"          #     map lambda k over valid operators "+-*/"
                   m              s_MB.cd2                #       map lambda b over all 2 element combinations from d
                             -db                          #         get the elements in d not in b, [...]
                     .i[\(k\)   )b                        #         interleave ["(", k, ")", [...]] with b
                    s                                     #         reduce on +, first summing into a string, then prepending that string to [...]
               ss                                         #   flatten out unwanted nesting
           ss                                             # flatten out more nesting
 o                                                        # sort this list based on lambda N
  a                                                       #   the absolute difference between
   .n1                                                    #   e
      .xvNZ                                               #   and eval(N) or 0 if error is thrown
h                                                         # take the first element

```

# Answer
> 1 votes
# Python, 331 bytes

```
def f(x,e):
 d={};A=[*C([*"()",""],x)]
 for o,p,q,r,s in[*product(A,sum([[*permutations(range(1,x+1),n)]for n in range(x+1)],[]),A,C("+-*/",x),A)]:
  try:S="".join("".join(map(str,l))for l in zip(o,p,q,r,s))[:-1];d[S]=eval(S)
  except:0
 return min(d,key=lambda a:abs(d[a]-e))
from itertools import*;C=combinations_with_replacement

```

Attempt This Online!

Brute-force so times out for \\$n\ge4\\$.

I tried to test it on my computer with \\$n=5\\$ but it was taking ages (probably because for \\$n=5\\$ it has to loop through something like 8.8 trillion times), so I can just reassure with the fact that it works *in theory*.

---
Tags: code-golf
---