title: Remove a letter to make a palindrome

text:
# Question
Title: Remove a letter to make a palindrome
# Problem

Let's say that a word is almost a **palindrome** if it is possible to remove one of its letters so that the word becomes a palindrome. Your task is to write a program that for a given word determines which letter to remove to get a palindrome.

The shortest code to do this in any programming language wins.

## Input

Input consists of a word of lowercase letters from 2 to 1000 characters long.

## Output

Output the 1-indexed position (leftmost letter has position 1, the next one has position 2 and so on) of the letter which should be removed. If there are possible choices that lead to the palindrome, output any of those positions. Note that you are required to remove a letter even if the given word is already a palindrome. If the given word is not almost a palindrome, output -1.

---

# Examples

The input:

```
racercar

```

might produce either of these outputs:

```
4
5

```

because removing the `4`th letter produces `racrcar` and removing the `5`th letter produces `racecar`, which are both palindromes.

Also, the input

```
racecar

```

can still produce the output

```
4

```

because removing the `4`th letter to produce `raccar` is still a palindrome.

The input

```
golf

```

should produce the output

```
-1

```

because there is no way to remove a single letter to make it a palindrome.

# Answer
# J - 31 25 char

```
(_1{ ::[1+[:I.1(-:|.)\.])

```

Largely standard fare for J, so I'll just point out the cool bits.

* The adverb `\.` is called *Outfix*. `x u\. y` removes every infix of length `x` from `y` and applies `u` to the result of each removal. Here, `x` is 1, `y` is the input string, and `u` is `(-:|.)`, a test for whether the string matches its reverse. Hence the result of this application of `\.` is a list of booleans, 1 in the place of each character whose removal makes the input a palindrome.
* `I.` creates an list of all the indices (0-origin) from above where there was a 1. Adding 1 with `1+` makes these 1-origin indices. If no indices were 1, the list is empty. Now, we try to take the last element with `_1{`. (We are allowed to output any of the removable letters!) If this works, we return. However, if the list was empty, there were no elements at all, so `{` throws a domain error which we catch with `::` and return the -1 with `[`.

Usage (recall that `NB.` is for comments):

```
   (_1{ ::[1+[:I.1(-:|.)\.]) 'RACECAR'    NB. remove the E
4
   (_1{ ::[1+[:I.1(-:|.)\.]) 'RAACECAR'   NB. remove an A
3
   (_1{ ::[1+[:I.1(-:|.)\.]) 'RAAACECAR'  NB. no valid removal
_1

```
> 11 votes

# Answer
# ~~Not-PHP~~ Python (73):

```
[a[:g]+a[g+1:]==(a[:g]+a[g+1:])[::-1] for g in range(len(a))].index(1)

```

Where a is the string you want to check. ~~This, however, throws an error if you can't turn it in an palindrome. Instead, you could use~~

~~```
try:print [a[:g]+a[g+1:]==(a[:g]+a[g+1:])[::-1] for g in range(len(a))].index(True)
except ValueError:print -1

```~~

EDIT: No, wait, it does work!

```
try: eval("<?php $line = fgets(STDIN); ?>")
except: print [a[:g]+a[g+1:]==(a[:g]+a[g+1:])[::-1] for g in range(len(a))].index(1)

```

Thanks, this does indeed raise the php-contents of this script by about 25% (that's what you want, right?)
> 10 votes

# Answer
## Mathematica, ~~106~~ ~~98~~ ~~87~~ 91 characters

I suppose I'm slightly handicapped by the long function names, but problems like this are quite fun in Mathematica:

```
f=Tr@Append[Position[c~Drop~{#}&/@Range@Length[c=Characters@#],l_/;l==Reverse@l,{1}],{-1}]&

```

It throws some warnings, because the `l_` pattern also matches all the characters inside, which `Reverse` can't operate on. But hey, it works!

Somewhat ungolfed:

```
f[s_] :=
  Append[
    Cases[
      Map[{#, Drop[Characters[s], {# }]} &, Range[StringLength[s]]],
      {_, l_} /; l == Reverse[l]
    ],
    {-1}
  ][[1, 1]]

```
> 5 votes

# Answer
### GolfScript, 28 26 characters

```
:I,,{)I/();\+.-1%=}?-2]0=)

```

Thanks to Peter for shortening by 2 characters. Try the test cases online:

```
> "RACECAR"
4
> "RAACECAR"
2
> "RAAACECAR"
-1
> "ABCC1BA"
5
> "AAAAAA"
1
> "ABCDE"
-1
> ""
-1
> "A"
1

```
> 5 votes

# Answer
# Jelly, 8 bytes

```
ŒḂ-ƤTȯ-Ḣ

```

Try it online!

Not overwriting my older answer since it's among my first Jelly answers, but it's still way too embarrassing not to fix. I can't blame myself for not coming up with this exactly since nilad-`Ƥ` is pretty obscure documentation-wise, but at least `JœPẎŒḂɗƇȯ-Ḣ` should have been in reach...

```
  -Ƥ        For each "1-outfix" (remove a single item) of the input,
ŒḂ          is it a palindrome?
    T       List all truthy indices.
     ȯ-     Replace an empty list with -1,
       Ḣ    and return the first element.

```

# Jelly, ~~17~~ 14 bytes

```
ŒPṖLÐṀṚŒḂ€TXo-

```

Try it online!

```
           X      A random
          T       truthy index
ŒP                from the powerset of the input
  Ṗ               excluding the input
   LÐṀ            and all proper subsequences with non-maximal length
      Ṛ           reversed
       ŒḂ€        with each element replaced with whether or not it's a palindrome,
            o-    or -1.

```

Since I changed my approach fast enough for the old version not to show up in edit history, it was this: `ŒPṚḊŒḂ€TṂ©’<La®o-`
> 4 votes

# Answer
# Stax, ~~8~~ 10 bytes

```
ú·àA÷¡%5Ñ╙

```

Run and debug it

This program shows all 1-based indices that can be removed from the string to form a palindrome. And if there are none, it shows -1.
> 4 votes

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

```
ā.Δõs<ǝÂQ

```

Try it online or verify some more test cases.

**Explanation:**

```
ā          # Push a list in the range [1, (implicit) input-length]
 .Δ        # Pop and find the first value in this list which is truthy for:
           # (which will result in -1 if none are truthy)
   õ       #  Push an empty string ""
    s      #  Swap to get the current integer of the find_first-loop
     <     #  Decrease it by 1 because 05AB1E uses 0-based indexing
      ǝ    #  In the (implicit) input-String, replace the character at that index with
           #  the empty string ""
       Â   #  Then bifurcate the string (short for Duplicate & Reverse copy)
        Q  #  And check if the reversed copy is equal to the original string
           #  (so `ÂQ` basically checks if a string is a palindrome)
           # (after which the result is output implicitly)

```
> 4 votes

# Answer
# Japt, 8 bytes

```
a@jYÉ êS

```

Try it

```
a@jYÉ êS     :Implicit input of string
a            :Last 0-based index that returns true (or -1 if none do)
 @           :When passed through the following function as Y
  j          :  Remove the character in U at index
   YÉ        :    Y-1
      êS     :  Is palindrome?

```
> 4 votes

# Answer
# C#, 134 Characters

```
static int F(string s,int i=0){if(i==s.Length)return-1;var R=s.Remove(i,1);return R.SequenceEqual(R.Reverse())?i+1:F(s,i+1);}

```

I know I lose **:(** but it was still fun **:D**

Readable version:

```
using System.Linq;

// namespace and class

static int PalindromeCharIndex(string str, int i = 0)
{
    if (i == str.Length) return -1;
    var removed = str.Remove(i, 1);
    return removed.SequenceEqual(removed.Reverse())
        ? i+1
        : PalindromeCharIndex(str, i + 1);
}

```
> 3 votes

# Answer
# Rebol (81)

```
r: -1 repeat i length? s[t: head remove at copy s i if t = reverse copy t[r: i]]r

```

Example usage in Rebol console:

```
>> s: "racercar"
== "racercar"

>> r: -1 repeat i length? s[t: head remove at copy s i if t = reverse copy t[r: i]]r
== 5

>> s: "1234"
== "1234"

>> r: -1 repeat i length? s[t: head remove at copy s i if t = reverse copy t[r: i]]r
== -1

```

Above returns index of last palindrome found. An alternative solution (85 chars) which returns every palindrome found would be:

```
collect[repeat i length? s[t: head remove at copy s i if t = reverse copy t[keep i]]]

```

So for `"racercar"` this would return list `[4 5]`.
> 3 votes

# Answer
# ~~Not Python~~ PHP, ~~85~~ ~~83~~ 81 bytes

```
while($argn[$x])$s!=strrev($s=substr_replace($argn,'',$x++,1))?:die("$x");echo-1;

```
* -2 bytes thanks to @Night2!

Try it online!

Unnecessarily recursive:

### PHP, 96 bytes

```
function f($a,$b='',$d=1){return$a?$c==strrev($c=$b.$e=substr($a,1))?$d:f($e,$b.$a[0],$d+1):-1;}

```

Try it online!
> 3 votes

# Answer
# Brachylog, 20 bytes

```
l⟧∋.&↻↺↙.b↺↻↙.I↔I∨_1

```

Try it online!

It was too long
> 3 votes

# Answer
# Ruby (61):

```
(1..s.size+1).find{|i|b=s.dup;b.slice!(i-1);b.reverse==b}||-1

```

Here, have a ruby solution. It will return the position of the character to remove or -1 if it cannot be done.

I can't help but feel there's improvement to be made with the dup and slice section, but Ruby doesn't appear to have a String method that will remove a character at a specific index and return the new string -\__-.

*Edited as per comment, ty!*
> 2 votes

# Answer
# Perl 5 `-p`, ~~56~~ 52 bytes

```
("$`$'"eq reverse"$`$'")&&($\=pos)while/./g}{$\||=-1

```

Try it online!
> 2 votes

# Answer
# Brachylog, 24 bytes

```
{l+₁≥.ℕ₂≜&↔⊇ᶠ↖.tT↔T∨0}-₁

```

Try it online!

Feels way too long.

Could be two bytes shorter if the output could be *2-indexed*:

```
l+₁≥.ℕ₂≜&↔⊇ᶠ↖.tT↔T∨_1

```

Two earlier and even worse iterations:

```
ẹ~c₃C⟨hct⟩P↔P∧C;Ȯ⟨kt⟩hl<|∧_1
l>X⁰ℕ≜<.&{iI¬tX⁰∧Ih}ᶠP↔P∨_1

```

The latter's use of a global variable necessitates a different testing header.
> 2 votes

# Answer
# Python 3, 681 bytes

```
from itertools import groupby

def solution(x):
    if len(x) == 1:
        return 1
    lst = [''.join(g) for _, g in groupby(sorted(x))]
    print(lst)
    pal_str_len = 0
    single_elements = False
    odd_elements = False
    for i in lst:
        if len(i)%2 == 0:
            pal_str_len +=len(i)
        elif len(i)%2 == 1:
            if odd_elements:
                pal_str_len +=len(i)-1
            else:
                odd_elements = True
                pal_str_len +=len(i)
        elif len(i) == 1:
            if not odd_elements and not single_elements:
                single_elements = True
                pal_str_len += 1

    return len(x)-pal_str_len
x = 'AAABBC'
print(solution(x))
```
> 2 votes

# Answer
# C++, ~~247~~ 150 bytes

-97 thanks to ceilingcat

TIO Link

```
#import<map>
int P(std::string s){int i=0,j,q,r=-1;for(;s[i++]*!~r;r=q?r:i)for(auto t=s.substr(j=q=0,i-1)+&s[i];t[j];)q|=t[j]-*(end(t)-++j);return r;}

```

Test code example :

```
std::cout << P("RACERCAR") << '\n';

```
> 2 votes

# Answer
# Brachylog, 17 bytes

```
~cLkʰcP↔P∧Lhl.∨_1

```

Try it online! (Can be rather slow for inputs that are not almost-palindromes. For faster performance, replace the `~c` with `~c₂`.)

### Explanation

```
~c                 "Unconcatenate" the string into a list of strings
  L                Call that list of substrings L
   kʰ              Remove the last character from the first substring
     c             Concatenate the list of strings together again
      P            Call that new string P
       ↔           Reverse
        P          Assert that the result is still the same (i.e. P is a palindrome)
         ∧L        Also, going back to the list L
           h       Get its first element
            l      Get its length
             .     This is the output of the predicate
              ∨    Or, if there is no way to satisfy the previous conditions
               _1  Output -1 instead

```
> 2 votes

# Answer
### Haskell, 107 characters:

```
(x:y)!1=y;(x:y)!n=x:y!(n-1)
main=getLine>>= \s->print$head$filter(\n->s!n==reverse(s!n))[1..length s]++[-1]

```

As a function (**85 characters**):

```
(x:y)!1=y;(x:y)!n=x:y!(n-1)
f s=head$filter(\n->s!n==reverse(s!n))[1..length s]++[-1]

```

original ungolfed version:

```
f str = case filter cp [1..length str] of
          x:_ -> x
          _   -> -1
    where cp n = palindrome $ cut n str
          cut (x:xs) 1 = xs
          cut (x:xs) n = x : cut xs (n-1)
          palindrome x = x == reverse x

```
> 1 votes

# Answer
## C# (184 characters)

I admit this is not the best language to do code-golfing...

```
using System.Linq;class C{static void Main(string[]a){int i=0,r=-1;while(i<a[0].Length){var x=a[0].Remove(i++,1);if(x==new string(x.Reverse().ToArray()))r=i;}System.Console.Write(r);}}

```

Formatted and commented:

```
using System.Linq;

class C
{
    static void Main(string[] a)
    {
        int i = 0, r = -1;
        // try all positions
        while (i < a[0].Length)
        {
            // create a string with the i-th character removed
            var x = a[0].Remove(i++, 1);
            // and test if it is a palindrome
            if (x == new string(x.Reverse().ToArray())) r = i;
        }
        Console.Write(r);
    }
}

```
> 1 votes

# Answer
# C# (84 Characters)

```
int x=0,o=i.Select(c=>i.Remove(x++,1)).Any(s=>s.Reverse().SequenceEqual(s))?x:-1;

```

LINQpad statement expecting the variable `i` to contain the input string. Output is stored in the `o` variable.
> 1 votes

# Answer
# Haskell, 80

```
a%b|b<1=0-1|(\x->x==reverse x)$take(b-1)a++b`drop`a=b|1<2=a%(b-1)
f a=a%length a

```

Called like this:

```
λ> f "racercar"
5

```
> 1 votes

# Answer
# Python 3, 71 bytes

```
def f(s,i=1):n=s[:i-1]+s[i:];return(n==n[::-1])*i-(i>len(s))or f(s,i+1)

```

Try it online!

Returns the 1-indexed character if the operation can be done and `-1` otherwise.
> 1 votes

# Answer
# C (gcc), ~~180~~ ~~168~~ ~~159~~ ~~157~~ ~~140~~ 139 bytes

```
f(char*s){int j=strlen(s),m=j--/2,p=-1,i=0;for(;p&&i<m;)p=s[i++]^s[j--]&&!++p?s[i]-s[j+1]?s[i-1]-s[j]?p:j--+2:i++:p;return p<0?m+1:p?p:-1;}

```

Try it online!

~~2~~ ~~16~~ 17 bytes shaved off thanks to ceilingcat! And 3 more bytes since the rules state the minimum length of the input is 2 characters, so don't have to check for empty strings.

Ungolfed:

f(char *s) {
  int j = strlen(s);             // j = length of input
  int m = j-- / 2;               // m = midpoint of string,
                                 // j = index of right character
  int p = -1;                    // p = position of extra character
                                 //     -1 means no extra character found yet
                                 //     0 means invalid input
  int i = 0;                     // i = index of left character

  for (; p && i < m; i++) {      // loop over the string from both sides,
                                 // as long as the input is valid.
    p = s[i] ^ s[j--]            // if (left character != right character
        && !++p ?                //     and we didn't remove a character yet*)
          s[i + 1] - s[j + 1] ?  //   if (left+1 char != right char)
            s[i] - s[j] ?        //     if (left char != right-1 char)
              p                  //       do nothing,
            :                    //     else
              j-- + 2            //       remove right char.
          :                      //   else
            ++i                  //       remove left char.
        :                        // else
          p;                     //     do nothing, or:
                                 //     *the input is marked invalid
  }

  return p < 0 ?                 // if (input valid and we didn't remove a character yet)
           m + 1                 //   return the midpoint character,
         :                       // else
           p ?                   //   if (we did remove a character)
             p                   //     return that character,
           :                     //   else
             -1;                 //     the input was invalid.
}
```
</code></pre>
> 1 votes

# Answer
# Wolfram Language (Mathematica), 56 bytes

```
FirstCase[Range@Tr[1^#],a_/;PalindromeQ@Delete[#,a],-1]&

```

Try it online!

Takes input as a list of characters. For string input, append `@*Characters`.

`PalindromeQ` was introduced in 2015. The alternative costs +4 bytes.
> 1 votes

# Answer
# Vyxal `G`, 58 bits<sup>v1</sup>, 7.25 bytes

```
ẏ⋎:R=T›uJ

```

Try it Online!

Hehe vyncode go brrr
> 1 votes

# Answer
# JavaScript (Node.js), 75 <sup>~~90~~</sup> bytes

> -15 bytes thanks to @Shaggy 's conversion into a recursive function, simplification of the array comparison, and replacement of a `map` with a `reduce`.

JS might not be the right tool for this job, but i was surprised no one posted a JS answer before.
For each character of the word, we test if the removal of this character gives a word that is a palindrome, and we retain the `index +1` of the last character that succeeded (or `-1` if there weren't any).

```
f=(s,r=i=-1)=>s[++i]?f(s,(a=[...s]).splice(i,1)&&a+``==a.reverse()?i+1:r):r

```

Try it online!
> 1 votes

# Answer
# sed `-E`,  ~~266 258 254~~  238 bytes

(230 bytes with ugly GNU extensions and bugs)

Unfortunally, `sed` needs to be tought how to count; otherwise this could have been much shorter. Anyhow, I think this is quite a clever approach and highly golfed. The idea is to put a `1` in front of the first char (line 1, along with counting helper), then to double the word with an increased number at an increased position (line 3). Then comes some overhead to count past 9 and even more overhead to count past 99. Could be golfed by switching to non-decimal output.

Finally, starting from `:3`, all strings are eaten up from the start and from the end, until there is only 1 or no char left. I'm pretty sure this is the shortest way to check for a palindrome.

```
s/.*/0123456789#:-1:1&:/
:1
s/(.)(.).*:([a-z]*)(.*)\1([a-z])([^:]*:)$/&\3\5\4\2\6/
s/([a-z])(9*)#/\10\2#/
:2
s/((.)(.).*)\2#/\1\30/
t2
/[0-9].:$/!b1
s/([a-z]*)([0-9]+)[^:]/\2\1/g
:3
s/([0-9])(.)([^:]*)\2:/\1\3:/
t3
s/.*:([-0-9]*).?:.*/\1/

```

Try it online!
> 1 votes

# Answer
# Julia, 72 68 bytes

```
!s=[filter(i->(t=s[1:i-1]s[i+1:end])==reverse(t),1:length(s));-1][1]

```

Attempt This Online!
> 1 votes

# Answer
## Haskell, 118C

```
m s|f s==[]=(-1)|True=f s!!0
f s=[i|i<-[1..length s],r s i==(reverse$r s i)]
r s i=let(a,_:b)=splitAt (i-1) s in a++b

```

Ungolfed:

```
fix s
    |indices s==[] = (-1)
    |True = indices s!!0
indices s = [i|i<-[1..length s],remove s i==(reverse$remove s i)]
remove s i = let (a,_:b) = (splitAt (i-1) s) in a++b

```
> 0 votes

# Answer
# k, 21 characters

No surprises, generates the list of strings that are the result of removing a character from each index, checks each for pallindrome, take the first index where true, filling with -1 if null

```
{-1^*&{x~|x}'x_/:!#x}

```
> 0 votes

# Answer
**Uiua, 21 bytes**

```
a←
▽∵(≅⇌.▽≠⇡⧻,∶a).⇡⧻a

```

I'm sure it could be done better, it does as you expect, filtering a range of indexes by which ones produce a palindrome (inside the brackets is the palindrome checker).
> 0 votes

# Answer
# Go, 166 bytes

```
func P(s string)bool{for i:=range s{if s[i]!=s[len(s)-i-1]{return 0>1}}
return 0<1}
func f(s string)int{for i:=0;i<len(s);i++{if P(s[:i]+s[i+1:]){return i}}
return-1}

```

Attempt This Online!

Returns the first 0-based index that creates a palindrome when removed.
> 0 votes

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


title: Half even rounding

text:
# Question
Title: Half even rounding
The `round` function in Python 3 will round values of the form \\$k+\frac{1}{2}\\$ (with \\$k\\$ being an integer) to the nearest **even** integer, which is apparently better than the rounding method taught in school

Your task is to recreate this functionality: write a program of function that given a (real) number as input, outputs that number rounded to the nearest number, using the same tie-breaking rule as Python's round function

## Examples/Test-cases

```
-3.0   ->    -3
-2.7   ->    -3
-2.5   ->    -2
-2.2   ->    -2
-1.7   ->    -2
-1.5   ->    -2
-0.7   ->    -1
-0.5   ->    0
0.0    ->    0
0.4    ->    0
0.5    ->    0
0.51   ->    1
1.0    ->    1
1.2    ->    1
1.4999 ->    1
1.5    ->    2
1.7    ->    2
2.0    ->    2
2.3    ->    2
2.5    ->    2
2.6    ->    3

```

## Rules

* Please add built-in solutions to the community wiki
* This is the shortest solution wins

# Answer
> 11 votes
### Builtins in various languages

# 05AB1E (legacy), 1 byte

```
ò

```

Only works in the legacy version of 05AB1E, which is builtin in Python. The new version of 05AB1E, which is built in Elixir, will round away from zero.

Try it online or verify all test cases.

# C, 5 bytes

```
lrint

```

The Linux manual page lists this as being part of the C99, POSIX.1-2001, and POSIX.1-2008 standards. It can be used without a prototype for golfing since it returns `long`, unlike the 4-byte `rint` which returns `double` and thus can handle the full range of `double` inputs. Both these and `nearbyint` use the current rounding FP mode, which is nearest-even by default on IEEE-754 systems, unlike C's `round` function which uses away-from-zero as a tiebreak (like Python 2's `round`).

C++11 includes the C99 math library (which many C/C++ implementations already provided). Since you need prototypes anyway in C++, `std::rint` or just **`rint` 4 bytes** should be available after `#include <cmath>` (cppreference).

# C# (Visual C# Compiler), 17 bytes

```
x=>Math.Round(x);

```

Try it online!

The build in Math.Round in C# already rounds to the nearest even number

# Factor, 13 bytes

```
round-to-even

```

Attempt This Online!

# Forth (gforth), 6 bytes

```
fround

```

Try it online!

# Haskell, 5 bytes

```
round

```

Try it online! From the documentation:

> `round x` returns the nearest integer to `x`; the even integer if `x` is equidistant between two integers

# Jelly, 3 bytes

```
ær0

```

Try it online!

# MMIX, 4 bytes/1 instruction

```
␗�␄�

```

The replacement characters are in order the output and input registers; Unicode control pictures have been used to encode unprintable characters. This is `FINT $x,ROUND_NEAR,$y`, which rounds a float to the nearest integer (half-even).

# PowerShell Core, 22 bytes

```
[Math]::Round("$args")

```

Try it online!

# PHP, 20 bytes

PHP's `round` has a third parameter "mode" that can be used with the constant `PHP_ROUND_HALF_EVEN` (value: 3)

```
<?=round($argn,0,3);

```

Try it online!

# Python, 5 bytes

```
round

```

Attempt This Online!

# , 5 bytes

```
round

```

Attempt This Online!

# Rust, 25 bytes

Using libmath

```
math::round::half_to_even

```

# Thunno 2, 1 byte

```
V

```

Try it online!

# Vyxal, 1 byte

Try it Online!

# Answer
> 11 votes
# JavaScript (ES6), 30 bytes

Uses the `Math.round()` built-in, then clears the least significant bit of the result if the squared fractional part of the original input is \\$1/4\\$.

```
v=>Math.round(v)&~(v*v%1==.25)

```

Try it online!

### Explanation

`Math.round` does *rounding half up*.

We have 4 cases. Given \\$k\ge 0\\$:

* \\$2k+1/2\\$ is rounded to \\$2k+1\\$. Clearing the LSB turns it into \\$2k\\$.

Example: \\$22.5 \rightarrow 23 \rightarrow 22\\$
* \\$2k+1+1/2\\$ is rounded to \\$2k+2\\$. Clearing the LSB leaves it unchanged.

Example: \\$23.5 \rightarrow 24 \rightarrow 24\\$
* \\$-(2k+1/2)\\$ is rounded to \\$-2k\\$. Clearing the LSB leaves it unchanged.

Example: \\$-22.5 \rightarrow -22 \rightarrow -22\\$
* \\$-(2k+1+1/2)\\$ is rounded to \\$-(2k+1)\\$. Clearing the LSB turns it into \\$-(2k+2)\\$.

Example: \\$-23.5 \rightarrow -23 \rightarrow -24\\$

# Answer
> 8 votes
# Jelly, 9 bytes

Jelly's builtin is 3 bytes: `ær0` \- round to nearest multiple of \\$10^0\\$, which employs Python's `round`.

```
Ḟ,ĊḂÞạÞ⁸Ḣ

```

**Try it online!**

### How?

```
Ḟ,ĊḂÞạÞ⁸Ḣ - Link: float, X
Ḟ         - floor {X}
  Ċ       - ceil {X}
 ,        - pair -> [floor(X), ceil(X)]
    Þ     - sort by:
   Ḃ      -   is odd?
      Þ   - sort by:
     ạ ⁸  -   absolute difference {X}
        Ḣ - head

```

# Answer
> 6 votes
# , 7 bytes

```
0".@":]

```

Try it online!

Formats to zero decimal places and then evaluates back to number.

# , 14 bytes

```
<.@+1-:@~:4|+:

```

Try it online!

Evaluates `floor(x + 0.5)` unless `2*x%4 == 1`, in which case `floor(x)` is returned instead.

```
<.@+1-:@~:4|+:
          4|+:   2*x%4
    1   ~:       != 1
     -:@         / 2
   +             x +
<.@              floor()

```

# Answer
> 5 votes
# , ~~35~~ ~~25~~ 23 bytes

*Edit: -2 bytes thanks to pajonk*

```
\(x)(x+.5-!x%%2-.5)%/%1

```

Attempt This Online!

# Answer
> 4 votes
# K (ngn/k), 38 37 34 27 23 bytes

```
{*r-2!r*=/r:|1_:\x+0.5}

```

Try it online!

-1 : Shuffle
-3 : Shuffle
-7 : Rework
-4 : Wow

# Answer
> 3 votes
# Retina 0.8.2, 61 bytes

```
([02468])\.5$|\.[0-4].*
$1
\b9+\.
0$&
T`9d`d`.9*\.
\..+

-0
0

```

Try it online! Link includes test cases. Explanation:

```
([02468])\.5$|\.[0-4].*
$1

```

Remove the `.5` after an even digit, and any decimal less than `.5`.

```
\b9+\.
0$&

```

If there is an all `9`s integer part with a decimal part, prefix a zero.

```
T`9d`d`.9*\.

```

If there is a decimal part then increment the integer part.

```
\..+

-0
0

```

Remove any decimal part and change `-0` to `0`.

# Retina, 46 bytes

```
([02468])\.5$|\.[0-4].*
$1
\d+\..+
$.(*__
-0
0

```

Try it online! Link includes test cases. Explanation:

```
([02468])\.5$|\.[0-4].*
$1

```

Remove the `.5` after an even digit, and any decimal less than `.5`.

```
\d+\..+
$.(*__

```

If there is still a decimal part, remove it and increment the integer part.

```
-0
0

```

Change `-0` to `0`.

# Answer
> 3 votes
# , ~~22~~ 21 bytes

```
<.@+&1r2([-AND)1=2|+:

```

Try it online!

Heavily inspired by Arnauld's approach, except checks for exact 0.5 by doubling and checking that the remainder mod 2 is exactly 1 `1=2|+:`.

Then subtracts the adjustment bit `AND`ed with the standard round from the standard round.

# Answer
> 2 votes
# , 57 bytes

```
\(x,a=x%/%1)`if`(x-a<.5,a,`if`(x-a>.5|a%%2,ceiling(x),a))

```

Attempt This Online!

# Answer
> 2 votes
# K (ngn/k), 16 bytes

```
{_x+0.5-1=4!2*x}

```

Try it online!

A near-port of my own J answer.

# Answer
> 2 votes
The nearest-even rounding mode, aka Banker's Rounding, is the default for IEEE-754 math, so normal programs (which haven't changed the FP environment) on most ISAs including x86 can just use instructions that round a float to an integer-valued float, or convert to integer with the current rounding mode. (Most programs don't change the rounding mode away from the default.)

This is basically just using built-ins, but I didn't want to clutter up the existing answer with a bunch of machine-code stuff and associated interesting stuff I wanted to write about x86. If people want to add sections for other ISAs, feel free, although most other mainstream ISAs have fixed-width instructions so it's always either a 2 or 4-byte instruction.

For the convert-to-integer instructions, out-of-range inputs produce the most-negative 2's complement integer of whatever destination width, which Intel calls the "integer indefinite" value. (e.g. `0x80000000` for 32-bit.) For AVX-512 unsigned conversions, the "integer indefinite" value is all-ones, `0xffffffff` (e.g. from `vcvtss2usi`.) Rounding instructions that produce a number in the same format as the input don't have this problem.

# x86(-64) machine code, x87 scalar math, 3 bytes

Uses the rounding mode in the x87 control word, which defaults to round-to-nearest w. even as a tie-break. (at reset and `finit`, and in fresh processes under normal OSes).

Input arg in `st0`, top of the x87 stack, result stored to an `int *` pointed-to by RDI (or EDI if the same bytes execute in 32-bit mode). None of the standard calling conventions even for 32-bit mode pass FP args in x87 registers; unlike the SSE part of the answer, you couldn't write a C prototype to describe it to a C compiler.

```
  db 1f                   fistp  DWORD PTR [rdi]
  c3                      ret

```

Or to round to an integer-valued `long double` (modifying `st0` in place), 2-byte `frndint` is `D9 FC`.

# x86(-64) SSE2 or AVX scalar math, 5 bytes

These use the current rounding mode in MXCSR, the SSE math control/status register, which is fully independent of the x87 FP environment. Both use the same 2-bit codes for four different rounding modes, ceil/floor/trunc and nearest-even. (The Python 2 / C `round()` rounding mode is not directly available in hardware on x86, so should be avoided for performance reasons unless you specifically want it. IIRC, ARM does have it in hardware, as well as IEEE standard rounding.)

All the relevant SSE / SSE2 / AVX conversion instructions are 4 bytes long, whether encoded as legacy-SSE or AVX, except for conversion into an MMX register. SSE1 `cvtps2pi mm0, xmm0` is `0f 2d c0`, allowing for a total 4-byte function if you're willing to return a 32-bit signed integer in the bottom of `mm0`, which is a pretty inconvenient place for it and would need the caller to use longer instructions to store or do math with it.

SSE1 `ps` instructions are only 3 bytes, but `cvtps2dq` involves packed integers so was new in SSE2 along with `cvtpd2dq` (packed-double vs. packed-single, converting to a double-quad-word of packed integers). SSE1 scalar instructions have an extra prefix, so SSE1 `cvtss2si eax, xmm0` is also 4 bytes, same as SSE2 `cvtsd2si eax, xmm0`. An AVX encoding of all of these is available with 2-byte VEX prefixes (plus opcode + modrm byte), again for 4-byte instructions, except there's no `cvtps2pi` (MMX destination.)

```
                          sse:       # first arg in XMM0, return in EAX
    f3 0f 2d c0             cvtss2si eax,xmm0         # SSE1
    c3                      ret

Alternatives:  # float vs. double, and scalar vs. packed.
    f2 0f 2d c0             cvtsd2si eax,xmm0         # SSE2 scalar double to i32, note same 0f 2d opcode but different prefix from SSE1 scalar.
       0f 2d c0             cvtps2pi mm0,xmm0         # SSE1 2 floats to 2 i32 in an MMX reg
    66 0f 5b c0             cvtps2dq xmm0,xmm0        # SSE2 packed conversion 4 floats to 4x i32.  cvtpd2dq (2 doubles to 2 i32) is the same size

    c5 f9 5b c0             vcvtps2dq xmm0,xmm0       # AVX encodings; different bits in the C5 ... prefix represent different combinations of prefixes.
    c5 fa 2d c0             vcvtss2si eax,xmm0
    c5 fb 2d c0             vcvtsd2si eax,xmm0      ... etc.

```

(There are also truncating versions of these, like `cvttsd2si`, to implement C `(int)double` rounding semantics of truncation toward 0 without having to change the rounding mode like in the bad old days of x87 before SSE3 `fisttp`.)

Implementing C `rint[f]` / `nearbyint[f]` (rounding to an integer-valued `double` \[or `float`\]) needs multiple instructions until SSE4.1 `roundsd` / `roundps` etc, which are 6-byte instructions (with register args and no REX). e.g. `66 0f 3a 0a c0 00 roundss xmm0,xmm0,0x0`. (roundss and roundsd have separate opcodes, instead of being distinguished by prefixes like SSE1 `addss` vs. SSE2 `addsd`). The instruction needs an immediate to specify the rounding mode: whether to override or not, and if so, which of the 4 modes to use, and whether to suppress FP inexact (precision) exceptions. See `roundsd` documentation. An immediate of `0` selects rounding-control = from the immediate, with the `00` field being the nearest-even mode that's the default.

(Like the "alternatives" above, I'm showing machine code + assembly of multiple instructions. You'd only ever use one, depending on the input format (float or double, scalar vs. packed).)

```
66 0f 3a 08 c0 00       roundps xmm0,xmm0,0x0        # other than SSE1, the ps form isn't shorter.
66 0f 3a 0a c0 00       roundss xmm0,xmm0,0x0
66 0f 3a 0b c0 00       roundsd xmm0,xmm0,0x0

c4 e3 79 0b c0 00       vroundsd xmm0,xmm0,xmm0,0x0      # 3-byte VEX prefix needed for instructions in opcode "maps" used by SSE4 and later, i.e. with 3 prefixes such as 66 0f 3a
c4 e3 79 08 c0 00       vroundps xmm0,xmm0,0x0   ... etc.

```

# x86 + AVX-512 not relying on the current rounding mode, 7 bytes

**AVX-512 EVEX prefixes can override the rounding mode on a per-instruction basis**, for *any* instruction with scalar or 512-bit vector width, including when `vaddps` or whatever have to round their result to a representable float/double. (Not 128 or 256-bit vector width until APX and AVX10.2 which finally stops caring about obsolete 32-bit mode so it can use more of the bits of the EVEX prefix, instead of having to slot in to only invalid-in-32-bit-mode encodings of some instruction.) Fun fact: out-of-order exec CPUs that support SMT (e.g. hyperthreading) already have to track the rounding mode on a per-instruction basis internally, because different logical cores could be using different rounding mode settings. So it makes some sense to expose this functionality to programmers.

AVX-512 also allows for conversion directly to unsigned integer, and to *packed* 64-bit integers, not just scalar-only for conversions involving 64-bit signed integers in SSE/AVX (in 64-bit mode only).

An Intel manual from 2016 when AVX-512 was newish has some details in section 2.5.4 *Static Rounding and Suppress All Exceptions*, where it compares to instructions like `vroundps` and `vrndscaleps` which allow this via an immediate, vs. setting MXCSR.

```
                         avx512:
    62 f1 ff 18 2d c0       vcvtsd2si rax,xmm0{rn-sae}
    c3                      ret

```

The NASM syntax I used is `vcvtsd2si rax, xmm0, {rn-sae}`. The disassembly is from `objdump -drwC -Mintel`, so is using GAS's `.intel_syntax noprefix` style for the rounding override.

Using an `eax` destination wouldn't save any machine code bytes, unlike with legacy SSE (separate REX prefix), or with AVX where `vcvtsd2si rax,xmm0` needs a 3-byte VEX prefix for a total length of 5 bytes instead of 4.

# Answer
> 1 votes
# Charcoal, 21 bytes

```
ＮθＩ⊟⌊Ｅ⟦⌊θ⌈θ⟧⟦↔⁻θι﹪ι²ι

```

Try it online! Link is to verbose version of code. Explanation: Port of @JonathanAllan's Jelly answer.

```
Ｎθ                      Input as a number
        θ               Input number
       ⌊                Floor
          θ             Input number
         ⌈              Ceiling
     Ｅ⟦    ⟧            Map over both values
               θ        Input number
                ι       Current value
             ↔⁻         Absolute difference
                  ι     Current value
                 ﹪      Modulo
                   ²    Literal integer `2`
                    ι   Current value
            ⟦           Make into list
    ⌊                   Take the minimum
   ⊟                    Pop the rounded result
  Ｉ                     Cast to string
                        Implicitly print

```

34 bytes for arbitrary precision:

```
≔⪪θ.η≔⊟ηζＩ⁻ＩΣη∧⎇﹪ＩΣη²¬‹ζ5›ζ5∨№θ-±¹

```

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

```
≔⪪θ.η≔⊟ηζ

```

Separate the integer and decimal parts.

```
Ｉ⁻ＩΣη∧⎇﹪ＩΣη²¬‹ζ5›ζ5∨№θ-±¹

```

Compare the decimal `>=` or `>` than `.5` depending on whether the integer is odd or even, and increment the absolute value of the integer if so.

# Answer
> 1 votes
# JavaScript (Node.js), 17 bytes

```
v=>v*(k=3e-324)/k

```

Try it online!

---
Tags: code-golf, number
---


title: Implement the RegPack decompressor

text:
# Question
Title: Implement the RegPack decompressor
The JavaScript compressor RegPack uses a very simple string compression algorithm. Given a piece of code, it will make a list of characters that aren't used in that code and use them to delimit repeated strings that are inserted back into the string.

To show how strings are compressed, it's necessary to show how the decompressor works. If you give RegPack the tongue-twister `How much wood would a woodchuck chuck if a woodchuck could chuck wood?`, it will spit out `How much } w|a }~~if a }~c|~}?~chuck }wood|ould`  along with the list of characters `|}~`.

The decompressor starts by splitting this string on the first character in the char list, `|`, resulting in `["How much } w", "a }~~if a }~c", "~}?~chuck }wood", "ould "]`. It then pops the last item, `"ould "`, and joins what remains by this, resulting in `"How much } would a }~~if a }~could ~}?~chuck }wood"`.

It then does the same thing for `}`, replacing `}` with `wood` to result in `"How much wood would a wood~~if a wood~could ~wood?~chuck "`, and finally replaces `~` with `"chuck "` to result in the whole thing, `How much wood would a woodchuck chuck if a woodchuck could chuck wood?`.

The advantage of this algorithm is that it's very simple and short to implement. RegPack itself implements it in 39 bytes of JavaScript: `for(i of<chars>)with(_.split(i))_=join(pop())` (where `<chars>` is a hardcoded char list), which basically performs the steps described above.

Your challenge is to, given a compressed string and a list of characters, decompress it using the above algorithm.

## Testcases

```
'a|b|c|hello', '|' => ahellobhelloc
'He||o, wor|d!|l', '|' => Hello, world!
'| | & &&|house|green', '|&' => green green greenhouse greenhouse
'N~give}up,n~let}down~ever gonna } you ', '}~' => Never gonna give you up,never gonna let you down
'How much } w|a }~~if a }~c|~}?~chuck }wood|ould ', '|}~' => How much wood would a woodchuck chuck if a woodchuck could chuck wood?
'She sells~ells by the~ore~ sea sh', '~' => She sells sea shells by the sea shore

```

# Answer
# 05AB1E, ~~6~~ 5 bytes

-1 thanks to @KevinCruijssen

```
vy¡`ý

```

Try it online!

## Explanation

```
v      # for each char in the char list
 y      # push it
 ¡      # split the current string by it
 `      # dump the parts to stack
 ý      # join the stack by the last part

```
> 6 votes

# Answer
# Husk, 7 bytes

```
F(↔ΓJx↔

```

Try it online!

### Explanation

```
F(↔ΓJx↔
F        For each character in the character list:
      ↔    flip the string
     x     split it on the given character
   ΓJ      use the first element to join the rest of the list
  ↔        flip the string back

```

Why all that flipping back and forth? Because in Husk it's often easier to operate on the first element of a list than the last (`Γ` here does exactly that). We could manually take the last element and everything except that, but the program would have the same length: `F(§J→hx`

We could solve the challenge in 5 bytes (`F(ΓJx`) if we were allowed to operate on the reversed string, or to have the changes listed at the beginning of the string.
> 5 votes

# Answer
# Retina 0.8.2, 45 bytes

```
+`(?=.*¶(.))\1((?=.*\1(.+))|.+)|(?<=¶).|¶$
$3

```

Try it online! No test suite because I can't think of a good separator between the two strings. Explanation:

```
+`

```

Repeat for each character in the list.

```
(?=.*¶(.))\1((?=.*\1(.+))|.+)|(?<=¶).|¶$
$3

```

Search the string for occurrences of the first character in the list, and try to replace it with the word after the last occurrence, otherwise delete the last occurrence and the word after it. Finish by deleting the character from the list and the list itself once the last character has been processed.
> 4 votes

# Answer
# Ruby, 41 bytes

```
->s,l{l.chars{|x|*k,w=s.split x;s=k*w};s}

```

Try it online!

Not particularly original, I guess.
> 3 votes

# Answer
# Jelly, 6 bytes

```
ṣjṪ$¥ƒ

```

Try it online!

Takes the delimiters on the left and the compressed string on the right.

```
    ¥ƒ    Reduce the delimiters by, starting with the compressed string:
ṣ         Split on the delimiter
 j        and join that on
  Ṫ$      its last element (removed).

```
> 3 votes

# Answer
# PowerShell Core, 74 bytes

```
param($t)$args|%{$j=($o=$t|% S*t $_)[-1]
$t=$o[0..($o.Count-2)]-join$j}
$t

```

Try it online!

Or using `""::Join`

Or using `$ofs`
> 2 votes

# Answer
# Perl 5 `-lp`, ~~64~~, 61 bytes

```
s/(\S+) //;for$c($1=~/./g){@a=split/\Q$c/;$_=join pop(@a),@a}

```

Try it online!

Another using regex

# Perl 5 `-lp`, ~~64~~, 54 bytes

```
s/^(\S)(?|.*\K\1(?=.*\1(.*)$)|(.*)\1.*)/$2/&&redo;s; ;

```

Try it online!
> 2 votes

# Answer
# Java 10, ~~121~~ ~~101~~ 99 bytes

```
a->s->{int i;for(var c:a)s=s.substring(0,i=s.lastIndexOf(c)).replace(c,s.substring(i+1));return s;}

```

-17 bytes (and an additional -3 implicit) thanks to *@NahuelFouilleul* by using `substring`s instead of `split` to an array.
-2 bytes thanks to *@ceilingcat*.

Try it online.

**Explanation:**

```
a->s->{                    // Method with String-array & String parameters and String return
  int i;                   //  Index-integer `i`, starting uninitialized
  for(var c:a)             //  Loop over the input-characters:
    s=                     //   Overwrite String `s` with:
      s.substring(0,i=s.lastIndexOf(c))
                           //    A substring until (excluding) the last occurrence of the
                           //    current character (and also set `i` to this last index
                           //    of the character at the same time)
       .replace(c,         //    From which the current character is replaced with
         s.substring(i+1));//    the trailing substring after index `i`
  return s;}               //  Return the modified `s` as result-String

```
> 2 votes

# Answer
# Go, 121 bytes

```
import."strings"
type S=string
func f(s,c S)S{for _,r:=range c{L:=Split(s,S(r))
l:=len(L)-1
s=Join(L[:l],L[l])}
return s}

```

Attempt This Online!
> 2 votes

# Answer
# Charcoal, 16 bytes

```
Ｆη«≔⪪θιυ≔⪫υ⊟υθ»θ

```

Try it online! Link is to verbose version of code. Explanation: Charcoal doesn't have a good way to refer to the split string twice, so it costs a block and an assignment.

```
Ｆη«

```

Loop over the list of characters.

```
≔⪪θιυ

```

Split the string.

```
≔⪫υ⊟υθ

```

Join it on the popped element.

```
»θ

```

Output the final result.
> 1 votes

# Answer
# Python, 59 bytes

```
lambda x,y:[x:=(z:=x.split(i)).pop().join(z)for i in y][-1]

```

Attempt This Online!
> 1 votes

# Answer
# , 95 bytes

```
f=\(s,L,`?`=length,x=el(strsplit(s,L[1],T)),t=?x)`if`(?L,f(paste(x[-t],collapse=x[t]),L[-1]),s)

```

Attempt This Online!
> 1 votes

# Answer
# Haskell, 89 85 bytes

```
f=foldl(\s c->(\(a,b)->reverse$tail b>>=(\x->last$[x]:[a|x==c])).span(c/=)$reverse s)

```

Try it online!
> 1 votes

# Answer
# , 81 bytes

```
\(x,y)Reduce(\(x,y)paste(head(a<-el(strsplit(x,y,T)),-1),collapse=tail(a,1)),y,x)

```

Attempt This Online!

Port of unrelated string's Jelly answer.
> 1 votes

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


title: Invalid Invali Inval

text:
# Question
Title: Invalid Invali Inval
This idea is loosely based upon @TùxCräftîñg's chat message.

Take a look at the below example sequence:

`INVALID0`, `INVALID1`, `INVALID2` `INVALID3`, `INVALID4`... `INVALID9`

After `INVALID9`, it goes on like this:

`INVALI0`, `INVALI1`, `INVALI2`, `INVALI3`... `INVALI9`

And after `INVALI9`, it's like this:

`INVAL0`,`INVAL1`, `INVAL2`, `INVAL3`... `INVAL9`

After, `INVAL9`, it's like this:

`INVA0`, `INVA1`, `INVA2`, `INVA3`, ... `INVA9`

Notice how we we kept removing a letter from the word `INVALID` each time.

You'll keep repeating this until you reach a single letter, that is, the letter `I`:

`I0`, `I1`, `I2`, `I3`, `I4` ... `I9`

Now, your task is, to take an input of a word, and produce a sequence from it like the above example. Your code must also work with single letters, and in that case the resulting sequence will be shorter.

You may choose any input and output format that you prefer (with or without a separator, as you wish), but you must specify which one you have chosen.

The sequence needs to be in the exact specified order.

The shortest code, in bytes, that successfully completes this challenge, wins the challenge.

Full sequence in the above example:

```
INVALID0, INVALID1, INVALID2, INVALID3, INVALID4, INVALID5, INVALID6, INVALID7, INVALID8, INVALID9, INVALI0, INVALI1, INVALI2, INVALI3, INVALI4, INVALI5, INVALI6, INVALI7, INVALI8, INVALI9, INVAL0, INVAL1, INVAL2, INVAL3, INVAL4, INVAL5, INVAL6, INVAL7, INVAL8, INVAL9, INVA0, INVA1, INVA2, INVA3, INVA4, INVA5, INVA6, INVA7, INVA8, INVA9, INV0, INV1, INV2, INV3, INV4, INV5, INV6, INV7, INV8, INV9, IN0, IN1, IN2, IN3, IN4, IN5, IN6, IN7, IN8, IN9, I0, I1, I2, I3, I4, I5, I6, I7, I8, I9

```

Other examples:

Input: `MAYBE` (Uppercase and lowercase don't matter)

Output:

```
MAYBE0, MAYBE1, MAYBE2, MAYBE3, MAYBE4, MAYBE5, MAYBE6, MAYBE7, MAYBE8, MAYBE9, MAYB0, MAYB1, MAYB2, MAYB3, MAYB4, MAYB5, MAYB6, MAYB7, MAYB8, MAYB9, MAY0, MAY1, MAY2, MAY3, MAY4, MAY5, MAY6, MAY7, MAY8, MAY9, MA0, MA1, MA2, MA3, MA4, MA5, MA6, MA7, MA8, MA9, M0, M1, M2, M3, M4, M5, M6, M7, M8, M9

```

---

---

Input: `AFTER`

Output:

```
AFTER0, AFTER1, AFTER2, AFTER3, AFTER4, AFTER5, AFTER6, AFTER7, AFTER8, AFTER9, AFTE0, AFTE1, AFTE2, AFTE3, AFTE4, AFTE5, AFTE6, AFTE7, AFTE8, AFTE9, AFT0, AFT1, AFT2, AFT3, AFT4, AFT5, AFT6, AFT7, AFT8, AFT9, AF0, AF1, AF2, AF3, AF4, AF5, AF6, AF7, AF8, AF9, A0, A1, A2, A3, A4, A5, A6, A7, A8, A9

```

---

---

Input: `WHAT ARE YOU DOING`

```
WHAT ARE YOU DOING0, WHAT ARE YOU DOING1, WHAT ARE YOU DOING2, WHAT ARE YOU DOING3, WHAT ARE YOU DOING4, WHAT ARE YOU DOING5, WHAT ARE YOU DOING6, WHAT ARE YOU DOING7, WHAT ARE YOU DOING8, WHAT ARE YOU DOING9, WHAT ARE YOU DOIN0, WHAT ARE YOU DOIN1, WHAT ARE YOU DOIN2, WHAT ARE YOU DOIN3, WHAT ARE YOU DOIN4, WHAT ARE YOU DOIN5, WHAT ARE YOU DOIN6, WHAT ARE YOU DOIN7, WHAT ARE YOU DOIN8, WHAT ARE YOU DOIN9, WHAT ARE YOU DOI0, WHAT ARE YOU DOI1, WHAT ARE YOU DOI2, WHAT ARE YOU DOI3, WHAT ARE YOU DOI4, WHAT ARE YOU DOI5, WHAT ARE YOU DOI6, WHAT ARE YOU DOI7, WHAT ARE YOU DOI8, WHAT ARE YOU DOI9, WHAT ARE YOU DO0, WHAT ARE YOU DO1, WHAT ARE YOU DO2, WHAT ARE YOU DO3, WHAT ARE YOU DO4, WHAT ARE YOU DO5, WHAT ARE YOU DO6, WHAT ARE YOU DO7, WHAT ARE YOU DO8, WHAT ARE YOU DO9, WHAT ARE YOU D0, WHAT ARE YOU D1, WHAT ARE YOU D2, WHAT ARE YOU D3, WHAT ARE YOU D4, WHAT ARE YOU D5, WHAT ARE YOU D6, WHAT ARE YOU D7, WHAT ARE YOU D8, WHAT ARE YOU D9, WHAT ARE YOU 0, WHAT ARE YOU 1, WHAT ARE YOU 2, WHAT ARE YOU 3, WHAT ARE YOU 4, WHAT ARE YOU 5, WHAT ARE YOU 6, WHAT ARE YOU 7, WHAT ARE YOU 8, WHAT ARE YOU 9, WHAT ARE YOU0, WHAT ARE YOU1, WHAT ARE YOU2, WHAT ARE YOU3, WHAT ARE YOU4, WHAT ARE YOU5, WHAT ARE YOU6, WHAT ARE YOU7, WHAT ARE YOU8, WHAT ARE YOU9, WHAT ARE YO0, WHAT ARE YO1, WHAT ARE YO2, WHAT ARE YO3, WHAT ARE YO4, WHAT ARE YO5, WHAT ARE YO6, WHAT ARE YO7, WHAT ARE YO8, WHAT ARE YO9, WHAT ARE Y0, WHAT ARE Y1, WHAT ARE Y2, WHAT ARE Y3, WHAT ARE Y4, WHAT ARE Y5, WHAT ARE Y6, WHAT ARE Y7, WHAT ARE Y8, WHAT ARE Y9, WHAT ARE 0, WHAT ARE 1, WHAT ARE 2, WHAT ARE 3, WHAT ARE 4, WHAT ARE 5, WHAT ARE 6, WHAT ARE 7, WHAT ARE 8, WHAT ARE 9, WHAT ARE0, WHAT ARE1, WHAT ARE2, WHAT ARE3, WHAT ARE4, WHAT ARE5, WHAT ARE6, WHAT ARE7, WHAT ARE8, WHAT ARE9, WHAT AR0, WHAT AR1, WHAT AR2, WHAT AR3, WHAT AR4, WHAT AR5, WHAT AR6, WHAT AR7, WHAT AR8, WHAT AR9, WHAT A0, WHAT A1, WHAT A2, WHAT A3, WHAT A4, WHAT A5, WHAT A6, WHAT A7, WHAT A8, WHAT A9, WHAT 0, WHAT 1, WHAT 2, WHAT 3, WHAT 4, WHAT 5, WHAT 6, WHAT 7, WHAT 8, WHAT 9, WHAT0, WHAT1, WHAT2, WHAT3, WHAT4, WHAT5, WHAT6, WHAT7, WHAT8, WHAT9, WHA0, WHA1, WHA2, WHA3, WHA4, WHA5, WHA6, WHA7, WHA8, WHA9, WH0, WH1, WH2, WH3, WH4, WH5, WH6, WH7, WH8, WH9, W0, W1, W2, W3, W4, W5, W6, W7, W8, W9

```

### Leaderboard

```
var QUESTION_ID=92156,OVERRIDE_USER=58717;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 5 votes
# Jelly, 7 bytes

```
ḣJṚp⁵Ḷ¤

```

Try it online!

### How it works

```
ḣJṚp⁵Ḷ¤  Main link. Argument: s (string)

 J       Yield all (1-based) indices of s.
ḣ        Head; for each index k, take the first k characters of s.
  Ṛ      Reverse the result.
      ¤  Combine the two links to the left into a niladic chain.
    ⁵      Yield 10.
     Ḷ     Unlength; yield [0, ..., 9].
   p     Return the Cartesian product of the prefixes and the range.
         (implicit) Print the Cartesian product without separators.

```

# Answer
> 9 votes
## Javascript (ES6), ~~53~~ 47 bytes

```
f=(s,n=0)=>s&&s+n+f(n-9?s:s.slice(0,-1),++n%10)

```

*Saved 6 bytes thanks to Peanut & Neil*

Output: all words as a single string with no separator.

### Example

```
var f=(s,n=0)=>s&&s+n+f(n-9?s:s.slice(0,-1),++n%10)

document.getElementsByTagName('div')[0].innerHTML = f('INVALID')
```

```
<div style="word-wrap:break-word"></div>
```

# Answer
> 8 votes
# 05AB1E, ~~10~~ 8 bytes

```
.pžmâ€JR

```

**Explanation**

```
.p        # get prefixes of input
  žmâ     # cartesian product with [9..0]
     €J   # join each
       R  # reverse

```

Try it online!

Saved 2 bytes thanks to Adnan

# Answer
> 7 votes
# Perl, 29 bytes

Includes +1 for `-n`

Run with input on STDIN:

```
perl -nE '/^.+(?{map{say$&.$_}0..9})^/' <<< PERL

```

Just the code:

```
/^.+(?{map{say$&.$_}0..9})^/

```

# Answer
> 6 votes
## Haskell, ~~47~~ 43 bytes

```
f""=[]
f x=map((x++).show)[0..9]++f(init x)

```

Usage example: `f "IN"` -\> `["IN0","IN1","IN2","IN3","IN4","IN5","IN6","IN7","IN8","IN9","I0","I1","I2","I3","I4","I5","I6","I7","I8","I9"]`.

Simple recursive approach. Append each digit to the word and append a recursive call with last letter removed.

# Answer
> 6 votes
# Pyth, 9 bytes

```
sM*_._QUT

```

A program that takes input of a quoted string on STDIN and prints a list of strings.

Try it online

**How it works**

```
sM*_._QUT  Program. Input: Q
    ._     List of prefixes of Q
   _       Reverse
       UT  Unary range up to 10, yielding [0, 1, 2, ..., 9]
  *        Cartesian product of the above two
sM         Map concatenate over the above
           Implicitly print

```

# Answer
> 5 votes
## Pip, ~~12~~ 11 bytes

Takes the word as a cmdline argument. Outputs with no separators.

```
Wa&Oa.,tDQa

```

Try it online!

Explanation:

```
             Implicit: a = 1st cmdline arg, t = 10
Wa           While a (i.e. while it's not the empty string)
   Oa.,t     Concatenate range(10) to a and output
               (Pip concatenates a string to a range itemwise)
  &          The output operation is &-ed to the loop condition to save on curly braces
        DQa  Dequeue from a, removing the final character on each iteration

```

# Answer
> 4 votes
# , 20 bytes

```
A0òYpó.10/0/e
$hòd

```

Try it online!

Since this contains unprintable characters, here is the readable format:

```
A0<esc>òYp<C-a>ó.10/0/e
$hòd

```

And here is a hexdump:

```
0000000: 4130 1bf2 5970 01f3 2e31 302f 302f 650a  A0..Yp...10/0/e.
0000010: 2468 f264                                $h.d

```

Explanation:

```
A0<esc>                 "Append a '0' to the input
       ò                "Recursively:
        Yp              "  Yank this line and paste it
          <C-a>         "  Increment the first number on this line
               ó        "  Substitute:
                .10     "    Any single character followed by '10'
                   /0   "    Replace it with a '0'
                     /e "    Ignore errors if this is not found
$h                      "  Move to the end of the end of this line than back one.
                        "  This makes it so the loop ends once there is only one
                        "  character on this line.
  ò                     "End the loop
   d                    "Delete a line (since we create one too many)

```

# Answer
> 4 votes
# Floroid \- 50 47 31 bytes

```
f=Ba:aM[a+b KbIhd]+f(a[:-1])H[]

```

Currently uses a similar method as @JonathanAllan uses on his second recursive method.

Could've been this if I would've implemented the cartesian product more carefully in the language: `Bc:ca([c]+[c[:-a-1]KaIw(Z(c)-1)],hd)`.

## Testcases

```
Input: ABC
Output: ['ABC0', 'ABC1', 'ABC2', 'ABC3', 'ABC4', 'ABC5', 'ABC6', 'ABC7', 'ABC8', 'ABC9', 'AB0', 'AB1', 'AB2', 'AB3', 'AB4', 'AB5', 'AB6', 'AB7', 'AB8', 'AB9', 'A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9']

Input: M
Output: ['M0', 'M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9']

```

# Answer
> 4 votes
# Bash + coreutils, 54 bytes:

```
for i in `seq ${#1} 1`;{ printf "${1:0:i}%s " {0..9};}

```

Simply loops through a sequence `[Length of Input,1]` and during each iteration, outputs the input word to the length of current iteration value `9` times with each number in `[0,9]` appended to each of the `9` copies of the word. Execute it within a file and the word or words in quotes, i.e. `bash A.sh "blah blah blah"`.

# Answer
> 3 votes
# braingasm, ~~34~~ ~~33~~ ~~31~~ 28 bytes

At its current state, braingasm is just glorified brainfuck with a few (*like, 3?*) extra features. I've been spending most of the development time making it as "enterprisy" as possible, instead of actually adding features...

Anyways, the following code should work with the latest development snapshot. It takes newline-less input from stdin, like `$ echo -n INVALID | braingasm invalid.bg`, and prints to stdout.

```
,[>,]#[48+10[#<[.>]<+]0,<0,]

```

Explanation:

```
,[>,]                 lay down the input on the tape
#[                    (length of input - 1) times do
  48+                   add '0' at the end of the tape
  10[                   10 times do
     #<[.>]               move to start of tape, then print the tape
     <+                   increase the number at the end of the tape
  ]                     done printing current word with 0 through 9
  0,                    erase the number by writing 0 onto it
  <0,                   likewise, remove one character
]                     done

```

edit: Appearantly it's OK to ~~skip~~ use empty string as the delimiter

# Answer
> 3 votes
# (lambdabot) Haskell - 49 bytes

```
f q=[x++show n|x<-reverse.tail$inits q,n<-[0..9]]

```

Lambdabot is a IRC bot over at #haskell; it automatically imports a bunch of modules, including `Data.List` which is where `inits` live. And because a language is defined by its implementation, I can call this lambdabot haskell and not pay the bytes for the imports.
Regular Haskell:

```
import Data.List
f q=[x++show n|x<-reverse.tail$inits q,n<-[0..9]]

```

# Answer
> 2 votes
# Python 2, ~~53~~ 55 bytes

+2 bytes: declaring f is necessary with recursion (as pointed out by @Destructible Watermelon)

```
f=lambda s:s and[s+`n`for n in range(10)]+f(s[:-1])or[]

```

Recurses down to the empty string (yielding an empty list), chops off a character at a time, and prepends with a list of ten of the current string with the digits 0-9 appended to each.

Test on **ideone**

**Python 3, ~~54~~ 56 bytes**

```
f=lambda s:s and[s+n for n in'0123456789']+f(s[:-1])or[]

```

Test on **ideone**

# Answer
> 2 votes
# Swift 3, 150 Bytes

Not quite the shortest solution, but not terrible for Swift

```
func a(s: String){var c=s.characters,r="";while(c.count>0){var k = "";for d in c{k+=String(d)};for i in 0...9{r+="\(k)\(i) "};c.removeLast()};print(r);}

```

Test this online in the IBM Swift Sandbox

### Ungolfed

```
func a(s s: String){
    var c = s.characters, r = ""
    while(c.count > 0){
        var k = ""
        for d in c{
            k+=String(d)
        }
        for i in 0...9{
            r+="\(k)\(i) "
        }
        c.removeLast()
    }
    print(r)
}

```

# Answer
> 2 votes
## Batch, ~~85~~ 83 bytes

```
@for /l %%i in (0,1,9)do @echo %1%%i
@set s=%1
@if not "%s:~,-1%"=="" %0 %s:~,-1%

```

# Answer
> 2 votes
## Ruby, ~~90~~ 85 bytes

```
f=->s{if s=="";return[];end;(0..9).map{|i|s+i.to_s}+f[s.chars.take(s.length-1).join]}

```

If the string is empty, return a empty array. Otherwise, generate the string + the number in each number from 0 to 9, and call `f` with the string without the last character.

Saved 5 bytes thanks to @LevelRiverSt

# Answer
> 2 votes
# Ruby, 51

No separator used.

```
->s{(10*n=s.size).times{|i|print s[0,n-i/10],i%10}}

```

Add the following after `i%10` for separators:

`,$/` for newline, `,?|` for `|`  (similar for any printable character), `,' '` for space.

**In test program**

```
f=->s{(10*n=s.size).times{|i|print s[0,n-i/10],i%10}}

f[gets.chomp]

```

# Answer
> 2 votes
# PHP, ~~64~~ 56 bytes

```
for($i=9;$a=substr($argv[1].a,0,-++$i/10);)echo$a.$i%10;

```
~~```
for(;$a=substr($argv[1].a,$i=0,-++$l);)for(;$i<10;)echo $a.$i++;

```~~

# Answer
> 2 votes
# Java 7, ~~105~~ 98 bytes

```
void c(String s){for(int x=0,l=s.length();x<l*10;)System.out.print(s.substring(0,l-x/10)+x++%10);}

```

-7 bytes thanks to *@Poke*.

**Ungolfed**:

```
void c(String s){
  for(int x = 0, l = s.length(); x < l*10; ){
    System.out.print(s.substring(0, l - x/10) + x++ % 10);
  }
}

```

**Test code:**

Try it here.

```
class M{
  static void c(String s){for(int x=0,l=s.length();x<l*10;)System.out.print(s.substring(0,l-x/10)+x++%10);}

  public static void main(String[] a){
    c("INVALID");
    System.out.println();
    c("MAYBE");
    System.out.println();
    c("AFTER");
    System.out.println();
    c("WHAT ARE YOU DOING");
  }
}

```

**Output:**

```
INVALID0INVALID1INVALID2INVALID3INVALID4INVALID5INVALID6INVALID7INVALID8INVALID9INVALID0INVALID1INVALID2INVALID3INVALID4INVALID5INVALID6INVALID7INVALID8INVALID9INVALI0INVALI1INVALI2INVALI3INVALI4INVALI5INVALI6INVALI7INVALI8INVALI9INVAL0INVAL1INVAL2INVAL3INVAL4INVAL5INVAL6INVAL7INVAL8INVAL9INVA0INVA1INVA2INVA3INVA4INVA5INVA6INVA7INVA8INVA9INV0INV1INV2INV3INV4INV5INV6INV7INV8INV9IN0IN1IN2IN3IN4IN5IN6IN7IN8IN9I0I1I2I3I4I5I6I7I8I9
MAYBE0MAYBE1MAYBE2MAYBE3MAYBE4MAYBE5MAYBE6MAYBE7MAYBE8MAYBE9MAYBE0MAYBE1MAYBE2MAYBE3MAYBE4MAYBE5MAYBE6MAYBE7MAYBE8MAYBE9MAYB0MAYB1MAYB2MAYB3MAYB4MAYB5MAYB6MAYB7MAYB8MAYB9MAY0MAY1MAY2MAY3MAY4MAY5MAY6MAY7MAY8MAY9MA0MA1MA2MA3MA4MA5MA6MA7MA8MA9M0M1M2M3M4M5M6M7M8M9
AFTER0AFTER1AFTER2AFTER3AFTER4AFTER5AFTER6AFTER7AFTER8AFTER9AFTER0AFTER1AFTER2AFTER3AFTER4AFTER5AFTER6AFTER7AFTER8AFTER9AFTE0AFTE1AFTE2AFTE3AFTE4AFTE5AFTE6AFTE7AFTE8AFTE9AFT0AFT1AFT2AFT3AFT4AFT5AFT6AFT7AFT8AFT9AF0AF1AF2AF3AF4AF5AF6AF7AF8AF9A0A1A2A3A4A5A6A7A8A9
WHAT ARE YOU DOING0WHAT ARE YOU DOING1WHAT ARE YOU DOING2WHAT ARE YOU DOING3WHAT ARE YOU DOING4WHAT ARE YOU DOING5WHAT ARE YOU DOING6WHAT ARE YOU DOING7WHAT ARE YOU DOING8WHAT ARE YOU DOING9WHAT ARE YOU DOING0WHAT ARE YOU DOING1WHAT ARE YOU DOING2WHAT ARE YOU DOING3WHAT ARE YOU DOING4WHAT ARE YOU DOING5WHAT ARE YOU DOING6WHAT ARE YOU DOING7WHAT ARE YOU DOING8WHAT ARE YOU DOING9WHAT ARE YOU DOIN0WHAT ARE YOU DOIN1WHAT ARE YOU DOIN2WHAT ARE YOU DOIN3WHAT ARE YOU DOIN4WHAT ARE YOU DOIN5WHAT ARE YOU DOIN6WHAT ARE YOU DOIN7WHAT ARE YOU DOIN8WHAT ARE YOU DOIN9WHAT ARE YOU DOI0WHAT ARE YOU DOI1WHAT ARE YOU DOI2WHAT ARE YOU DOI3WHAT ARE YOU DOI4WHAT ARE YOU DOI5WHAT ARE YOU DOI6WHAT ARE YOU DOI7WHAT ARE YOU DOI8WHAT ARE YOU DOI9WHAT ARE YOU DO0WHAT ARE YOU DO1WHAT ARE YOU DO2WHAT ARE YOU DO3WHAT ARE YOU DO4WHAT ARE YOU DO5WHAT ARE YOU DO6WHAT ARE YOU DO7WHAT ARE YOU DO8WHAT ARE YOU DO9WHAT ARE YOU D0WHAT ARE YOU D1WHAT ARE YOU D2WHAT ARE YOU D3WHAT ARE YOU D4WHAT ARE YOU D5WHAT ARE YOU D6WHAT ARE YOU D7WHAT ARE YOU D8WHAT ARE YOU D9WHAT ARE YOU 0WHAT ARE YOU 1WHAT ARE YOU 2WHAT ARE YOU 3WHAT ARE YOU 4WHAT ARE YOU 5WHAT ARE YOU 6WHAT ARE YOU 7WHAT ARE YOU 8WHAT ARE YOU 9WHAT ARE YOU0WHAT ARE YOU1WHAT ARE YOU2WHAT ARE YOU3WHAT ARE YOU4WHAT ARE YOU5WHAT ARE YOU6WHAT ARE YOU7WHAT ARE YOU8WHAT ARE YOU9WHAT ARE YO0WHAT ARE YO1WHAT ARE YO2WHAT ARE YO3WHAT ARE YO4WHAT ARE YO5WHAT ARE YO6WHAT ARE YO7WHAT ARE YO8WHAT ARE YO9WHAT ARE Y0WHAT ARE Y1WHAT ARE Y2WHAT ARE Y3WHAT ARE Y4WHAT ARE Y5WHAT ARE Y6WHAT ARE Y7WHAT ARE Y8WHAT ARE Y9WHAT ARE 0WHAT ARE 1WHAT ARE 2WHAT ARE 3WHAT ARE 4WHAT ARE 5WHAT ARE 6WHAT ARE 7WHAT ARE 8WHAT ARE 9WHAT ARE0WHAT ARE1WHAT ARE2WHAT ARE3WHAT ARE4WHAT ARE5WHAT ARE6WHAT ARE7WHAT ARE8WHAT ARE9WHAT AR0WHAT AR1WHAT AR2WHAT AR3WHAT AR4WHAT AR5WHAT AR6WHAT AR7WHAT AR8WHAT AR9WHAT A0WHAT A1WHAT A2WHAT A3WHAT A4WHAT A5WHAT A6WHAT A7WHAT A8WHAT A9WHAT 0WHAT 1WHAT 2WHAT 3WHAT 4WHAT 5WHAT 6WHAT 7WHAT 8WHAT 9WHAT0WHAT1WHAT2WHAT3WHAT4WHAT5WHAT6WHAT7WHAT8WHAT9WHA0WHA1WHA2WHA3WHA4WHA5WHA6WHA7WHA8WHA9WH0WH1WH2WH3WH4WH5WH6WH7WH8WH9W0W1W2W3W4W5W6W7W8W9

```

# Answer
> 2 votes
# C#, ~~107~~ 102 Bytes

```
string f(string i){var o="";while(i!=""){for(int k=0;k<=9;)o+=i+k++;i=i.Remove(i.Length-1);}return o;}

```

**Ungolfed**

```
string f(string i)
{
   string o = "";
   while(i != "")
   {
      for (int k = 0; k <= 9;)
         o += i + k++;
      i = i.Remove(i.Length - 1);
   }
   return o;
}

```

# Answer
> 2 votes
## Haskell, ~~49~~ 46 bytes

```
f=(>>=(<$>['0'..'9']).snoc).reverse.tail.inits

```

# Answer
> 2 votes
# Dyalog APL, ~~14~~ 11 bytes

Returns list of strings.

```
,⎕D∘.,⍨⌽,\⍞

```

`,` listify (make table into list)

`⎕D` all digits

`∘.,⍨` appended to all of (i.e. making all combinations with)

the reversed list of

`,\` the cumulative concatenation of

the text input

TryAPL online!

# Answer
> 2 votes
## Perl 6, 32 = 31 bytes + 1 for -p

I'm not all that proficient with Perl 6, so there may be ways to reduce it even more.

```
$_= ~((~$_,*.chop...^!*)X~ ^10)

```

It uses `-p` to evaluate once for each input line. The line is placed into `$_` and after the program runs, it prints `$_`.

The `(~$_,*.chop...^!*)` is a list where the first element is stringified (`~`) input, each subsequent element is obtained by chopping the last character off the previous one (`*.chop`) and that continues until the string is empty (`!*`), excluding the empty string case (the `^` in `...^`).

`X~` generates all pairs of the lists on the left and right, using the specified operation, in this case, the string concatenation (`~`) on them. `^10` is a list of 0, 1, ... 9.

Finally, the list is stringified again with `~`, giving the required words with space as a separator.

# Answer
> 2 votes
## PowerShell v2+, 60 bytes

```
param($n)$n.length..1|%{$i=$_-1;0..9|%{-join$n[0..$i]+"$_"}}

```

Loops from the length of the input string down to `1`. Each iteration, set helper `$i` equal to the current number minus `1`. This is necessary because `.length` is the total number of characters, but indexing a string is 0-based. Then, we loop from `0` to `9`. Each inner loop, slice the input string `$n` based on the value of our outer loop, `-join` it back into a string, and string-concatenate on the inner loop count. Each individual loop result is placed on the pipeline, and output is implicit at program completion.

```
PS C:\Tools\Scripts\golfing> .\invalid-invali-inval.ps1 'foo'
foo0
foo1
foo2
foo3
foo4
foo5
foo6
foo7
foo8
foo9
fo0
fo1
fo2
fo3
fo4
fo5
fo6
fo7
fo8
fo9
f0
f1
f2
f3
f4
f5
f6
f7
f8
f9

```

# Answer
> 2 votes
# Groovy (58 Bytes)

No idea why I'm even bothering to post a Groovy answer... The minimum required size for a Groovy golf is 2 based on needing a closure, so the best answer here is double my minimum size.

```
   {s->(s.length()-1..0).each{c->10.times{print s[0..c]+it}}}

```

Try it here: https://groovyconsole.appspot.com/script/5148433803378688

# Answer
> 1 votes
# Python 3, 62 bytes

```
lambda x:[(x+" ")[:~i//10]+str(i%10)for i in range(len(x)*10)]

```

Doesn't use recursion like the other answer.

The reason the " " in `x+" "` is there: -0 is still zero, and so we can't use minus notation to get all of the string in this way so the highest we can go is minus one, so the " " is to pad the string,

# Answer
> 1 votes
# C, ~~72~~, 70 bytes

```
j;F(char*s,int l){while(l--)for(j=0;j<10;)printf("%.*s%d",l+1,s,j++);}

```

Takes strings as pointer/size pairs. Test main:

```
int main() {
  F("INVALID", 7); putchar('\n');
  F("MAYBE", 5); putchar('\n');
  F("AFTER", 5); putchar('\n');
  F("WHAT ARE YOU DOING", 18); putchar('\n');
}

```

# Answer
> 1 votes
# Retina, 37 bytes

Byte count assumes ISO 8859-1 encoding.

```
M&!r`.+
m`$
0
%{`$
¶$%`
T`w`d`.$
G10`

```

Try it online!

### Explanation

```
M&!r`.+

```

Get all prefixes of the input by matching and printing all overlapping matches from the right.

```
m`$
0

```

Append a `0` to each line.

```
%{`$
¶$%`

```

The `{` indicates that the remaining three stages are executed in a loop until they fail to change the string. The `%` says that they should be applied to each line separately.

The stage itself simply duplicates the last line (initially this is just the line this is run on, but each iteration of the three stages adds another line).

```
T`w`d`.$

```

Increment the digit in the last row by performing the following character substitution:

```
from: _0123456789AB...
to:   0123456789

```

And finally:

```
G10`

```

Keep only the first 10 lines, so that we remove the line we just added after `INPUT9`.

# Answer
> 1 votes
# Racket 113 bytes

```
(λ(s)(let((n(string-length s)))(for*/list((i n)(j 10))(string-append(substring s 0(- n i))(number->string j)))))

```

More readable form:

```
(define(f s)
  (let ((n (string-length s)))
  (for*/list ((i n)(j 10))
    (string-append
     (substring s 0(- n i))
     (number->string j)))))

```

Usage:

```
(f "Invalid")
'("Invalid0"
  "Invalid1"
  "Invalid2"
  "Invalid3"
  "Invalid4"
  "Invalid5"
  "Invalid6"
  "Invalid7"
  "Invalid8"
  "Invalid9"
  "Invali0"
  "Invali1"
  "Invali2"
  "Invali3"
  "Invali4"
  "Invali5"
  "Invali6"
  "Invali7"
  "Invali8"
  "Invali9"
  "Inval0"
  "Inval1"
  "Inval2"
  "Inval3"
  "Inval4"
  "Inval5"
  "Inval6"
  "Inval7"
  "Inval8"
  "Inval9"
  "Inva0"
  "Inva1"
  "Inva2"
  "Inva3"
  "Inva4"
  "Inva5"
  "Inva6"
  "Inva7"
  "Inva8"
  "Inva9"
  "Inv0"
  "Inv1"
  "Inv2"
  "Inv3"
  "Inv4"
  "Inv5"
  "Inv6"
  "Inv7"
  "Inv8"
  "Inv9"
  "In0"
  "In1"
  "In2"
  "In3"
  "In4"
  "In5"
  "In6"
  "In7"
  "In8"
  "In9"
  "I0"
  "I1"
  "I2"
  "I3"
  "I4"
  "I5"
  "I6"
  "I7"
  "I8"
  "I9")

```

# Answer
> 1 votes
# Scala, 73 70 bytes

```
def g(s:String):String=if(s=="")""else(0 to 9 flatMap(s+_))++g(s.init)

```

Call it like `f("INVALID")`. Returns a Sequence of Chars.

### Explanation

```
def g(s:String):String= //defines a method g taking a String as a parameter
                        //and returning a String
if(s=="")""             //guard to prevent infinite recursion
else
    (0 to 9             //create a Range from 0 to 9 (inclusive)
    flatMap(            //map:
        s+_                 //append each number to the string
    ))                  //and flatten
    ++ g(s.init)        //concatenate with g applied to everything but the last element of s

```

## Alternative solution, 73 bytes

```
(s:String)=>s.scanLeft("")(_+_).tail.reverse.flatMap(x=>(0 to 9)map(x+_))

```

defines an anonymous function. To call it, write

```
val f = ...

```

and call it like this

```
f("INVALID")

```

It returns a sequence of strings, which will look like this when printed:

```
Vector(INVALID0, INVALID1, INVALID2, INVALID3, INVALID4, INVALID5, INVALID6, INVALID7, INVALID8, INVALID9, INVALI0, INVALI1, INVALI2, INVALI3, INVALI4, INVALI5, INVALI6, INVALI7, INVALI8, INVALI9, INVAL0, INVAL1, INVAL2, INVAL3, INVAL4, INVAL5, INVAL6, INVAL7, INVAL8, INVAL9, INVA0, INVA1, INVA2, INVA3, INVA4, INVA5, INVA6, INVA7, INVA8, INVA9, INV0, INV1, INV2, INV3, INV4, INV5, INV6, INV7, INV8, INV9, IN0, IN1, IN2, IN3, IN4, IN5, IN6, IN7, IN8, IN9, I0, I1, I2, I3, I4, I5, I6, I7, I8, I9)

```

### Explanation

```
s.scanLeft("")(_+_)    //accumulate letters from left to right -> Vector("", "I", "IN", "INV", "INVA", "INVAL", "INVALI", "INVALID")
.tail                  //drop the first element
.reverse               //reverse it
.flatMap(x =>          //map each element called x
    (0 to 9)           //create a Range from 0 to 9 (inclusive)
    map(x+_)           //append each number to x
)                      //and flatten

```

# Answer
> 1 votes
# CJam, ~~29~~ 28 bytes

```
ls_,,:)W%]~{_[X<aA*A,]zo}fX;

```

Explanation:

```
ls                              read input as string
  _                             duplicate input
   ,,                           create range of length input
      :)W%]                     add 1 to all elements and reverse
           ~                    dump array on stack
            {            }fX    for loop
             _                  duplicate input string
              [X<aA*            slice input string and multiply by 10
                    A,]         range(10)
                       zo       zip array and print (no separator)
                            ;   clear stack

```

Try it online

# Answer
> 1 votes
# sed 107

```
s/$/HH/;:;s/..$/0/p;s/.$/1/p;s/.$/2/p;s/.$/3/p;s/.$/4/p
s/.$/5/p;s/.$/6/p;s/.$/7/p;s/.$/8/p;s/.$/9/p;/.../b

```

# Answer
> 1 votes
# Brainf\*ck, 217 bytes

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

```

Not really a competitive entry, I just wanted to see if I could do it. Not a trivial brainf\*ck program! Nested conditionals and all. It prints the output separated by newlines instead of comma, space. Here's my annotated version:

```
[
    We'll have a string in the first n positions on the tape.
    One after the end of the string, we'll put a 48 '0' and do a loop adding
    1 to it 9 times, then loop back and delete the last letter of the string.
]

>,[>,----------[++++++++++>]<]
[Read line of input and leave a 0 at the beginning to navigate back.]

>++++++++[<++++++>-]
>++++++++++[>+>+<<-]>>[<<+>>-]<<    we have {string} {48} {0} {10} {10}

Now we should have {string} {48} {0} {9}

[
    -<<[<]
    >[.>]
    <+>>>.<   printed out string and we're at the cell 3 past the end
    >>[-]+   put a 1 in the cell 2 to the right of this
    <<[>>-]  clear that cell if this one is not zero
    <[<]        sets us at the cell 2 after the end of the string (0)

    >>>
    [         If the cell we flagged is still flagged we counted all the way up
              to 9
        [-]   Clear the flag
        <<++++++++++        Add 10 back to the cell 3 off end of string
        <<----------        subtract 10 to get 48 in the last cell of string
                            again
        <[-]                Clear last cell in string

        <[[>+<-]<]
        [copy cells into the next one all the way down; entire string has been
         moved up one place now.]

        >>[>]     seek back to end of string
        >>>[-]+<<<<<    set a flag in the cell three after this (unused)
        [>>>>>[-]]      if there is a letter left clear the flag
        >[[>]>>>>]<     this line puts us at the cell with the flag no matter
                        what we did at the last line

        [               If the flag is set we're all out of string
            <<[-]>>[-]  Clear the 3rd cell past the end and the flag; pointer is
                        at the flag cell like it would have been if we never
                        entered the loop
        ]
    ]
    <<                  Puts us at the cell 3 after the end
]

```

Input is the string followed by optionally a newline (output is prettier) and then EOF.

# Answer
> 1 votes
# Vyxal, 7 bytes

```
¦₀ʁv+Ṙf

```

Try it Online!

```
¦       # Prefixes
   v+   # To each append
 ₀ʁ     # 0...9
     Ṙf # Reverse and flatten

```

# Answer
> 1 votes
# Factor, 74 bytes

```
[ head-clump reverse 10 repeat [ 10 mod number>string append ] map-index ]
```

Attempt This Online!

# Answer
> 1 votes
# Thunno 2, 6 bytes

```
ƒrıTL+

```

Try it online!

#### Explanation

```
ƒrıTL+  # Implicit input
ƒr      # Reversed prefixes
  ı     # Map:
   TL   #  Push [0..9]
     +  #  Concatenate
        # Implicit output

```

# Answer
> 1 votes
# Uiua (0.0.18), 56 bytes

```
;⊞(0&p⊂⊔)⇌∺(□↙∶)∶+1⇡⧻.∶+@0⇡10

```

Try it online!

**Explanation**:

```
                      ∶+@0⇡10  # create the string "0123456789" and put it below input
                 +1⇡⧻.         # create a range from 1 to the length of input, inclusive
          ∺(□↙∶)∶              # for each item in the range, take that many chars of input
 ⊞(     )⇌                     # for each possible (input_prefix, digit) pair,
   0&p⊂⊔                       # join them, print them, and then push a dummy value
;                              # pop the table of dummy values so it isn't printed

```

# Answer
> 1 votes
# Uiua, 18 bytes

```
♭⊠⍜⊔$"__"∶⇡10⇌\⍜⊔⊂

```

Try it!

```
♭⊠⍜⊔$"__"∶⇡10⇌\⍜⊔⊂
             ⇌\⍜⊔⊂  # reversed prefixes
          ⇡10       # 0..9
         :          # flip
 ⊠⍜⊔$"__"           # join each combination of pairs to a string
♭                   # deshape

```

# Answer
> 0 votes
## Clojure, 68 bytes

```
#(for[i(reverse(range(count %)))j(range 10)](str(subs % 0(inc i))j))

```

Plain boring `for`, couldn't make it shorter by `(iterate butlast %)` or others :/

# Answer
> 0 votes
## R, 72 bytes

Reads input from stdin and returns an R-vector of the desired output:

```
unname(unlist(lapply(Map(substr,x<-scan(,""),1,nchar(x):1),paste0,0:9)))

```

Example output for input `hello`:

```

 [1] "hello0" "hello1" "hello2" "hello3" "hello4" "hello5" "hello6" "hello7" "hello8" "hello9"
[11] "hell0"  "hell1"  "hell2"  "hell3"  "hell4"  "hell5"  "hell6"  "hell7"  "hell8"  "hell9"
[21] "hel0"   "hel1"   "hel2"   "hel3"   "hel4"   "hel5"   "hel6"   "hel7"   "hel8"   "hel9"
[31] "he0"    "he1"    "he2"    "he3"    "he4"    "he5"    "he6"    "he7"    "he8"    "he9"
[41] "h0"     "h1"     "h2"     "h3"     "h4"     "h5"     "h6"     "h7"     "h8"     "h9"

```

# Answer
> 0 votes
# Perl 6, 17 bytes

```
{m:ex/^.+/X~ ^10}

```

Try it online!

### How it works:

```
{               }  # A lambda
 m   /   /          # Apply a regex to the lambda argument,
      ^.+           #   matching prefixes of the string,
  :ex               #   with exhaustive matching (i.e. *all* possible prefixes).
             ^10    # Range from 0 to 9.
          X~        # Take the Cartesian product, and concatenate each result.

```

In case returning a list is not acceptable, this 20 byte version returns a space-separated string:

```
{~(m:ex/^.+/X~ ^10)}

```

# Answer
> 0 votes
# Python 3, ~~76~~ 73 bytes

```
s=input()
for i in range(len(s),0,-1):
 for j in range(10):print(s[:i],j)

```

Try it online!

# Answer
> 0 votes
# Retina, 28 bytes

Thanks to Martin for helping make it valid.

```
$
0
;{:G`
(?<=.).9
#
}T`#d`d

```

**Try it online**

# Answer
> 0 votes
# Python 2, 84 Bytes

Ah, the old nested merged list generator lambda-roo

```
c="".join
lambda s:c([c([s[:l]+`i`for i in range(10)])for l in range(len(s),0,-1)])

```

# Answer
> 0 votes
# Ruby `-n`, ~~37~~ 36 bytes

`-n` enables automatically reading input in a loop. `$_` stores the last line of input. Trailing newline is required.

`chop` is a function that's only available in `-n` or `-p` mode, which is equivalent to `$_.chop!` normally (it removes the last character from `$_` and returns the new value).

Conveniently for this problem, Ruby reads in the newline at the end of each line of input if `-l` is not specified, which allows the first `chop` in the loop to take it out instead of messing with the "actual" input.

```
puts (?0..?9).map{$_+_1}while''<chop

```

Attempt This Online!

---
Tags: code-golf, sequence
---


title: Golf a LaTeΧ math expression

text:
# Question
Title: Golf a LaTeΧ math expression
A problem I sometimes encounter is that when writing comments using LaTeX, the comment is too long. Today you will solve this, by writing code which, given a LaTeX math expression, will produce the shortest equivalent expression.

To define equivalent expressions, we will need to specify a (simplified) parser for LaTeX:

## Tokenizer

Given an expression, it is first processed by tokenizing it. To tokenize an expression, it is processed from left to right. Most characters are a token by themselves, except whitespaces which are ignored, and `\` which has special behavior - if it's followed by a non-letter character, then it and the character become a token. Otherwise, it and all following letters become a token.

For example, `\sum_{n \leq r^2} {\frac{v(n)}{n}} + \frac1n \in \{1,2,3\}` is tokenized as `\sum _ { n \leq r ^ 2 } { \frac { v ( n ) } { n } } + \frac 1 n \in \{ 1 , 2 , 3 \}` (with tokens seperated by a space).

## Parsing

If the `{` and `}` aren't validly matched, this is an invalid LaTeX equation. You can assume this won't be the case in the input. Now, to parse the LaTeX, we will look at the arity of each token. Most tokens have an arity of 0, and we will only have the following exceptions: `_`, `^`, and `\sqrt` (*note*: this isn't fully accurate for `_` and `^`, since they expect a subformula and not an argument, but we'll ignore this for simplicity's sake) have an arity of 1, and `\frac` has an arity of 2. Each token will bind a number of tokens as its arity, but tokens surrounded by `{` `}` are considered a single token for this purpose. For example, the above equation will bind as `\sum _({ n \leq r ^ 2 }) { \frac({ v ( n ) }, { n }) } + \frac(1, n) \in \{ 1 , 2 , 3 \}`.

Finally, all `{` and `}` are removed, so our parsed equation will become `\sum _(n \leq r ^ 2) \frac(v ( n ), n) + \frac(1, n) \in \{ 1 , 2 , 3 \}`.

We will say two expressions are equivalent if their parsed version is the same.

# Input

A valid LaTeX math expression (the braces are matched, and each token has enough tokens to bind to). You may assume it only contains ASCII characters. You can use any reasonable string I/O, but you can't take it pre-parsed. You can assume there are no empty braces, and the only whitespace is a space.

# Output

The shortest equivalent LaTeX math expression. You can use any reasonable string I/O (not necessarily the same as the input), but you can't output a parse tree or something similar.

# Testcases

```
\sum_{n \leq r^2} {\frac{v(n)}{n}} + \frac1n \in \{1,2,3\} -> \sum_{n\leq r^2}\frac{v(n)}n+\frac1n\in\{1,2,3\}
\a{b c}d -> \a bcd
\sqrt{b c}d -> \sqrt{bc}d
\sqrt{2 2}d -> \sqrt{22}d
\sqrt{a}d -> \sqrt ad
\sqrt{2}d -> \sqrt2d
\frac{1}{2} -> \frac12
\frac{12}{3} -> \frac{12}3
\frac{2}{n} -> \frac2n
\frac{a}{n} -> \frac an
\frac{a+1}{n} -> \frac{a+1}n
\frac{\frac12}3 -> \frac{\frac12}3
\frac{\sqrt2}3 -> \frac{\sqrt2}3
\frac {1} {23} -> \frac1{23}
\a b -> \a b
^{a b} -> ^{ab}
{ab}_{\log} -> ab_\log
{\sqrt{2}}^2 -> \sqrt2^2
\frac{\frac{\frac{1}{\sqrt{x_{1}}}+1}{\sqrt{x_{2}+1}}+2}{\sqrt{x_{3}+2}}+3 -> \frac{\frac{\frac1{\sqrt{x_1}}+1}{\sqrt{x_2+1}}+2}{\sqrt{x_3+2}}+3
\sqrt{\{} -> \sqrt\{

```

Note that `{ab}_{\log} -> ab_\log`, for example, isn't correct in real LaTeX.

This is , so the shortest answer in each language wins. Standard loopholes are disallowed.

# Answer
> 5 votes
# Retina 0.8.2, 202 bytes

```
M!`\\[A-Za-z]+|\\?.
A`^
+`(?<!\\)\{¶(.+)¶}
$1
+`(?<!\\|(?<!\\)[_^]¶|\\sqrt¶|\\frac¶(\{¶(((\{)|(?<-4>})|[^{}])+)¶}(?(4)^)¶|.+¶)?)\{¶(((\{)|(?<-7>})|[^{}])+)¶}(?(7)^)
$5
(\\[A-Za-z]+¶)([A-Za-z])
$1 $2
¶

```

Try it online! Link includes test cases. Explanation:

```
M!`\\[A-Za-z]+|\\?.

```

Tokenise the input.

```
A`^

```

Delete unquoted spaces.

```
+`(?<!\\)\{¶(.+)¶}
$1

```

Remove `{}`s surrounding a single token.

```
+`(?<!\\|(?<!\\)[_^]¶|\\sqrt¶|\\frac¶(\{¶(((\{)|(?<-4>})|[^{}])+)¶}(?(4)^)¶|.+¶)?)\{¶(((\{)|(?<-7>})|[^{}])+)¶}(?(7)^)
$5

```

Remove matched `{}`s that don't follow `\`, `_`, `^`, `\sqrt`, `\frac`, or aren't the second argument to `frac`.

```
(\\[A-Za-z]+¶)([A-Za-z])
$1 $2

```

If a quoted word is followed by a bare letter, insert a space.

Join everything together.

# Answer
> 3 votes
# Python3, 442 bytes:

```
lambda s:R(f(re.findall(r'\\\W|\\[a-z]+|\S',s)))
import re
def R(I):
 r=[]
 for i in I:r+=[' '*(r!=[]and r[-1][0]=='\\'and[]!=re.findall('^[a-z]',i))+i]
 return''.join(r)
def f(s,p=0):
 v={'\\sqrt':1,'^':1,'_':1,'\\frac':2}
 if[]==s:return
 if(t:=s.pop(0))in v:k=f(s,1);yield from[t,*[next(k)for _ in range(v[t])]]
 if'{'==t:T=[t,*f(s),'}'];yield R([T[1:-1],T][p and len(T)>3])
 if'}'!=t:
  if t not in v and'{'!=t:yield t
  yield from f(s,p)

```

Try it online!

# Answer
> 2 votes
# Charcoal, 178 bytes

```
Ｆ⪫_}⪫{_Ｓ¿⌕⮌υ\¿⁼ι Ｗ⌊υ⊞υω≡ι}«≔⟦⟧θＦ⌕⮌υ{Ｆ∧∨⌊υ⊟υ∧№α↥§§⊞Ｏθ⊟υ±¹¦⁰⬤§υ±¹⎇μ№α↥λ⁼λ\⊞θ ≔⊟υη¿∧⊖Ｌθ∨№⪪“7§⪪◧⌊q⦄ＮYL？⦄”¶§υ±¹⁼\frac§υ±²⊞υ⪫{}⪫⮌θωＷθ⊞υ⊟θ⊞υω»⊞υ⁺⎇∨№υω∧№α↥ι⬤§υ±¹⎇λ№α↥κ⁼κ\⊟υωι⊞υ⁺⊟υι✂⌈υ¹±²

```

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

```
Ｆ⪫_}⪫{_Ｓ

```

Wrap the input in `_{` and `_}` as the code will automatically join the tokens back together this way, and then loop over the characters.

```
¿⌕⮌υ\

```

If the last character was not a new escape, then:

```
¿⁼ι

```

If the current character is a space, then...

```
Ｗ⌊υ⊞υω

```

... push an empty string to the predefined empty list if there is not one already, preventing subsequent letters from being joined to a preceding command. Otherwise:

```
≡ι}«

```

If current character is a `}`, then:

```
≔⟦⟧θ

```

Start collecting tokens in reverse between the `}` and the previous `{`.

```
Ｆ⌕⮌υ{

```

Loop over the number of tokens.

```
Ｆ∧∨⌊υ⊟υ∧№α↥§§⊞Ｏθ⊟υ±¹¦⁰⬤§υ±¹⎇μ№α↥λ⁼λ\

```

Unless the current token is empty, if the current token starts with a letter and the next (previous) token is a command, then...

```
⊞θ

```

Insert a space after pushing the current token.

```
≔⊟υη

```

Remove the `{`.

```
¿∧⊖Ｌθ∨№⪪“7§⪪◧⌊q⦄ＮYL？⦄”¶§υ±¹⁼\frac§υ±²

```

If there was more than one token and the previous token(s) were `^`, `_`, `\sqrt` or `\frac`, then...

```
⊞υ⪫{}⪫⮌θω

```

... join the reversed tokens and wrap them in `{}`s, else...

```
Ｗθ⊞υ⊟θ

```

... push the tokens back. Note that this might also insert extra spaces but there's no point removing them as they would just get reinserted later.

```
⊞υω

```

Push an empty string in case the last original token was a command, so that a following letter does not get concatenated to it.

```
»⊞υ⁺⎇∨№υω∧№α↥ι⬤§υ±¹⎇λ№α↥κ⁼κ\⊟υωι

```

But if the current character was not a `}` then if the previous token was a space or current character is a letter and the previous token is a command then append the current character to it otherwise push it to the predefined empty list as a new token.

```
⊞υ⁺⊟υι

```

But if the last character was an escape, then append the current character to it.

```
✂⌈υ¹±²

```

Output the final result.

# Answer
> 2 votes
# K (ngn/k), 416 410 394 bytes

```
a:~"a{"'
t:{,/(((,:';,:)"\\"=*:')t)@'t:(0,&~(-1_0,"\\"=x)|a@x)_x}
kw:"|"\"\\frac |\\sqrt |_|^"
ar:1+~!4
k:{$[1<#x;(,/x)/"{}";*x]}
r:*(,,)/(,()),
f:{*{$[^*y;x;"}"~*y;(,()),x
 "{"~*y;r(x 0;x 1;2_x)
 ~^i:kw?y;r(y;ar[i]#*x;ar[i]_*x;1_x)
 r(y;*x;1_x)]}/[,();|u,'("\\"=*'u:t x)#\:" "]}
g:{r@(!#r)^w@&~a@r@1+w:&^r:{$[`C~@x;x
 |/kw~\:*x;x[0],,/{$[y;x;k@x]}[;2 1~#'(x;x 1)]'o'1_x
 1=#x;o@*x
 ,/o'x]}f@x}

```

Try it online!

shift/reduce parser (no regexes). Probably plenty of golfing left.
`t` tokenizes, `f` parses into an AST and `g` renders. I couldn't roll rendering into parsing because I couldn't distinguish deep structures which render as a single string from single tokens and failed on the ones mentioned in the problem comments.

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