# Question
Title: Write a Stack Exchange compliant brainfuck explainer
You are to take a string representing a piece of brainfuck code and Explanations, containing only printable ASCII characters and newlines ( to `~`, ASCII 10 and 32 to 126) as input and output an explanation of that code, formatted to be compliant with Stack Exchange markdown.

That is, the explanation must satisfy:

* Each line has an additional leading space, or multiple if the line above has multiple characters of code, such that it remains aligned vertically
* All commands are on their own line, while any consecutive no-ops (anything that isn't one of `<>+-.,[]`) are grouped together on one line
* The "explanation" for each command are all aligned to a single column, one space after the code itself
* The entire thing is in a "code block".
    + Either the entire explanation has a preceding and trailing ````` line, or
    + The entire explanation has a preceding `<pre><code>` line and a trailing `</code></pre>`
    + Each line of the explanation has 4 leading spaces, in addition to any leading spaces it might already have.
    + You don't have to escape parts of the output that might break the markdown.
* The first line of code block is the BF input code.

For example, if the code is `+[]Loop`, the explanation (without "explanations") would be formatted as one of

```
    +[]Loop
    +
     [
      ]
       Loop

```

```

+[]Loop
+
 [
  ]
   Loop

```

<pre><code>```
+[]Loop
+
 [
  ]
   Loop
```
</code></pre>

### Explanations

The explanation for each character will be provided as input:

```
Move the pointer to the right
Move the pointer to the left
Increment the memory cell at the pointer
Decrement the memory cell at the pointer
Output the character signified by the cell at the pointer
Input a character and store it in the cell at the pointer
Jump past the matching ] if the cell at the pointer is 0
Jump back to the matching [ if the cell at the pointer is nonzero
No Operation

```

The input always contain 9 explanation strings.
Answers can choose how to associate each brainfuck command with each explanation.
You may use array.
We can now add these explanations to our sample code to get

```
    +[]Loop
    +       Increment the memory cell at the pointer
     [      Jump past the matching ] if the cell at the pointer is 0
      ]     Jump back to the matching [ if the cell at the pointer is nonzero
       Loop No Operation

```

(using 4 leading spaces instead of backtick fencing or HTML tags).

This is , so the shortest code in bytes wins.

## Testcases

Input:

```
[]<>{}()++--..,,
Move the pointer to the right
Move the pointer to the left
Increment the memory cell at the pointer
Decrement the memory cell at the pointer
Output the character signified by the cell at the pointer
Input a character and store it in the cell at the pointer
Jump past the matching ] if the cell at the pointer is 0
Jump back to the matching [ if the cell at the pointer is nonzero
No Operation

```

Output:

```
    []<>{}()++--..,,
    [                Jump past the matching ] if the cell at the pointer is 0
     ]               Jump back to the matching [ if the cell at the pointer is nonzero
      <              Move the pointer to the left
       >             Move the pointer to the right
        {}()         No Operation
            +        Increment the memory cell at the pointer
             +       Increment the memory cell at the pointer
              -      Decrement the memory cell at the pointer
               -     Decrement the memory cell at the pointer
                .    Output the character signified by the cell at the pointer
                 .   Output the character signified by the cell at the pointer
                  ,  Input a character and store it in the cell at the pointer
                   , Input a character and store it in the cell at the pointer

```

Input:

```
Brainfuck Power.
Move the pointer to the right
Move the pointer to the left
Increment the memory cell at the pointer
Decrement the memory cell at the pointer
Output the character signified by the cell at the pointer
Input a character and store it in the cell at the pointer
Jump past the matching ] if the cell at the pointer is 0
Jump back to the matching [ if the cell at the pointer is nonzero
No Operation

```

Output:

<pre><code>```
Brainfuck Power.
Brainfuck Power  No Operation
               . Output the character signified by the cell at the pointer
```
</code></pre>

Input:

```
>++++++[{{<,.>-}}]
Move the pointer to the right
Move the pointer to the left
Increment the memory cell at the pointer
Decrement the memory cell at the pointer
Output the character signified by the cell at the pointer
Input a character and store it in the cell at the pointer
Jump past the matching ] if the cell at the pointer is 0
Jump back to the matching [ if the cell at the pointer is nonzero
No Operation

```

Output:

```

>++++++[{{<,.>-}}]
>                  Move the pointer to the right
 +                 Increment the memory cell at the pointer
  +                Increment the memory cell at the pointer
   +               Increment the memory cell at the pointer
    +              Increment the memory cell at the pointer
     +             Increment the memory cell at the pointer
      +            Increment the memory cell at the pointer
       [           Jump past the matching ] if the cell at the pointer is 0
        {{         No Operation
          <        Move the pointer to the left
           ,       Input a character and store it in the cell at the pointer
            .      Output the character signified by the cell at the pointer
             >     Move the pointer to the right
              -    Decrement the memory cell at the pointer
               }}  No Operation
                 ] Jump back to the matching [ if the cell at the pointer is nonzero

```

Input:

```
><+-.,NOP[]
Move
Move
Increment
Decrement
STD
STD
While
While
NOP

```

Output:

```
    ><+-.,NOP[]
    >           Move
     <          Move
      +         Increment
       -        Decrement
        .       STD
         ,      STD
          NOP   NOP
             [  While
              ] While

```

Input:

```
-\
Blah
Blah
Blah
Decrement
Blah
Blah
Blah
Blah
Nothing happens here

```

Output:

```
-\
-  Decrement
 \ Nothing happens here

```

# Answer
> 4 votes
# Stax, 45 bytes

```
å☺m█Q╗½§ÄN!╢┼♫mù}Jt→v)╢+Θ☼î╔↓bÉü╡⌐CÇ-♠•¿♪FM¥2

```

Run and debug it

Made this after Fmbalbuena's challenge in TNB. Will try to post something in Pip as well.

Found a nice save after Neil pointed out a mistake.

## Explanation

```
LBc4NtPY{"><+-.,[]"XI^i*}/zsFs%Ntcaay%^(x_Iasn@as+4NtPs
LBc4NtPY{"                                              No Operation
          >                                             Move the pointer to the right
           <                                            Move the pointer to the left
            +                                           Increment the memory cell at the pointer
             -                                          Decrement the memory cell at the pointer
              .                                         Output the character signified by the cell at the pointer
               ,                                        Input a character and store it in the cell at the pointer
                [                                       Jump past the matching ] if the cell at the pointer is 0
                 ]                                      Jump back to the matching [ if the cell at the pointer is nonzero
                  "XI^i*}/zsFs%Ntcaay%^(x_Iasn@as       No Operation
                                                 +      Increment the memory cell at the pointer
                                                  4NtPs No Operation

```

# Answer
> 21 votes
# brainfuck, ~~811~~ ~~775~~ ~~709~~ 701 bytes

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

```

Try it online!

This could probably be golfed more, as this is, like, the second brainfuck program I've written.

## Explanation

I should really write a program to do this for me...

Fullscreen Explanation

```
#####
# Execution will be divided into two phases: input and output.
# The input phase will input all characters and lay them out into memory with metadata.
# The output phase will then loop over the memory and print various segments of it, forming the explanation.

###############
# Input Phase #
###############

#####
# First, let's take a look at the memory layout.
# We'll divide the memory into 6-byte chunks.
# The chunks will be laid out in this format:
#   - first header chunk, to denote the start
#   - second header chunk, to denote the start
#   - first source chunk
#   - second source chunk
#   - ...
#   - last source chunk
#   - primary separator chunk (in place of newline)
#   - first chunk of first explanation
#   - second chunk of first explanation
#   - ...
#   - last chunk of first explanation
#   - separator chunk (in place of newline)
#   - first chunk of second explanation
#   - ......
#   - last chunk of last explanation
#   - eof chunk
# The first header chunk will have the following bytes:
#   0 10 96 0 0 0
# (10 is newline, and 96 is backtick)
# The second header chunk will consist entirely of zeroes.

                     #####
                     # Initialize the header chunks and output the initial code fence:
>>                     # Move to cell #2 (0-indexed).
-[-[--->]<<-]>--       # Set cell #2 to backtick (96) (pulled from https://esolangs.org/wiki/Brainfuck_constants).
...                    # Print it thrice (fine, there is a tiny bit of output in this phase).
<++++++++++.           # Set cell #1 to newline (10) and print it.
>>>>>>>>>>+          # Move to cell #5 of the second header chunk and temporarily set it to 1.

                     #####
                     # Next, read the input into chunks and initialize them.
                     # Every non-header non-eof chunk will be initialized to the following format:
                     #   #0: [char]  (0 if separator)
                     #   #1: [kind]  (which operator the char is)
                     #   #2: [mark]  (currently 1; this will occasionally be temporarily set to 0 as a "bookmark")
                     #   #3: 32      (the code for space, used for output)
                     #   #4: [noop]  (1 if no-op source chunk or non-primary separator, 0 otherwise)
                     #   #5: [done]  (currently 0, undone)
                     # During the initialization, some cells are used for temporary values.
[                    # While the current cell (#5 of the preceding chunk) is non-zero (and thus known to be 1), loop over the input:
  -                    # Subtract 1 from the cell, [done], returning it to 0 (undone)
  >                    # Move to the active chunk.
                       # Cell #5 will be used for positioning the pointer after a branch ('alignment'):
  >>>>>+               # Set cell #5 to 1
                       #####
                       # Next, we'll read a character.
  <<,                  # Move to cell #3 and input a character into it (temp).
  [                    # If this character is non-zero (not eof):
    [-<+<+>>]            # Duplicate this character into cells #1 and #2 [temp], erasing this cell, #3.
    <----------          # Move to cell #2 and subtract 10 (code for newline) from it.
                         # The chunk is now:
                         #   #0: 0
                         #   #1: char (temp)
                         # > #2: char - 10 (temp)
                         #   #3: 0
                         #   #4: 0
                         #   #5: 1 (alignment)
                         #####
                         # Next, if char is newline (10), we'll set cell #1 to 0.
    [[-]->]              # If cell #2 (char - 10) is non-zero (the char is not a newline), set this cell to 255 and move to cell #3.
    -[+>-]               # Move to the first cell to the right set to 1 (cell #5), and set it to 0.
                         # (The above is done without any net change to other cells.)
    <<<+                 # Move to cell #2 and add one to it; this cell is now 1 if char is a newline, or 0 otherwise.
    [-<[-]>]             # If cell #2 is 1, set it back to 0, move to cell #1, clear it, and move back to cell #2.
                         # From now on, char will be 0 if the character was a newline.
                         # The chunk is now:
                         #   #0: 0
                         #   #1: char (temp)
                         # > #2: 0
                         #   #3: 0
                         #   #4: 0
                         #   #5: 0
                         #####
                         # Next we'll inialize cell #0 [char] and put a copy of char into cell #2.
    <                    # Move to cell #1.
    [-<+>>+<]            # Duplicate this value to cells #0 and #2, clearing this cell.
                         # The chunk is now:
                         #   #0: [char]
                         # > #1: 0
                         #   #2: char (temp)
                         #   #3: 0
                         #   #4: 0
                         #   #5: 0
                         #####
                         # Next, we'll initialize cell #1 [kind] to a number denoting the 'kind' of the char is.
                         # The kind is an index from 0 to 8 matching the order "N+-<>[],." (where N stands for any no-op).
                         # The kind could be determined by directly checking if the character matches an operation (char == op).
                         # In BF, however, it's easier to check if something is not equal to X than if it is equal to X.
                         # We'll start cell #1 [kind] at the sum of the kind, 36 (1+2+3+4+5+6+7+8).
                         # For each operation, we'll check if the character does not match that operation, (char != op).
                         # To do so, we will use cell #2 for checking whether (char - op) is non-zero.
                         # If the character does not match that operation, we will subtract its kind from the sum.
                         # After doing so for all of the operations, the result will be the kind of the operation that the character matches.
                         # We'll do this not in kind order, but in op order: "+" (43), then "," (44), then "-" (45), etc.
                         #####
>>++++++[-<<++++++>>]    # Set cell #1 to 36 and move to cell #3.
>+                       # Set cell #4 to 1 to be used for alignment.
                         # The chunk is now:
                         #   #0: [char]
                         #   #1: 36 (sum of all kinds)
                         #   #2: char (char - 0)
                         #   #3: 0
                         # > #4: 1 (alignment)
                         #   #5: 0
                         #####
                         # The next set of lines are based on using the following pattern for each of the operations:
                           # Subtract from cell #2 the difference between the char codes for this operation and the previous.
                           # If cell #2 is not zero (if char != op):
                             # Remove this kind from the sum by subtracting from cell #1 (kind_sum) the kind of this operation.
                           # Return to cell #2 (using cell #4 for alignment).
                           # The resulting chunk will be:
                           #   #0: [char]
                           #   #1: kind_sum
                           # > #2: char (char - op)
                           #   #3: 0
                           #   #4: 1 (alignment)
                           #   #5: 0
                         # For '+', check 43:
    <++++++[-<------->]<-  # Subtract 43 (6 * 7 + 1) from cell #2, the difference between '+' and 0.
                           # The value in cell #2 is now char - 43.
    [                      # If the cell #2 is non-zero (char != 43; the character is not '+'):
      <->>                   # Subtract from cell #1 the kind of '+', 1.
    ]                      # End if.
    >[<]<                  # Return to cell #2 (using cell #4 for alignment).
                         # (For the remaining operations, the pattern will be shown in a condensed form.)
                         # For ',', check 44:
    -                      # Subtract 1 (the difference between ',' and '+').
    [<------->>]>[<]<      # If not zero, remove 7 from kind_sum. Return to cell #2.
                         # For '-', check 45:
    -                      # Subtract 1.
    [<-->>]>[<]<           # If not zero, remove 2 from kind_sum. Return to cell #2.
                         # For '.', check 46:
    -                      # Subtract 1.
    [<-------->>]>[<]<     # If not zero, remove 8 from kind_sum. Return to cell #2.
                         # For '<', check 60:
    --------------         # Subtract 14.
    [<--->>]>[<]<          # If not zero, remove 3 from kind_sum. Return to cell #2.
                         # For '>', check 62:
    --                     # Subtract 2.
    [<---->>]>[<]<         # If not zero, remove 4 from kind_sum. Return to cell #2.
                         # For '[', check 91
    >+++++[-<------>]<+    # Subtract 29 (5 * 6 - 1).
    [<----->>]>[<]<        # If not zero, remove 5 from kind_sum. Return to cell #2.
                         # For ']', check 93
    --                     # Subtract 2.
    [<------>>]>[<]<       # If not zero, remove 6 from kind_sum. Return to cell #2.
                         #
    [-]                  # Set cell #2 to zero.
                         # The chunk is now:
                         #   #0: [char]
                         #   #1: [kind]
                         # > #2: 0
                         #   #3: 0
                         #   #4: 1 (temp)
                         #   #5: 0
                         #####
                         # Next, cell #4 [noop] will be initialized to 0 if char is not a no-op.
    <<+                  # Move to cell #0, adding 1 (temporarily, for alignment)
    >                    # Move to cell #1.
    [>>>-]               # If cell #1 [kind] is non-zero (the char is not a no-op),
                         #  move to cell #4 [noop] and subtract 1 to set it to 0.
    <[>>>]               # Move to cell #3, using cell #0 for realignment.
    <<<-                 # Move to cell #0 and subtract 1 from it, returning it to char.
                         # The chunk is now:
                         # > #0: [char]
                         #   #1: [kind]
                         #   #2: 0
                         #   #3: 0
                         #   #4: [noop] (1 if no-op, 0 otherwise)
                         #   #5: 0
                         #####
                         # Next, cell #2 [mark] will be initialized to 1 (unmarked) and cell #3 [space] will be initialized to 32 (code for space).
    >>++++[->++++++++<]  # Move to cell #2 and set cell #3 to 32 (4 * 8)
    +                    # Set #2 [mark] to 1 (unmarked)
    >>>+                 # Move to cell #5 and set it to 1 (temporarily, so the input loop continues; this will be unset in the next iteration).
    >                    # Move to cell #0 of the next chunk.
  ]                    # End "if non-eof".
  <                  # If at cell #0 of the next chunk (from the preceding branch for processing a source chunk), move to cell #5 of the current chunk;
                     #   otherwise (at cell #3 after the source chunks), move to cell #2.
]                    # End input loop.
                     # Every non-header non-eof chunk is now:
                     #   #0: [char]  (0 if separator)
                     #   #1: [kind]  (which operator the char is)
                     #   #2: [mark]  (currently 1; this will occasionally be temporarily set to 0 as a "bookmark")
                     #   #3: 32      (the code for space, used for output)
                     #   #4: [noop]  (1 if no-op source chunk or non-primary separator, 0 otherwise)
                     #   #5: [done]  (currently 0, undone)
                     # Since the loop ended, it reached eof, and the head is at cell #2 of the eof chunk.

################
# Output Phase #
################

                     #####
                     # First, we will return to the header chunks.
+                    # Set cell #2 to 1 (used later to save a byte).
[<<<<<<]             # Move left one chunk at a time until cell #2 is zero, reaching the second header chunk.
>>>>                 # Move to cell #0 of the first source chunk.
[.>>>>>>]            # While cell #0 is non-zero, print it and move to the next chunk
                     #  (this writes the first line of the explanation, the code verbatim).
                     # Now, the head is at cell #0 of the primary separator chunk.
>>>>-<<<<            # Set its cell #4 to 0 (used later to break a loop).
<<<<<<[<<<<<<]       # Move to the next 0-char chunk to the left (this is the second header chunk).
<<<<<.               # Move to cell #1 of the first header chunk (newline) and output it (ending the first line).

                     #####
                     # As we go through each line of the explanation, we'll follow this psuedo-code:
                     #   - Output a space for every source character marked as 'done'
                     #   - Output the characters for the active operations (multiple if it's a chain of no-ops, only one otherwise)
                     #   - Mark all active operations 'done'
                     #   - Output a space for every source character after the active ones
                     #   - Output a space followed by the associated explanation
                     # These steps will be expanded on later.

>>>                  # Move to cell #4 of the first header chunk.
+                    # Set it to one to start the loop.
[                    # Begin a loop to print subsequent lines:
                       #####
                       # First, we will find the first not done chunk.
  -                    # Set this cell, #4 of the first header chunk, back to 0.
  >>>>>>>>>>>>>        # Move to cell #5 [done] of the first source chunk.
  [>>>>>>]             # Go to the first not done cell to the right (it might be the current chunk).
  <<<<<                # Go to cell #0 [char].
  [                    # If it's non-zero (if it's a source chunk):
                         #####
                         # Next, we will output the leading spaces and the first active character.
    <[<<.<<<<]           # Go to cell #5 of the first not done chunk to the left
                         #  (this is the second header chunk), outputting spaces along the way.
    >>>>>>               # Go to cell #5 [done] of the next chunk.
    [>>>>>>]             # Move to cell #5 of the first non-done cell to the right.
    <<<<<.               # Move to cell #0 [char] of this chunk (the first active source chunk) and output it.
    >>>>                 # Move to cell #4 [noop] of this chunk.

                         #####
                         # Next, the following branch will process a sequence of no-op chunks.
                         # This is handled differently from non-no-op chunks because sequential no-op characters are printed in one line.
    [                    # If it's non-zero (if this character is a no-op):
      >+                   # Set cell #5 [done].
                           #####
                           # First, we will output each subsequent active character and mark their chunks as done.
      >>>>>                # Move to cell #4 [noop] of the next chunk.
      [                    # While the current chunk is a no-op:
        <<<<.                # Move to cell #0 [char] and output it.
        >>>>>+               # Move to cell #5 [done] and set it to 1.
        >>>>>                # Move to cell #4 [noop] of the next chunk.
                             # (Note that the primary separator has cell #4 [noop] set to 0 in order to break this loop)
      ]                    # End loop. Now the head is at the cell #4 [noop] of the first non-no-op chunk.
                           #####
                           # Next, we will output the trailing spaces and the no-op explanation.
      <<<<[>>>.>>>]        # Move to the primary separator chunk, outputting a space for each skipped chunk.
      >>>.>>>              # Move to cell #0 of the first chunk of the first explanation, outputting a space.
      [.>>>>>>]            # Move to the next non-explanation chunk, outputting each character.
      >>                   # Move to cell #2 [mark].
      [<<<<<<]             # Move to cell #2 of the second header chunk.
      <                    # Move to cell #1.
    ]                    # End if.
    <<<                  # If at cell #1 of the second header chunk (from the preceding branch for processing a no-op), move to cell #4 of the first header chunk;
                         #  otherwise, (still at the cell $4 [noop] of the current source chunk), move to cell #1 [kind].

                         #####
                         # Next, the following branch will process a non-no-op chunk.
                         # This is handled separately from no-op chunks because operators are printed on separate lines.
    [                    # If cell #1 [kind] is non-zero (if in a non-no-op source chunk):
                           #####
                           # First, we will output the trailing spaces and find the primary separator chunk.
      >-                   # Move to cell #2 [mark] and set it to 0 (this marks the cell to return to later).
      >>>+                 # Move to cell #5 [done] and set it to 1.
      >[>>>.>>>]           # Move to the primary separator chunk, outputting a space for each skipped chunk.
      >>-                  # Mark this chunk (the primary separator chunk).
      <<<<<.<              # Move to cell #2 [mark] of the previous chunk, outputting a space.
      [<<<<<<]             # Move to the first marked (mark == 0) cell to the left (the active source chunk).
      <                    # Move to cell #1 [kind].
                           #####
                           # Next, we'll locate the correct explanation.
                           # We're at cell #2 [kind], which acts as an index to the explanation.
                           # The primary separator (which precedes the 0th (no-op) explanation) is marked.
      [-                   # Continually decrement the kind:
                             # Each iteration will unmark the currently marked separator and mark the next separator.
        >>>>>>>[>>>>>>]      # Move to the first marked cell to the right.
        +                    # Unmark this chunk.
        >>>>                 # Move to cell #0 of the next chunk.
        [>>>>>>]             # Move through the explanation chunks to the next separator chunk.
        >>-                  # Mark this separator chunk.
        <<<<<<[<<<<<<]<      # Return cell #1 [kind] of the active source chunk (as it's marked).
      ]                    # End loop.
                           #####
                           # Next, we will output the explanation we have located.
      >+                   # Unmark the current source chunk.
      [>>>>>>]             # Move to the marked separator chunk.
      +                    # Unmark this chunk.
      >>>>                 # Move to cell #0 [char] of the next chunk.
      [.>>>>>>]            # While cell #0 [char] is non-zero, output it and move to the next chunk.
      >>[<<<<<<]           # Return to the second header chunk.
      <<<<                 # Move to cell #4 of the first header chunk.
    ]                    # End if.

                         # From either branch, we are now at cell #4 of the first header chunk.
    +                    # Set cell #4 to 1 (to continue the loop).
    <<<.                 # Move to cell #1 (newline) and output it.
    >>                   # Move to cell #3 (which is 0).
  ]                    # End if.
  >                    # If at the first header chunk (from the preceding branch for processing a source chunk), move to cell #4 (which is 1, continuing the loop);
                       #  otherwise (still at the primary separator), move to cell #1 (which is 0, ending the loop).
]                    # End loop.

#####
# Lastly, we will print the final code fence.
>[<<<<<<]            # Move to cell #2 of the second header chunk.
<<<<<<...            # Move to the first header chunk and output the backtick thrice.

#####
# Finally, we can enjoy the fruits of our efforts: https://pastebin.com/raw/C9yYHx3F.

```

# Answer
> 7 votes
# Vyxal `oj`, 69 bytes

```
:4$꘍,`([%^])`\\`><+-,.[]`f:→+∑%ṡ';:vL¦0pṪZƛ÷$꘍nh←=Tuw∨□ḣ∇‟İ„L›„↲p4$꘍∑

```

Try it Online!

## Explained

```
`([%^])`

```

Push the string `"([%^])"` to the stack. This will serve as the basis for a regular expression that groups on non-BF commands

```
\\

```

Push a backslash to the stack. This will serve to escape all the characters in the BF character set (`[` and `]` need to be escaped, because they interfere with the range set)

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

```

Push the string `"><+-,.[]"` to the stack, and turn it into a list of characters. It's important it's turned into a list of characters because the backslash will be prepended to each character using vectorised addition.

```
:→

```

But first, put the character set into the ghost variable for later storage - there's no BF character set element in vyxal, so to save bytes, it needs to be stored.

```
+∑

```

Prepend the backslash to each character just like I said I would, and convert it back to a single string.

```
%

```

And place that into the regex pattern string from earlier using string formatting

```
ṡ';

```

Split the input program on that regex, and keep only non-empty strings. This splits the program into single bf chars and groups of NOPs.

```
:vL¦0pṪZ

```

Get the length of each group, get the cumulative sum of that, prepend a 0 and zip with each group. This has the effect of calculating how many spaces to prepend to each group.

```
ƛ

```

To each item `X = [spaces, character_group]` in that, do the following

```
÷ð*p

```

Prepend `spaces` spaces to `character_group`

```
nh←=Tuw∨

```

Get the index of `character_group` in the BF character set stored in the ghost variable. This is basically a hacky version of  because  doesn't work on the version the site uses (it's fixed in the 2.6 preleases, but I'm sticking with 2.4.1)

```
□ḣ

```

Wrap all inputs (program and explanation strings) into a single list and push the program separately from the explanation strings.

```
∇‟İ

```

Do some weird stack manipulation to retrieve the corresponding explanation string using the index generated by `nh←=Tuw∨`.

```
„L›„↲$+

```

Left justify the character group with the prepended spaces with extra spaces to match the length of the input program + 1. And add that to the explanation using some extra weird stack manipulation.

```
4ð*p∑

```

Indent that 4 spaces, and convert into a single string.

```
;⁋

```

Join the entire list on newlines. The `j` flag would usually take care of this, but 69 is a funny number.

# Answer
> 7 votes
# Charcoal, ~~54~~ ~~48~~ 47 bytes

```
× ⁴ＰＳＦθ«⊞υ⌕><+-.,[]ι¿⁺²Σ✂υ±²↓Ｐ⊟υι»↑⸿↓≔Ｅ⁹ＳηＥυ§ηι

```

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

```
× ⁴

```

Indent by 4 spaces.

```
ＰＳ

```

Print the code without moving the cursor.

```
Ｆθ«

```

Loop over the characters in the code.

```
⊞υ⌕><+-.,[]ι

```

Push the index of the appropriate explanation to the predefined empty list. NOPs will have an index of `-1`, which will cyclically index to the last explanation, but is also useful for coalescing consecutive NOPs below.

```
¿⁺²Σ✂υ±²

```

If there are not two consecutive NOPs, then...

... move down a line, else...

```
Ｐ⊟υ

```

... discard one of the NOPs.

```
ι

```

Output the current character.

```
»↑⸿

```

Move to the start of the next column.

Move to the first row of explanations.

```
≔Ｅ⁹Ｓη

```

Read in the explanations.

```
Ｅυ§ηι

```

Print each appropriate explanation.

Today I discovered a bug in Charcoal's `Split` command which unintentionally results in partial regex support: `Split(<string>, <list>)` is supposed to split the string at any occurrence of any word in `<list>`, but due to the bug what actually happens is that `Split(<pattern>, [<string>])` escapes the string and splits it on the pattern. Unfortunately the original approach has since been golfed down from its original 54 bytes which this approach ties with, but that's still good going considering the duplication of the command characters:

```
× ⁴≔Φ⪪“ xMＴ¦Ｔ~≧_x”⟦Ｓ⟧ιθＰ⪫θωＦθ⁺¶ι↑⸿↓≔Ｅ⁹ＳηＥθ§η⌕><+-.,[]ι

```

Try it online! Link is to verbose version of code. Note: Backslashes are not supported because this is relying on buggy Charcoal behaviour. Explanation:

```
× ⁴

```

Indent by 4 spaces.

```
≔Φ⪪“ xMＴ¦Ｔ~≧_x”⟦Ｓ⟧ιθ

```

Extract command characters or runs of non-command non-backslash characters from the input.

```
Ｐ⪫θω

```

Print the code without moving the cursor.

```
Ｆθ⁺¶ι

```

Output each command on its own line, but increasing the indent as it goes.

```
↑⸿

```

Move to the start of the next column.

Move to the first row of explanations.

```
≔Ｅ⁹Ｓη

```

Read in the explanations.

```
Ｅθ§η⌕><+-.,[]ι

```

Find and output the appropriate explanation for each command, or the last explanation for non-commands.

# Answer
> 7 votes
# 05AB1E, ~~53~~ ~~52~~ 50 bytes

```
.γ"><+-.,[]"©såN>*}DU¹g>j|VεXN>£JvÁ}Y®XNèkè«}¹š4ú»

```

-2 bytes thanks to *@ovs*.

Outputs the lines with four leading spaces.

Try it online.

**Explanation:**

```
.γ                 # Group the first (implicit) input-string into parts:
  "><+-.,[]"       #  Push the string "><+-.,[]"
            ©      #  Store it in variable `®` (without popping)
             s     #  Swap to get the current character
              å    #  Check if it's in the string
               N>* #  Multiply it by the 1-based index
                   #  (this ensures all characters in that string become unique
                   #  values, but all unknown characters map to the same value 0)
}DU                # After the group-by, store a copy in variable `X`
   ¹g              # Push the length of the first input-string
     >             # Increase it by 1
      j            # Make all strings of that length by padding leading spaces
|                  # Push a list of all remaining input-lines
 V                 # Pop and store it in variable `Y`
      ε            # Map over the parts:
       X           #  Push the parts from variable `X`
        N>£        #  Leave the first map-index + 1 amount of parts
           J       #  Join them together
            v }    #  Pop and loop its length amount of times:
             Á     #   Rotate the string once towards the right
         XNè       #  Get the map-index'th part from variable `X`
        ®   k      #  Get the index of that part from variable `®`
       Y     è     #  Use that to index into the list of lines `Y`
              «    #  Append the two strings together
      }¹š          # After the map: prepend the first input-string
         4ú        # Pad each string with 4 leading spaces
           »       # Join the list by newlines
                   # (after which the result is output implicitly)

```

# Answer
> 6 votes
# JavaScript (ES2022), 141 bytes

```
s=>a=>"    "+s+s.replace(/(?:[^+-.<>[\]]+|.)(?=(.*))/g,(c,e)=>`
`+(c+e.replace(/.|$/g,' ')).padStart(s.length+5)+a.at('><+-.,[]'.indexOf(c)))

```

Try it online!

```
f: (source_code: string) => (explain_array: string[]) => string

```

# Answer
> 5 votes
# Pip, ~~65~~ 60 bytes

```
OsX4FbPp:#_FIa^C X^Y"><+-.,[]"P[sX4pRXXsRA Uvbs(gU(y@?b)|9)]

```

The BF program and the nine explanation strings are taken as command-line arguments. Alternately, you can use the `-r` flag to take them from stdin. Replit! Or, here's a 61-byte equivalent in Pip Classic: Try it online!

### Former explanation

New explanation pending... This is the explanation for the previous 65-byte solution.

```
Oi:sX4Pp:#_FIa^C X^Y"><+-.,[]"WpP[iPBsX#xx:POpsX#Jps(gU(y@?x)|v)]

```

First, the setup:

```
Oi:sX4Pp:#_FIa^C X^Y"><+-.,[]"
   sX4                          Space character, repeated 4 times
 i:                             Assign to i (the indent)
O                               Output it without trailing newline
                   Y"><+-.,[]"  Yank that string into y (BF commands)
                  ^             Split into a list of chars
                 X              Convert to a regex that matches any one of those chars
               C                Wrap the regex in a capture group
             a^                 Split the first program arg on that regex
                                (As in Python, splitting on a regex wrapped in a group
                                keeps the matches of the regex in the result list)
           FI                   Filter that list on this function:
         #_                      Length of item
                                (This gets rid of empty strings while not getting rid
                                of "0", which is falsey in Pip)
       p:                       Assign the result to p (the processed program)
      P                         Print it with trailing newline

```

Then, the main loop:

```
WpP[iPBsX#xx:POpsX#Jps(gU(y@?x)|v)]
Wp                                   While p is not empty:
  P                                  Print (with trailing newline)
   [                              ]  this list, concatenated:
                                      1. Indent:
          x                            Last chunk (initially empty string)
         #                             Length of the above
       sX                              That many spaces
     PB                                Push those onto the end of
    i                                  i (modifies i in-place)
                                      2. Current chunk:
             POp                       Pop the first item from p
           x:                          Assign it to x
                                      3. Padding:
                    p                  Remaining chunks
                   J                   Joined into a single string
                  #                    Length of the above
                sX                     That many spaces
                     s                4. One more space before explanation
                                      5. Explanation:
                          y@?x         Index of current chunk in BF commands
                                       (0 to 7, or nil if not found)
                        U(    )        Increment (1 to 8, or nil)
                               |       Logical OR
                                v      Negative one (1 to 8, or -1)
                      (g         )     Item in program args at that index

```

# Answer
> 4 votes
# Jelly, 46 bytes

```
®Ṭ€z0aḷżṚ⁸ṭṚŻ€4¡o⁶ð“><+-.,[]”iⱮxṠoŒQÄ©ŒQƲ$$ịŻ€

```

Try it online!

Program on the left and list of descriptions on the right. I suspect this can lose a few bytes fairly easily, but I'm posting it now in order to preserve one of the most hideous things I have ever written for posterity.

# Answer
> 3 votes
# Vyxal 3 , ~~80~~ 79 bytes

```
Dð4×§,0$"<>+-.,[]"£([¥nc[⁰Lm-ꜝð×§¹,|n§1#x)4m+ð×§¥nḞꜝ:[#?Ḣin§⁰Lm-ð×§,0|n§1][ð§¹,

```

Try it Online!

### Explanation:

Setup:

```
Dð4×§,0$"<>+-.,[]"£(
 ð4×§                 ## Print "    " without newline
D    ,                ## Print the first line of input with newline
        "<>+-.,[]"£   ## Put "<>+-.,[]" in the register
      0$              ## Push the 0 in the stack (Swapped because the top of the stack is used for looping)
                   (  ## Loop every char in the first line of input

```

Looping part:

```
[¥nc[⁰Lm-ꜝð×§¹,|n§1#x)4m+ð×§¥nḞꜝ:[#?Ḣin§⁰Lm-ð×§,0|n§1]
[¥nc[                                                   ## if the current character is in "<>+-.,[]"
     ⁰Lm-ꜝð×§¹,                                         ## print that many spaces, then the second line of input, with newline.
               |n§1#x)                                  ## else print the current character and continue with the 1 in the top of the stack.
                      4m+ð×§                            ## Print that many spaces
                            ¥nḞꜝ                        ## index of the current character (1 to 8, 0 if not found)
                                :[                      ## if the index of the current character is 1 or more
                                  #?Ḣin§⁰Lm-ð×§,0       ## Print that many spaces, then the right explanation, with newline, and push 0
                                                 |n§1]  ## else, print the current character, and push 1

```

Final part:

```
[ð§¹,
[      ## If the top of stack is 1 or greater
       ## (I have no idea why that works)
 ð§    ## print " " without newline
   ¹,  ## Print the second line of input, with newline

```

Created with the help of Luminespire.

# Answer
> 2 votes
# Perl 5 \+ `-nF -M5.10.0`, 93 bytes

Thanks to @Fmbalbuena for noticing I'd missed printing the unaltered string! Thanks to @emanresu A and @Neil's regex wizardry saving 14 (!!) bytes!

```
@@=<>;say$"x4,$_,map$"x(4+$-).$_.$"x(@F-($-+=y///c)).$@[index'><+-.,[]',$_],/[^]<>+-.[
]+|./g

```

Try it online!

## Explanation

First `print` `4` `x` (string repetition operator) `$"` (which defaults to space), then store the length of the input (implicitly obtained via `-F` into `@F`) in `$=`, and store the explanations in `@@`. Then, `for` each matching piece of code (either one char from `-<>+.,[]`, or any number of any other chars) concatenate the following with `$\`: 4 + `$-` (which starts out as `0`) `x` `$"`, followed by the piece of code (`$_`), followed by the original length, minus `$-` (to which we add the current length of this code piece) `x` `$"` and finally, using the `index` function on the string `><+-.,[]`, the message associated to the current piece of code (`index` returns `-1` for missing index, for which Perl returns the last element of the list). `$_` is output followed by `$\` thanks to `-p` flag.

---

# Perl 5 \+ `-F/([^]<>+-.[]+|.)/ -M5.10.0`, 92 bytes

The regex used in the above, can be provided via `-F` to save a byte.

```
$==y///c;@@=<>;say$"x4,$_,map/./&&$"x(4+$-).$_.$"x($=-($-+=y///c)).$@[index'><+-.,[]',$_],@F

```

Try it online!

# Answer
> 2 votes
# C (clang), ~~191~~ 188 bytes

*-3 thanks to @ceilingcat*

```
*S="><+-.,[]";i;l;d;f(char*a,**e){for(i=5,l=printf("    %s \n",a);*a;printf("%*s%s\n",l-i,"",e[d?d-(int)S:8]))for(d=index(S,*a),printf("%*c",i++,*a);!d&!index(S,*++a);)i+=write(1,a,*a>0);}

```

Try it online! Assumes explanations are in the order `> < + - . , [ ] NOP`.

# Answer
> 2 votes
# Ruby, 118 bytes

```
c,*a=*$<
print" "*l=4,c
c.scan(/[^+-.\[\]<>\n]+|./){puts" "*l+$&+" "*(c.size+4-l+=$&.size)+a["><+-.,[]".index($&)||8]}

```

Try it online!

#### Explanation

```
c,*a=*$<                                 # assign 'c' to first line and 'a' to the rest of input
print" "*l=4,c                           # output code and assign 'l' to 4 at the same time
c.scan(/[^+-.\[\]<>\n]+|./)              # for every match:
{puts" "*l+$&+" "*(c.size+4-l+=$&.size)+ # output the padded match, update 'l' to keep track of the spaces
a["><+-.,[]".index($&)||8]}              # output the correct explanation

```

inspiration taken from lonelyelk

# Answer
> 2 votes
# Haskell, 330 bytes

```
import Data.List
main=interact$unlines.f.lines
f(c:a)=(s 4++c):(map(p c.(a%)).tail.inits.t)c
t r|r==[]=[]|q x=[x]:t y|0<1=a:t b where(x:y)=r;(a,b)=span(not.q)r
q=(`elem`n)
p c(a,e)=s(4+(l.init)a)++last a++s(1+length c-l a)++e
s=(`replicate`' ')
n="><+-.,[]"
e%j=(j,e!!(n#last j))
l=length.concat
(s:z)#c|[s]==c=0|z==[]=1|0<1=1+z#c

```

Try it online!

#### Explanation:

```
import Data.List
main=interact$unlines.f.lines
f(c:a)=(s 4++c):(map(p c.(a%)).tail.inits.t)c

```

import Data.List `inits`(prefixes), this is used to keep track of the number of spaces
call `f` with lines of input, then output each line
f = `" " * 4 + code` \+
`map` on each `prefix` of each command or noop:
select explanation and then pad with spaces

```
t r|r==[]=[]|q x=[x]:t y|0<1=a:t b where(x:y)=r;(a,b)=span(not.q)r
q=(`elem`n)
n="><+-.,[]"

```

`t` splits the code into commands or noop
`q` checks if a char is a command
`n` is the string `"><+-.,[]"`

```
p c(a,e)=s(4+(l.init)a)++last a++s(1+length c-l a)++e
s=(`replicate`' ')
e%j=(j,e!!(n#last j))
(s:z)#c|[s]==c=0|z==[]=1|0<1=1+z#c

```

`p` pads a (prefix, explanation)-pair with spaces
`s` returns n spaces
`%` creates said (prefix, explanation)-pair
`#` returns the index of the command in `n` or 8 if it's a noop

# Answer
> 1 votes
# Retina, ~~207~~ 205 bytes

<pre><code>*\K````
*\0G`
\G.
$& $&¶
m,-10T`_><+\-.,[]p`d`.$
(?<=^(.+¶)*.) 9¶(?=. 9)

+`^(.+¶)*(.)+ .¶(?!¶|(?<-2> )*(?(2)$))
$&
,-10P`.+
+`(\d)( *)(¶(.+¶)*¶)
$2$1*_$3
+`(_)+(¶(.+¶)*(?<-1>.*¶)+(.*))
$4$2
(¶.*){9}$
```
</code></pre>

Try it online! Explanation:

<pre><code>*\K````

Output the leading fence.

```
*\0G`

```

Output the line of code.

```
\G.
$& $&¶

```

Split the line of code into characters. For each character, repeat it twice, joined with a space.

```
m,-10T`_><+\-.,[]p`d`.$

```

Transliterate the last character of each pair to a digit `1-8`, with unknown characters becoming `9`.

```
(?<=^(.+¶)*.) 9¶(?=. 9)

```

Join together all runs of unknown characters.

```
+`^(.+¶)*(.)+ .¶(?!¶|(?<-2> )*(?(2)$))
$&

```

(note trailing space) Align each run after the end of the previous run.

```
,-10P`.+

```

Pad all of the explanation lines to the same width.

```
+`(\d)( *)(¶(.+¶)*¶)
$2$1*_$3

```

Convert all of the transliterated digits to runs of underscores and move them to the end of the line.

```
+`(_)+(¶(.+¶)*(?<-1>.*¶)+(.*))
$4$2

```

Replace each run of underscores with the appropriate line of explanation.

(¶.*){9}$
```
</code></pre>

Replace all of the explanations with the trailing fence.

# Answer
> 1 votes
# Ruby, ~~143~~ ~~142~~ 138 bytes

```
->i{c,*e=i.split ?\n;puts" "*(m=4)+c;c.scan(/[^<>+-.,\[\]]+|./){|b|r=" ".*c.size+5;r[m,z=b.size]=b;puts r+e["<>+-.,[]".index(b)||8];m+=z}}

```

Try it online!

The function expects input to be lines separated by `\n`. It scans the program using regexp `/[^<>+\.,\[\]-]+|./`. It outputs to stdout instead of returning. Which is all there is to it.

Thanks to @Fmbalbuena for removing a space!

Saved 4 more bytes by re-reading ruby golfing tips :)

# Answer
> 1 votes
# Haskell, 235 231 bytes

```
import Data.List
main=interact$unlines.map("    "++).f"><+-.,[]".lines
f o(i:e)|let t=not.(`elem`o);p=(>>" ").concat;w((c:r):t)=(c:r++p t++' ':maybe(e!!8)id(lookup c$zip o e)):[p[c:r]++l|l<-w t];w[]=[]=i:w(groupBy(\x y->t x&&t y)i)

```

Try it online!

Old answer:

**Haskell, 235 bytes**

```
import Data.List
main=interact$unlines.map("    "++).f.lines
o="><+-.,[]"
t=not.(`elem`o)
p=(>>" ").concat
f(i:e)|let w((c:r):t)=(c:r++p t++' ':maybe(last e)id(lookup c$zip o e)):[p[c:r]++l|l<-w t];w[]=[]=i:(w$groupBy(\x y->t x&&t y)i)

```

Try it online!

*The answer is not final, will probably be golfed further.*

---
Tags: code-golf, string, brainfuck, whitespace
---


# Question
Title: The Three 'R's: Reverse, Reorder, Repeat
While doodling around with numbers, I found an interesting permutation you can generate from a list of numbers. If you repeat this same permutation enough times, you will always end up back at the original array. Let's use the following list:

```
[1, 2, 3, 4, 5]

```

as an example

1. **Reverse** the array. Now our array is

```
[5, 4, 3, 2, 1]

```
2. **Reorder** (swap) each pair. Our list has 2 pairs: `[5, 4]`, and `[3, 2]`. Unfortunately, we can't group the `1` into a pair, so we'll just leave it on it's own. After swapping each pair, the new array is:

```
[4, 5, 2, 3, 1]

```
3. **Repeat** steps 1 and 2 until we return to the original array. Here are the next 4 steps:

```
Step 2:
Start:          [4, 5, 2, 3, 1]
Reversed:       [1, 3, 2, 5, 4]
Pairs Swapped:  [3, 1, 5, 2, 4]

Step 3:
Start:          [3, 1, 5, 2, 4]
Reversed:       [4, 2, 5, 1, 3]
Pairs Swapped:  [2, 4, 1, 5, 3]

Step 4:
Start:          [2, 4, 1, 5, 3]
Reversed:       [3, 5, 1, 4, 2]
Pairs Swapped:  [5, 3, 4, 1, 2]

Step 5:
Start:          [5, 3, 4, 1, 2]
Reversed:       [2, 1, 4, 3, 5]
Pairs Swapped:  [1, 2, 3, 4, 5]

# No more steps needed because we are back to the original array

```

If the length of the list, **n** is odd, it will always take exactly **n** steps to return to the original array. If **n** is even, it will always take 2 steps to return to the original array, *unless* n is 2, in which case it will take 1 step (because reversing and swapping is the same thing).

Your task for today (should you choose to accept it) is to visualize this set of steps for lists of arbitrary lengths. You must write a program or function that takes a single positive integer *n* as input, and does this set of steps for the list `[1, n]`. You must output each intermediate step along the way, whether that means printing each step, or returning them all as a list of steps. I'm not very picky about the output format, as long as it's clear that you are generating every step. This means (for example) any of these:

* Outputting every step as a list to STDOUT
* Returning a list of lists
* Returning a list of string representations of each step
* Returning/outputting a matrix

would be acceptable.

You must also output the original array, whether that comes at the end or at the beginning is up to you. (technically, both are correct)

*You will have to handle the edge case of 2 taking 1 step instead of 2*, so please make sure your solution works with an input of 2 (and 1 is another potential edge case).

As usual, this is , so standard loopholes apply, and try to make your solution shorter than any other in the language of your choice (or even try to beat another language that is typically shorter than yours if you're feeling up for a challenge).

# Test IO

```
1:
[1]

2:
[1, 2]

3:
[2, 3, 1]
[3, 1, 2]
[1, 2, 3]

4:
[3, 4, 1, 2]
[1, 2, 3, 4]

5:
[4, 5, 2, 3, 1]
[3, 1, 5, 2, 4]
[2, 4, 1, 5, 3]
[5, 3, 4, 1, 2]
[1, 2, 3, 4, 5]

7:
[6, 7, 4, 5, 2, 3, 1]
[3, 1, 5, 2, 7, 4, 6]
[4, 6, 2, 7, 1, 5, 3]
[5, 3, 7, 1, 6, 2, 4]
[2, 4, 1, 6, 3, 7, 5]
[7, 5, 6, 3, 4, 1, 2]
[1, 2, 3, 4, 5, 6, 7]

9:
[8, 9, 6, 7, 4, 5, 2, 3, 1]
[3, 1, 5, 2, 7, 4, 9, 6, 8]
[6, 8, 4, 9, 2, 7, 1, 5, 3]
[5, 3, 7, 1, 9, 2, 8, 4, 6]
[4, 6, 2, 8, 1, 9, 3, 7, 5]
[7, 5, 9, 3, 8, 1, 6, 2, 4]
[2, 4, 1, 6, 3, 8, 5, 9, 7]
[9, 7, 8, 5, 6, 3, 4, 1, 2]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

```

And for good measure, here's one giant test case:

```
27:
[26, 27, 24, 25, 22, 23, 20, 21, 18, 19, 16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 1]
[3, 1, 5, 2, 7, 4, 9, 6, 11, 8, 13, 10, 15, 12, 17, 14, 19, 16, 21, 18, 23, 20, 25, 22, 27, 24, 26]
[24, 26, 22, 27, 20, 25, 18, 23, 16, 21, 14, 19, 12, 17, 10, 15, 8, 13, 6, 11, 4, 9, 2, 7, 1, 5, 3]
[5, 3, 7, 1, 9, 2, 11, 4, 13, 6, 15, 8, 17, 10, 19, 12, 21, 14, 23, 16, 25, 18, 27, 20, 26, 22, 24]
[22, 24, 20, 26, 18, 27, 16, 25, 14, 23, 12, 21, 10, 19, 8, 17, 6, 15, 4, 13, 2, 11, 1, 9, 3, 7, 5]
[7, 5, 9, 3, 11, 1, 13, 2, 15, 4, 17, 6, 19, 8, 21, 10, 23, 12, 25, 14, 27, 16, 26, 18, 24, 20, 22]
[20, 22, 18, 24, 16, 26, 14, 27, 12, 25, 10, 23, 8, 21, 6, 19, 4, 17, 2, 15, 1, 13, 3, 11, 5, 9, 7]
[9, 7, 11, 5, 13, 3, 15, 1, 17, 2, 19, 4, 21, 6, 23, 8, 25, 10, 27, 12, 26, 14, 24, 16, 22, 18, 20]
[18, 20, 16, 22, 14, 24, 12, 26, 10, 27, 8, 25, 6, 23, 4, 21, 2, 19, 1, 17, 3, 15, 5, 13, 7, 11, 9]
[11, 9, 13, 7, 15, 5, 17, 3, 19, 1, 21, 2, 23, 4, 25, 6, 27, 8, 26, 10, 24, 12, 22, 14, 20, 16, 18]
[16, 18, 14, 20, 12, 22, 10, 24, 8, 26, 6, 27, 4, 25, 2, 23, 1, 21, 3, 19, 5, 17, 7, 15, 9, 13, 11]
[13, 11, 15, 9, 17, 7, 19, 5, 21, 3, 23, 1, 25, 2, 27, 4, 26, 6, 24, 8, 22, 10, 20, 12, 18, 14, 16]
[14, 16, 12, 18, 10, 20, 8, 22, 6, 24, 4, 26, 2, 27, 1, 25, 3, 23, 5, 21, 7, 19, 9, 17, 11, 15, 13]
[15, 13, 17, 11, 19, 9, 21, 7, 23, 5, 25, 3, 27, 1, 26, 2, 24, 4, 22, 6, 20, 8, 18, 10, 16, 12, 14]
[12, 14, 10, 16, 8, 18, 6, 20, 4, 22, 2, 24, 1, 26, 3, 27, 5, 25, 7, 23, 9, 21, 11, 19, 13, 17, 15]
[17, 15, 19, 13, 21, 11, 23, 9, 25, 7, 27, 5, 26, 3, 24, 1, 22, 2, 20, 4, 18, 6, 16, 8, 14, 10, 12]
[10, 12, 8, 14, 6, 16, 4, 18, 2, 20, 1, 22, 3, 24, 5, 26, 7, 27, 9, 25, 11, 23, 13, 21, 15, 19, 17]
[19, 17, 21, 15, 23, 13, 25, 11, 27, 9, 26, 7, 24, 5, 22, 3, 20, 1, 18, 2, 16, 4, 14, 6, 12, 8, 10]
[8, 10, 6, 12, 4, 14, 2, 16, 1, 18, 3, 20, 5, 22, 7, 24, 9, 26, 11, 27, 13, 25, 15, 23, 17, 21, 19]
[21, 19, 23, 17, 25, 15, 27, 13, 26, 11, 24, 9, 22, 7, 20, 5, 18, 3, 16, 1, 14, 2, 12, 4, 10, 6, 8]
[6, 8, 4, 10, 2, 12, 1, 14, 3, 16, 5, 18, 7, 20, 9, 22, 11, 24, 13, 26, 15, 27, 17, 25, 19, 23, 21]
[23, 21, 25, 19, 27, 17, 26, 15, 24, 13, 22, 11, 20, 9, 18, 7, 16, 5, 14, 3, 12, 1, 10, 2, 8, 4, 6]
[4, 6, 2, 8, 1, 10, 3, 12, 5, 14, 7, 16, 9, 18, 11, 20, 13, 22, 15, 24, 17, 26, 19, 27, 21, 25, 23]
[25, 23, 27, 21, 26, 19, 24, 17, 22, 15, 20, 13, 18, 11, 16, 9, 14, 7, 12, 5, 10, 3, 8, 1, 6, 2, 4]
[2, 4, 1, 6, 3, 8, 5, 10, 7, 12, 9, 14, 11, 16, 13, 18, 15, 20, 17, 22, 19, 24, 21, 26, 23, 27, 25]
[27, 25, 26, 23, 24, 21, 22, 19, 20, 17, 18, 15, 16, 13, 14, 11, 12, 9, 10, 7, 8, 5, 6, 3, 4, 1, 2]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27]

```

Have fun golfing!

# Answer
# TI-Basic (83 series), ~~58~~ ~~57~~ 54 bytes (104 characters)

```
:seq(I,I,1,Ans→A
:Ans→B
:Repeat prod(Ans=ᶫB
:ᶫB→C
:int(⁻Ans/2→D
:SortD(ᶫC,ᶫA
:SortD(ᶫD,ᶫA
:Pause ᶫA
:End

```

### Explanation

Takes input in `Ans` (e.g., write `5:prgmNAME` to use lists of size five).

Creates three auxiliary lists of the given size (which are recreated from `ᶫB` at each step): `ᶫB = ᶫC = {1,2,3,4,5,...}` and `ᶫD = {-1,-1,-2,-2,-3,...}`. At each step, sorts `ᶫC` and `ᶫD` in descending order, applying the same permutation to `ᶫA`. In the case of `ᶫC`, this reverses `ᶫA`, and in the case of `ᶫD`, this swaps adjacent pairs because TI-Basic uses a **really stupid selection sort implementation** for `SortD(` which reorders as many identical elements as it possibly can. When `ᶫA` is equal to `ᶫB` again, we stop.

No, seriously, their built-in sorting algorithm is my second-biggest complaint with the TI-Basic interpreter. (My biggest complaint is how lots of nested loops slow down the interpreter, since the loop data is stored in a stack, but the stack is grown from the wrong end, so the calculator has to *move the entire stack* every time an element is pushed or popped.) But this time, it's convenient.

---

-1 byte: `Pause` stores the value it's printing to `Ans`, which is shorter to reference than `ᶫA`.

-3 bytes: take input in `Ans`
> 16 votes

# Answer
# Jelly, 10 bytes

```
RµUs2UFµÐĿ

```

Try it online!

# Explanation

```
RµUs2UFµÐĿ  Main link
R           Generate the range
        ÐĿ  While the results are unique (collecting results)
 µUs2UFµ    Reverse and reorder
  U         Reverse
   s        Slice non-overlapping into length
    2       2
     U      Reverse (automatically vectorizes to depth 1)
      F     Flatten

```

# Note

If the original range *needs* to be at the end, append `ṙ1` to the code for 12 bytes.
> 7 votes

# Answer
# 05AB1E, ~~13~~ 11 bytes

```
LIGÂ2ôí˜})Ù

```

Try it online!

**Explanation**

```
L             # range [1 ... input]
 IG           # input-1 times do:
   Â          # bifurcate
    2ô        # split into pieces of 2
      í       # reverse each
       ˜      # flatten
        }     # end loop
         )    # wrap stack in a list
          Ù   # remove duplicates

```
> 5 votes

# Answer
# JavaScript (ES6), ~~89~~ 85

*Edit* 4 bytes saved thx @JustinMariner

Using the fact that when any element is at the right place, all elements are.

```
n=>{for(l=[];n;l[n-1]=n--);while(alert(l=l.reverse().map((x,i)=>l[i^1]||x)),l[0]-1);}

```

*Less golfed*

```
n => {
  for(l=[], i=0; i<n; l[i] = ++i);
  while( alert(l=l.reverse().map( (x,i) => l[i^1] || x)),
         l[0]-1);
}

```

**Test**

```
var F=
n=>{for(l=[];n;l[n-1]=n--);while(alert(l=l.reverse().map((x,i)=>l[i^1]||x)),l[0]-1);}

alert=x=>console.log(x+'') // to avoid popup stress

function update() {
  F(+I.value);
}

update()
```

```
<input type=number id=I value=1 min=1 oninput='update()'>
```
> 4 votes

# Answer
# R, ~~109~~ ~~95~~ ~~94~~ ~~79~~ ~~74~~ 62 bytes

If the fact that the code throws warnings on top of the actual solution (no warnings if `n` is 1, 3 warnings if `n` is even and `n` warnings if `n` is odd) is not an issue, then the following works similarly to the previous solution, thanks to vector recycling:

```
n=scan();m=1:n;w=0:n+2*1:0;while(print(m<-rev(m)[w[w<=n]])-1)n

```

Try it online!

Thanks again to @Giuseppe for an extra 12 bytes off!

**Previous, warning-less solution at 94 bytes:**

```
n=scan();m=s=1:n;while(any(print(m<-rev(m)[c(if(n>1)2:1+rep(seq(0,n-2,2),e=2),n[n%%2])])!=s))n

```

Try it online!

**Original solution at 109 bytes**:

```
n=scan();m=s=1:n;repeat{cat(m<-rev(m)[c(t(embed(s,min(n,2))[!!s[-n]%%2,]),n[n%%2])],"\n");if(all(m==s))break}

```

Try it online!
> 4 votes

# Answer
# Mathematica, 142 bytes

```
(h=Range@#;W={};For[i=1,i<=#,i++,s=Reverse@h;AppendTo[W,h=Join[f=Flatten[Reverse/@Partition[s,{2}]],s~Complement~f]];s=h];DeleteDuplicates@W)&

```
> 3 votes

# Answer
# Japt, ~~20~~ ~~18~~ ~~15~~ 12 bytes

```
õ
£=ò2n)ÔcÃâ

```

Try it (`-R` flag for visualisation purposes only)

1 byte saved thanks to ETHproductions.

```
               :Implicit input of integer U
õ              :Range [1,U]
\n             :Reassign to U
£              :Map
  ò            :  Partitions
   2           :    Of length 2
    n          :    Starting from the end
     )         :  End partition
      Ô        :  Reverse
       c       :  Flatten
 =             :  Reassign to U
        Ã      :End map
         â     :Deduplicate

```
> 3 votes

# Answer
# Husk, 9 bytes

```
U¡ȯṁ↔C2↔ḣ

```

Try it online!

```
            -- implicit input N                 |  3
         ḣ  -- list [1..N]                      | [1,2,3]
 ¡(     )   -- iterate the following function,  | [[1,2,3],[2,3,1],[3,1,2],[1,2,3],...
U           -- until the first repetition:      | [[1,2,3],[2,3,1],[3,1,2]]
       ↔    --   reverse                        |   [3,2,1]
     C2     --   cut into two                   |   [[3,2],[1]]
   ṁ↔       --   reverse each pair & flatten    |   [2,3,1]

```
> 3 votes

# Answer
# JavaScript (ES6), 79 bytes

```
f=(n,a=[...Array(n)],b=a.map((x,i)=>n-((x?x-1:i)^1)||1))=>b[0]>1?b+`
`+f(n,b):b

```

Outputs a list for each step.

Note that we don't need to initialize the array to get the ball rolling. If uninitialized (`x` is undefined), we can use the array's indices (parameter `i`) to do the first step:

```
b=a.map((x,i)=>n-((x?x-1:i)^1)||1)

```

**Test Cases:**

```
f=(n,a=[...Array(n)],b=a.map((x,i)=>n-((x?x-1:i)^1)||1))=>b[0]>1?b+`
`+f(n,b):b

console.log(f(1));
console.log(f(2));
console.log(f(3));
console.log(f(4));
console.log(f(5));
console.log(f(7));
console.log(f(27));
```
> 3 votes

# Answer
# Ruby, ~~64 57 52~~ 50 bytes

```
->x{(s=*w=1..x).map{s=w.map{|y|s[-y^1]||s[0]}}|[]}

```

Try it online!

### How it works:

First create the range, then repeat the permutation x times: use a negative index, but flip the last bit, so we get the sequence -2, -1, -4, -3... if x is even, this will end well, if not we will add the remaining element at the end. Last step: filter out repeated arrays (so we cover all cases: x=1, x=2, odd and even numbers)
> 2 votes

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

```
g(a:b:c)=b:a:g c
g x=x
h=g.reverse
0!x|x<[2]=[x]|1<2=x:0!h x
p n=0!h[1..n]

```

Try it online!

`g` does the pair-wise swaps, `h` a single step (reverse + reorder), `!` repeatedly applies `h` (and collects the intermediate results) until the order is restored. Note: `!` takes the additional but unused extra parameter `0` just to make it an infix operator. The main function `p` starts it up.

Edit: Thanks to @Angs for a byte.
> 2 votes

# Answer
# Stax, 17 bytes

```
âΩÄ─g╫B♥C╛♠ƒ?|πcD

```

Run and debug it

**Explanation**

```
RX~Wr2/{r+}Fc|uPcx=C      # Full program, unpacked, implicit input
RX~                       # Create range, save to X register, pop back to input stack
   W                      # Start while loop until truthy value
    r                     # reverse array
     2/                   # Split into groups of 2
      {r+}F               # Loop through each set and reverse each
           c              # Copy top value
            |u            # Convert to string representation of array
              P           # Pop top value off
               cx=        # Copy top value, get value of x register, compare to top value
                  C       # If top value is truthy, cancel block and end

```

Suprised it works as fast as it does, tested up to 399 before I didn't want to temp my browser anymore.
> 2 votes

# Answer
# Python 2, ~~165~~ ~~159~~ ~~138~~ 81 bytes

```
x=input()+1
b=a=range(1,x)
while b:b=[b[x-min(x,i+1^1)]for i in a];print b;b*=a<b

```

Try it online!

*-20 bytes thanks to @ChasBrown*. (Sigh, I made a whole challenge about extended slicing syntax)

Whoa! GolfStorm (-57 bytes)! Thanks to Ian Gödel, tsh, and Jonathan Frech.
> 1 votes

# Answer
# Java 8, ~~215~~ 214 bytes

```
import java.util.*;n->{Stack a=new Stack(),t;int i=0;for(;i<n;a.add(++i));t=(Stack)a.clone();Collections x=null;for(i=0;i<1|!a.equals(t);System.out.println(t))for(x.reverse(t),i=0;i<n;i++)if(i<n-1)x.swap(t,i,++i);}

```

I tried to golf it using actual arrays instead of a List, but both reversing and swapping will take up too many bytes.. Maybe it can be combined in one loop (instead of first reversing, then swapping), but I've yet to figure this out.
This can definitely be golfed some more, though.

**Explanation:**

Try it here.

```
import java.util.*;           // Required import for Stack and Collections

n->{                          // Method with integer parameter and no return-type
  Stack a=new Stack(),        //  Original List
        t;                    //  Copy-List
  int i=0;                    //  Index-integer, starting at 0
  for(;i<n;a.add(++i));       //  Fill the original list with the integers
  t=(Stack)a.clone();         //  Make a copy of the List
  Collections x=null;         //  Static `Collections` to reduce bytes
  for(i=0;                    //  Reset index `i` to 0
      i<1                     //  Loop (1) as long as `i` is 0 (the first iteration),
      |!a.equals(t);          //  or the input array is not equal to the copy
      System.out.println(t))  //    After every iteration: print the modified List
    for(x.reverse(t),         //   Reverse the copied List
        i=0;                  //   Reset `i` to 0
        i<n;                  //   Inner loop (2) over the List
        i++)                  //     After every iteration: increase `i` by 1 again
      if(i<n-1)               //    Unless it's the last item in the List:
        x.swap(t,i,++i);      //     Swap the items at indexes `i` and `i+1`
                              //     (by increasing `i` by 1 first with `++i`)
                              //   End of inner loop (2) (implicit / single-line body)
                              //  End of loop (1) (implicit / single-line body)
}                             // End of method

```
> 1 votes

# Answer
# Java (OpenJDK 8), ~~257~~ ~~245~~ ~~243~~ ~~226~~ ~~206~~ 205 bytes

```
n->{int i=0,k,t[]=new int[n];while(i<n)t[i]=++i;do{for(i=0;i<n/2;t[i]=t[n+~i],t[n+~i++]=k)k=t[i];for(k=1;k<n;t[k]=t[--k],t[k]=i,k+=3)i=t[k];System.out.println(java.util.Arrays.toString(t));}while(t[0]>1);}

```

Try it online!
> 1 votes

# Answer
# MATL, 17 bytes

```
:`tP2ePXz!tG:-a]x

```

Try it online!

### Explanation

```
:       % Implicit input: n. Push [1 2 ... n]
`       % Do...while
  t     %   Duplicate
  P     %   Reverse
  2e    %   Reshape into a 2-row matrix. A final 0 is added if needed
  P     %   Reverse each column
  Xz    %   Nonzero entries (i.e. remove final 0 if present). Gives a column vector
  !     %   Transpose into a row
  t     %   Duplicate
  G:    %   Push [1 2 ... n] again
  -     %   Subtract element-wise
  a     %   Any. Gives true if there is at least a nonzero value
]       % End. Go to next iteration if top of the stack is true.  So the loop ends
        % when [1 2 ... n] has been found again
x       % Delete top of the stack (which is [1 2  ... n]). Implicit display

```
> 1 votes

# Answer
# GolfScript, 33 bytes

Nope, I can't simplify the algorithm.

```
~),1>:a{-1%2/{-1%}%{+}*.p.a=!}do;

```

Try it online!

## Explanation

```
~                                 # Dump the input
 ),                               # Generate inclusive range: 0 -> input
   1>:a                           # Set [1 2 ... input-1 input] to a without popping
       {                     }do  # Do ... While
                         .a=!     # The current item does not equal to a
        -1%                       # Reverse the item
           2/                     # Split into equal parts of 2
             {-1%}%               # For each equal part, reverse
                   {+}*           # Flatten the list
                       .p         # Print the list
                                ; # We don't need to implicit output the
                                  # extra value left on the stack

```
> 1 votes

# Answer
# Vyxal 3 `j`, 8 bytes

```
ɾᶨλṚ2ẆVf

```

Try it Online!
> 1 votes

# Answer
## JavaScript (ES6), 122 bytes

```
f=(n,a=[...Array(n)].map((_,i)=>i+1),r=[],b=a.map((_,i)=>a[n+~(i^1)]||a[0]))=>b.some((e,i)=>e>b[i+1],r.push(b))?f(n,b,r):r

```

`r.push(a)` could be used instead of `r.push(b)` to put the original permutation at the front.
> 0 votes

# Answer
# Haskell, 97 bytes

This feels a bit long :(

```
f n|x<-[1..n]=x:takeWhile(/=x)(tail$iterate((r=<<).g.r)x)
r=reverse
g[]=[]
g x=take 2x:g(drop 2x)

```

Try it online!

### Explanation/Ungolfed

```
-- starting with x, accumulate the results of repeatedly
-- applying the function permute
f n = x : takeWhile (/=x) (tail $ iterate permute x)
  where x = [1..n]
        -- reverse, cut2, reverse each pair & flatten
        permute = concatMap reverse . cut2 . reverse

-- recursively transform a list into groups of 2
cut2 [] = []
cut2 xs = take 2 xs : g (drop 2 xs)

```
> 0 votes

# Answer
# Stacked, 42 bytes

```
[~>[rev 2#<$revflatmap]periodsteps behead]

```

Try it online!

Performs the given transformation using the `periodsteps` builtin. However, this builtin returns all of the elements, which includes the input's range as its first and last elements. We therefore behead the list, returning all but the first element.
> 0 votes

# Answer
# AWK, 123 bytes

Not very tight, but this is the best I could come up with.

```
{for(N=$1;N>$i=++i;);for(;n++<(i%2?i:i>2?2:1);){for(k=0;k++<i;)K[k]=(z=i-k+(k-1)%2*2)?$z:$1;for(k=0;k++<N;){$k=K[k]}print}}

```

Try it online!
> 0 votes

# Answer
# JavaScript, 136 bytes

```
(n)=>{for(a=[],i=0;i<n;a[i]=++i);for(j=0;j<(n&1?n:2);j++){a.reverse();for(i=0;i<a.length-1;i += 2)m=a[i],a[i]=a[i+1],a[i+1]=m;alert(a)}}

```
> 0 votes

# Answer
# TypeScript’s type system, ~~203~~ ~~193~~ ~~190~~ 183 bytes

```
//@ts-ignore
type F<N,A=[],E=A,O=N,G=[...N,...A]>=N extends[1,...infer D]?F<D,[N,...A]>:A extends[...infer R,infer X,infer Y]?F<[...N,X,Y],R,E,O>:E extends O[any]?O:F<[],G,E,[...O,G]>

```

Try it at the TS playground

This is a generic type `F`, which takes input as a tuple type of 1s representing a unary number, and outputs a list of unary numbers in the same format.

I can’t believe I got this all to fit in a single type. This is definitely one of the coolest TS types submissions I’ve posted.

## Explanation

The `//@ts-ignore` comment on the first line tells the compiler to suppress any warnings from the following line.

The beginning of the type describes its arguments:

```
type F<N,A=[],E=A,O=N,G=[...N,...A]>

```

What the arguments do is explained later, but you should know that `G` is an alias for N with A appended to it; it comes in handy later.

The type has three “stages”, which are entered at different times in the evaluation of the type.

* The first stage converts the unary number to the range of unary numbers between 1 and the input. (At this stage, the input is in N, and A is the empty tuple.)

```
N extends[1,...infer D]

```

Is the first item of N a one? If so, remove it and call the rest D, and…

```
F<D,[N,...A]>

```

…recurse, with N set to D, and with N prepended to A.

By the end of stage 1, A will contain the range from 1 to the input, E will be set equal to A, and N and O will both be the empty tuple.

(E is the initial step; this will be how the type knows to terminate. O will be the list of intermediate results, which will be the final return value.)
* If the first stage was not entered, because N is either empty or contains elements that aren’t ones, then the second stage is entered, to reverse and reorder the elements of A.

```
A extends[...infer R,infer X,infer Y]

```

If A has two or more items, call the last two X and Y respectively, and the rest R.

```
F<[...N,X,Y],R,E,O>

```

Recurse, appending X and Y to N, setting A to R, and keeping the values of E and O as they already are.

By the end of this stage, N will contain the reversed and reordered items of A. A will be empty if it originally had an even number of items, but if its length was odd then it will contain the last item to be appended to N. This is a minor pain point of the solution, adding 14 bytes to alias G to N with A appended.
* The third stage does the “repeat” step.

```
E extends O[any]?O

```

If E (the initial result) is contained in O (the list of intermediate results), then the program is finished; return O.

```
F<[],G,E,[...O,G]>

```

Otherwise, recurse with N set to the empty tuple (skipping stage 1 and going straight to stage 2), A set to G (the alias for N with A appended), E left unchanged, and O with G appended.
> 0 votes

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

```
$_=$;=join$",1..$_;do{$_=join$",reverse/\d+/g;s/(\d+) (\d+)/$2 $1/g;$\+=say}until$;eq$_}{

```

Try it online!
> 0 votes

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


title: Iteratively sort a list

text:
# Question
Title: Iteratively sort a list
Given a list of Integers greater than zero, Sort each of the unique values in ascending order, then repeat the process on the remaining duplicate values and append.

Example:

```
[1,5,2,2,8,3,5,2,9] ==> [1,2,3,5,8,9,2,5,2]
[8,5] ==> [5,8]
[2,2,2] ==> [2,2,2]

```

# Answer
> 10 votes
# Haskell, 44 bytes

```
import Data.List
concat.transpose.group.sort

```

Try it online! (has an extra 2 bytes for `f=`)

# Answer
> 8 votes
# Jelly, 5 bytes

```
ṢŒgZF

```

Try it online!

A monadic link taking an unsorted list of integers and returning the list sorted as described.

## Explanation

```
Ṣ     | Sort
 Œg   | Group runs of identical digits together
   Z  | Transpose
    F | Flatten

```

# Answer
> 7 votes
# Vyxal, 28 bitsv2, 3.5 bytes

```
sĠ∩f

```

Try it Online!

Bitstring:

```
1000100001100101100111101000

```

Port of the Uiua answer except without the 0 filling because it's not needed here. And they say having a fixed array model is a good thing! :p

## Explained

```
sĠ∩f
s     # Sort the input
 Ġ    # Group on consecutive items
  ∩   # Transpose
   f  # and flatten

```

Created with the help of Luminespire.

# Answer
> 7 votes
# Uiua, 11 bytes

```
▽≠0.♭⍉⬚0⊕∘.

```

Try it!

* `.` duplicate input

* `⬚0⊕∘` group by identity, filling with zeros

* transpose

* deshape

* `▽≠0.` keep non-zeros

# Answer
> 6 votes
# Nekomata \+ `-1`, 5 bytes

```
oOᵐůj

```

Attempt This Online!

```
oOᵐůj
o       Sort
 O      Find a set partition
  ᵐů    such that no part contains duplicates
    j   Join

```

The flag `-1` finds only the first solution.

The built-in `O` (`\setPartition`) uses the following algorithm (taken from Curry's Combinatorial package), which ensures that the first solution is exactly the one we want:

```
partition    :: [a] -> [[a]]
partition [] = []
partition (x:xs) = insert x (partition xs)
    where insert e [] = [[e]]
          insert e (y:ys) = ((e:y):ys) ? (y:insert e ys)

```

# Answer
> 6 votes
# Jelly, 4 bytes

```
ĠZFị

```

A monadic Link that accepts a list and yields the "sorted" list.

**Try it online!**

### How?

```
ĠZFị - Link: list A            e.g. [8,8,8,3,7,7,3,3]
Ġ    - Group indices of A by value  [[4,7,8],[5,6],[1,2,3]]
 Z   - transpose                    [[4,5,1],[7,6,2],[8,3]]
  F  - flatten                      [4,5,1,7,6,2,8,3]
   ị - index into A                 [3,7,8,3,7,8,3,8]

```

# Answer
> 5 votes
# , 40 bytes

```
function(x)x[order(ave(!x,x,FUN=seq),x)]

```

Try it online!

Shorter to use `order` than `split`.

# , 55 bytes

```
function(x,y=sort(x))unlist(split(y,ave(!y,y,FUN=seq)))

```

Try it online!

Noticed the `split` and `ave` characterization about 2 minutes after posting the longer answer below. Rough R equivalent to the Jelly answer.

# , 73 bytes

```
f=function(x,o={},d=duplicated(x))'if'(sum(x),f(x[d],c(o,sort(x[!d]))),o)

```

Try it online!

Naive implementation: sort unique values and recurse on remainder, appending as you go. Probably there's a shorter way.

# Answer
> 5 votes
# Haskell, ~~62~~ 52 bytes

```
import Data.List
f[]=[]
f x|z<-sort$nub x=z++f(x\\z)

```

Try it online!

# Answer
> 5 votes
# , 13 bytes

```
/:],.~1#.]=]\

```

Try it online!

* `/:` Sort by
* `1#.]=]\` Running sum count of each unique value *first*
* `,.~` Followed by
* `]` The original value

That is, we form pairs `<running count for this value, this value>` and sort by those pairs.

# Answer
> 4 votes
# JavaScript (Node.js), 45 bytes

Expects an `Uint16Array` filled with unsigned bytes and returns a `Buffer`.

```
a=>Buffer(a.map(o=v=>o[v]=o[v]+256|v).sort())

```

Try it online!

### Commented

```
a =>             // a[] = input Uint16Array
Buffer(          // coerce to bytes:
  a.map(o =      //   o = object to keep track of the number
                 //       of times each value appears
  v =>           //   for each value v in a[]:
    o[v] =       //     update o[v]:
      o[v] + 256 //       increment the high byte
                 //       (no effect on the 1st iteration)
      | v        //       use v as the low byte
  )              //   end of map()
  .sort()        //   sort the 16-bit values
)                // end of Buffer()

```

---

# JavaScript (ES6), 51 bytes

Expects an `Uint16Array` filled with unsigned bytes and returns an array in the same format.

(This version could be updated to support larger integers at the cost of a few extra bytes.)

```
a=>a.map(o=v=>o[v]=o[v]+256|v).sort().map(v=>v&255)

```

Try it online!

# Answer
> 4 votes
# BQN, 6 bytes

```
⍋∘⊒⊸⊏∧

```

Try it online!

Or alternatively, `∾⊒⊸⊔∘∧`

# Answer
> 3 votes
# Retina 0.8.2, 38 bytes

```
mO$`(.+)(?<=((^\1$)|.|¶)*)
$#3$*1,$&$*

```

Try it online! Takes input on separate lines but link splits on commas for convenience. Explanation: Sorts each value by a key made up of its occurrence count and value, expressed in unary.

@TwiNight's idea of sorting twice (since the sort is stable) saves 10 bytes, since the second sort doesn't have to guard against extraneous matches:

```
O#`
O#$`(.+)(?<=(¶?\1)+)
$#2

```

Try it online! Takes input on separate lines but link splits on commas for convenience.

Note that each link can be turned into a test suite by prefixing `%(` to the header.

# Answer
> 3 votes
# APL (Dyalog Classic), 15 bytes

-2 bytes thanks to att.

```
{0~⍨,⍉⊣¨⌸⍵[⍋⍵]}

```

Try it online!

**Explanation**

```
{0~⍨,⍉⊣¨⌸⍵[⍋⍵]}
{                 }  # dfn
           ⍵[⍋⍵]   # sort
       ⊣¨⌸          # groups into matrix, padding with zeros
     ⍉              # transpose
    ,                # ravel (flatten)
 0~⍨                 # remove zeros

```

Created with the help of Luminespire.

I think that using a *dfn* rather than tacit is probably shorter here, since we are applying a bunch of monadic functions, and sorting is no shorter in tacit: `⊂∘⍋⌷⊢`.

# Answer
> 3 votes
# Retina, ~~30~~ 26 bytes

```
N`
N$`(.+)(?<=(¶?\1)+)
$#2

```

Attempt This Online!

Edit: -4 bytes thanks to Neil, by changing I/O format

Input and output are newline-separated decimals.

First sort normally, then sort (stably) again using the occurrence index

# Answer
> 3 votes
# BQN (CBQN), 10 bytes

```
{∾∧¨⊔˜⊒}

```

Attempt This Online!

# Answer
> 3 votes
# Perl 5 `-MList::Util=uniq -a`, 59 bytes

```
map$t{$_}++,@F;1while@F=grep{say;--$t{$_}}sort{$a-$b}uniq@F

```

Try it online!

# Answer
> 3 votes
# Ruby, 41 bytes

```
->l,*r{l.sort_by{|x|[(r<<x).count(x),x]}}

```

Try it online!

# Answer
> 3 votes
# PowerShell Core, 73 bytes

```
$f={param($a)if($a){($g=$a|group).Name
&$f($g|%{,$_.Name*($_.Count-1)})}}

```

Try it online!

Recursive function
Takes an array as a parameter
Returns an array

### Explanation

```
param($a)                    # The array in variable $a
if($a){...}                  # If the array is empty, do nothing, otherwise:
($g=$a|group).Name           # Group the numbers in the array, store the groups in $g and return the unique elements sorted
$g|%{,$_.Name*($_.Count-1)}  # From the groups, rebuild a list with one element less for each elements
&$f(...)                     # Recursively invoke the function on the rebuilt list

```

# Answer
> 3 votes
# Brachylog, 5 bytes

```
oḅz₁c

```

Try it online!

### Explanation

```
o        Sort in ascending order
 ḅ       Group consecutive elements together
  z₁     Zip without cycling
    c    Concatenate

```

# Answer
> 2 votes
# Charcoal, 24 bytes

```
ＵＭθ⟦№…θκιι⟧Ｗ⁻θυ⊞υ⌊ιＩＥυ⊟ι

```

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

```
ＵＭθ⟦№…θκιι⟧

```

Replace each value with a tuple of its occurrence index and value.

```
Ｗ⁻θυ⊞υ⌊ι

```

Sort the tuples into order.

```
ＩＥυ⊟ι

```

Output the sorted values.

# Answer
> 2 votes
# 05AB1E, 5 bytes

```
{γζ˜þ

```

Try it online.

**Explanation:**

```
{      # Sort the (implicit) input-list
 γ     # Group it into equal adjacent values
  ζ    # Zip/transpose; swapping rows/columns,
       # using " " implicitly as filler for unequal length lists
   ˜   # Flatten this list of lists
    þ  # Remove all " " by only keeping integers
       # (after which the resulting list is output implicitly)

```

# Answer
> 2 votes
**APL(NARS), 23 chars**

```
{0≥≢⍵:⍬⋄a[⍋a],∇⍵∼⍦a←∪⍵}

```

use:

```
  {0≥≢⍵:⍬⋄a[⍋a],∇⍵∼⍦a←∪⍵}1 5 2 2 8 3 5 2 9
┌9─────────────────┐
│ 1 2 3 5 8 9 2 5 2│
└~─────────────────┘

```

zilde has to be as void set for all the types

# Answer
> 2 votes
# APL+WIN, 30 bytes

Prompts for list of integers:

```
(,⍉⊃(⌈/¨⍴¨n)↑¨n←n⊂n←m[⍋m←⎕])~0

```

Try it online! Thanks to Dyalog Classic

# Answer
> 2 votes
# JavaScript (Node.js), 62 bytes

```
a=>a.map(t=$=>[t[$]=9+t[$]||Array($)+t,$]).sort().map(x=>x[1])

```

Try it online!

# Answer
> 2 votes
# Japt, 5 bytes

```
ü Õcf

```

Try it

```
ü Õcf     :Implicit input of array
ü         :Group & sort by value
  Õ       :Transpose
   c      :Flatten after
    f     :  Filtering (to remove null values)

```

# Answer
> 2 votes
# Haskell \+ hgl, 11 bytes

```
cx<tx<sr<bg

```

Attempt This Online!

## Alternative

```
cx<tx<gr<sr

```

Attempt This Online!

## Explanation

* `bg` group the input into bags of equal elements
* `sr` sort the bags by value
* `tx` transpose
* `cx` concat

## Reflection

There are a couple of ways hgl could be improved I'm seeing here:

* There are two options for how to sort the bags in `bg`

+ Sort by how many items are in a bag
    + Sort by how early the earliest item appears

Neither of these is really helpful in this case. It might be nice to have a case function to sort by the value in the bags which would save us here, but really we need an option for the user to specify how to sort (wouldn't help here since `sr<bg` is already quite short).
* There's probably an argument to be made to have a combined `cx<tx`. I can see that being used in more places than just here.

# Answer
> 2 votes
# Python, 53 bytes

```
f=lambda L:[*map(L.remove,x:={*L})]and sorted(x)+f(L)

```

Attempt This Online!

Straight-forward method used by many other answers previously: Pick, sort and remove uniques and start over.

# Answer
> 1 votes
# Scala 3, 118 bytes

A Port of @matteo\_c's Haskell answer in Scala.

---

Golfed version. Attempt This Online!

```
_ match{case Nil=>Nil;case x=>x.sorted.distinct++f(x.sorted.groupBy(identity).mapValues(_.tail).values.flatten.toSeq)}

```

Ungolfed version. Attempt This Online!

```
object Main extends App {
  def f(lst: List[Int]): List[Int] = lst match {
    case Nil => Nil
    case x =>
      val sorted = x.sorted
      val distinctElements = sorted.distinct
      val groupedElements = sorted.groupBy(identity).mapValues(_.tail).values.flatten.toList
      distinctElements ++ f(groupedElements)
  }

  val testcases = List(
    (List(1, 5, 2, 2, 8, 3, 5, 2, 9), List(1, 2, 3, 5, 8, 9, 2, 5, 2)),
    (List(4, 4, 4), List(4, 4, 4)),
    (List(8, 5), List(5, 8)),
    (List[Int](), List[Int]())
  )

  testcases.foreach { case (input, expectedOutput) =>
    assert(f(input) == expectedOutput, s"Test failed for input: $input")
  }

  println("All tests passed!")
}

```

# Answer
> 1 votes
# Desmos, 63 bytes

```
f(l)=sort(l,[l[1...i][l=l[i]].countfori=[1...l.count]]2l.max+l)

```

Port of some other answers which sort by running occurrence count and value of the corresponding element.

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 1 votes
**, 51 Bytes**

```
{$[x~();x;asc[key g],.z.s x asc(,/)_[1]'[g:(=:)x]]}

```

The above function takes an implicit parameter, *x*, and:

* returns *x* if it is empty
* otherwise, groups the items in *x* using K function *=:* which is equivalent to Q function *group*. This yields a dictionary where each key is a unique items in *x* and each value is a list of the indexes at which the item occurs in *x*
* and returns:

1. the sorted, unique items in *x*. The unique items are found by taking the keys of the group dictionary

concatenated with

2. the results of a recursive call to the function (*.z.s*) with the remaining items as the parameter. The remaining items are found by dropping the first index from each list in the group dictionary values (using *\_\[1\]'*), merging the lists (using *,/*), and grabbing the items at those indices from *x*

# Answer
> 1 votes
# C# (Visual C# Compiler), 317 bytes

```
using System.Linq;class P{static void Main() => System.Console.WriteLine(string.Join(", ", S(new ushort[] { 1, 5, 2, 2, 8, 3, 5, 2, 9 }))); static ushort[] S(ushort[] a) => a.Select(v => o[v] = (ushort)(o[v] + 256 | v)).OrderBy(x => x).Select(v => (ushort)(v & 255)).ToArray(); static ushort[] o = new ushort[65536];}

```

Try it online!

# Answer
> 1 votes
# Julia 1.0, ~~56~~ 53 bytes

```
~a=a>[] ? [sort!(a)[(d=diff([0;a])).>0];~a[d.<1]] : a

```

Try it online!

sort the array, take each first occurence with diff, and recurse

---
Tags: code-golf, sorting
---


# Question
Title: Translate Japanese hiragana into the flick input method
The flick input method is a way of inputting Japanese kana on a modern smartphone. It is arranged in a 12-key layout, with the following labels:

```
あかさ
たなは
まやら
小わ、

```

When a key is tapped, it produces its respective kana. However, when the key is flicked in one of the four cardinal directions (up, down, left, right) it produces the kana with the respective vowel:

```
 u
iae
 o

```

where the center vowel is the key, just tapped and not flicked.

So, when the  key is swiped up, it will produce the  kana.

A special key is the  key. By default, just tapping on the  key will cycle the previous kana between it's "small" and "large" forms.

Swiping down-left will apply a dakuten, and down-right a handakuten, if it can be applied to the kana.

For this challenge, the  key will have the following flick mapping:

```
　小
゛小゜
　゛　<-- this is a dakuten

```

Kana with dakuten, handakuten, and small forms are in the table below. If the kana does not have a small form when  is pressed, it is a NOP. Similarly, if a kana does not have a dakuten or handakuten form when one is applied, it is also a NOP.

Some keys have either a special layout and punctuation characters assigned to them:

Image source: Wikimedia Commons

Note here that the  and  keys have punctuation assigned:

```
　ゆ
（や）　<-- unicode FF08, FF09
　よ

　ん
をわー　<-- unicode 30FC
　〜　　<-- unicode 301C

```

You *will* need to handle punctuation, but only on  and . **This challenge will not be using the  key.**

## Hiragana

Hiragana is Japanese's native syllabic writing system. Most hiragana can be considered as a pair of a consonant and a vowel:

|  | a | i | u | e | o |
| --- | --- | --- | --- | --- | --- |
|  |  |  |  |  |  |
| **k** |  |  |  |  |  |
| **s** |  |  |  |  |  |
| **t** |  |  |  |  |  |
| **n** |  |  |  |  |  |
| **h** |  |  |  |  |  |
| **m** |  |  |  |  |  |
| **y** |  |  |  |  |  |
| **r** |  |  |  |  |  |
| **w** |  |  |  |  |  |

"ん" is special because it is the only hiragana without a vowel.

Some hiragana can have a diacritic applied called a "dakuten" or "handakuten" that either voices the consonant (e.g. "k" to "g") or "half-voices" the consonant (only for h-series kana, from "h" to "p"). Some kana also have a small form (applies to vowels, y-series kana, and つ).

| Kana | Dakuten | Handakuten | Small |
| --- | --- | --- | --- |
| あいうえお |  |  | ぁぃぅぇぉ |
| かきくけこ | がぎぐげご |  |  |
| さしすせそ | ざじずぜぞ |  |  |
| たちつてと | だぢづでど |  |  |
| はひふへほ | ばびぶべぼ | ぱぴぷぺぽ |  |
| やゆよ |  |  | ゃゅょ |

## Input

Input is a string of hiragana using any reasonable input format: a string, a list/array of characters, a sequence of raw Unicode bytes, etc.

## Output

Output is a sequence of inputs for the 12-key flick input method. You may use any reasonable output format. However, each input in the sequence *must* be at least 2 distinguishable parts, and must encode at minimum the following:

* Which key is tapped, and
* Which direction it is swiped, if at all.

You must specify what encoding you use for your output. (The two-part output is to prevent mapping kana to a single value one-to-one.)

## Test Cases

For these test cases, output will be in the format of space-separated `KD`, where `K` is the kana's consonant (or "a" if it is ), and `D` is one of `58426` (directions on a numpad, 5 for no swipe). The  key will be represented as `x`.

```
かな --> k5 n5
ありがとう --> a5 r4 k5 x4 t2 a8
ありがとうございます --> a5 r4 k5 x4 t2 a8 k2 x4 s5 x4 a4 m5 s8
だがことわる -->  t5 x4 k5 x4 k2 t2 w5 r8
おまえはもうしんでいる --> a2 m5 a6 h5 m2 a8 s4 w8 t6 x4 a4 r8
かかります --> k5 k5 r4 m5 s8
あ --> a5
た --> t5
っ --> t8 x5
ぬ --> n8
ぎゅうにゅ --> k4 x4 y8 x5 a8 n4 y8 x5
やつた --> y5 t8 t5
やづた --> y5 t8 x4 t5
やった --> y5 t8 x5 t5
は --> h5
ば --> h5 x4
ぱ --> h5 x6
（わらい） --> y4 w5 r5 a4 y6
どじゃあぁーん〜 --> t2 x4 s4 x4 y5 x5 a5 a5 x5 w6 w8 w2
を --> w2

```

This is a related inverse of this post for keitai to kana.

# Answer
> 3 votes
# Python 3, ~~511~~ 410 chars

```
[print('わあ  わい  わう  やい  やえ  わお  わえ  ああ小あああ  あい小ああい  あう小ああう  あえ小ああえ  あお小ああお  かあ  かあ小おかい  かい小おかう  かう小おかえ  かえ小おかお  かお小おさあ  さあ小おさい  さい小おさう  さう小おさえ  さえ小おさお  さお小おたあ  たあ小おたい  たい小おたう小あたう  たう小おたえ  たえ小おたお  たお小おなあ  ない  なう  なえ  なお  はあ  はあ小おはあ小えはい  はい小おはい小えはう  はう小おはう小えはえ  はえ小おはえ小えはお  はお小えはお小えまあ  まい  まう  まえ  まお  やあ小あやあ  やう小あやう  やお小あやお  らあ  らい  らう  らえ  らお'[x:x+4])for x in[(ord(x)-126)%188%153%111%87%85*4for x in input()]]

```

Try it online!

more bytes since using kana as output, but they are just for output. it works the exact same in 511 bytes if you use boring ascii:

# Python 3, ~~511~~ 410 bytes

```
[print('wa  wi  wu  yi  ye  wo  we  aaxaaa  aixaai  auxaau  aexaae  aoxaao  ka  kaxoki  kixoku  kuxoke  kexoko  koxosa  saxosi  sixosu  suxose  sexoso  soxota  taxoti  tixotuxatu  tuxote  texoto  toxona  ni  nu  ne  no  ha  haxohaxehi  hixohixehu  huxohuxehe  hexohexeho  hoxehoxema  mi  mu  me  mo  yaxaya  yuxayu  yoxayo  ra  ri  ru  re  ro'[x:x+4])for x in[(ord(x)%188-126)%188%153%111%87%85*4for x in input()]]

```

Try it online!

it gives you 4 chars of output for every char of input, and you read it in pairs; ie if you give it `ぁあ` it'll give you `ああ小あ` and `ああ`  meaning the first char is made by selecting the あ key in the あ direction and the 小 key in the あ direction and that the second char is just selecting the あ key in the あ direction. (so the first is one of あかさたなはまやら小わ and the second is one of あいうえお). the tio links just have all the characters for your convenience. they're ordered by unicode codepoint, lowest to highest. any other characters you put in there will just tell you about a random key. I tried to find something mathematically that would let me build the first then the second char but there's so many exceptions that it's faster to just manually map each one.

-101 bytes because I finally got around to swapping out the if statements for modulus operations

Explanation:

```
[                #open main for loop
print(           #open print statement
'は...え'         #list of instructions, spaced at 4 chars per instruction
[x:x+4]          #chars from index x to index x+4
)                #end of print statement; print the slice we just indexed
for x in[        #says 'do the previous on each item in the coming list'
(ord(x)-126)%188 #188 is a magic number mapping the output of ord to unique values in a small range. subtracting 126 keeps the consecutive kana consecutive.
%153%111%87%85   #these slot the rest of the values which were at random locations into the start of the string.
*4               #spaces out the values we are indexing into
for x in input() #input() defaults to a string, so to iterate against it you have to add this extra loop
]                #close the input for loop and make it into a list for the main loop to iterate on
]                #close main for loop and save it as a list into a non-existent variable; we're sending output as we go along with the print statement so we don't need it

```

since it's just manually mapping to the string, adding in the punctuation key doesn't cost that much:

# Python 3, 444 chars

```
[print('わえ  、あ  、い  やい  やえ  、う  、お  わお  ああ小あああ  あい小ああい  あう小ああう  あえ小ああえ  あお小ああお  かあ  かあ小おかい  かい小おかう  かう小おかえ  かえ小おかお  かお小おさあ  さあ小おさい  さい小おさう  さう小おさえ  さえ小おさお  さお小おたあ  たあ小おたい  たい小おたう小あたう  たう小おたえ  たえ小おたお  たお小おなあ  ない  なう  なえ  なお  はあ  はあ小おはあ小えはい  はい小おはい小えはう  はう小おはう小えはえ  はえ小おはえ小えはお  はお小えはお小えまあ  まい  まう  まえ  まお  やあ小あやあ  やう小あやう  やお小あやお  らあ  らい  らう  らえ  らお  ,   わあ  .   .   わい  わう  、え  '[x:x+4])for x in[(ord(x)%195-60)%152%126%116%95*4for x in input()]]

```

Try it online!

the moduluses you preform on ord are different (`(ord(x)%195-60)%152%126%116%95`) but the idea is the same. the additional characters were added to the test cases on the tio link

# Answer
> 2 votes
# Go \+ `golang.org/x/text/unicode/runenames`, 603 bytes

```
import(."strings";."golang.org/x/text/unicode/runenames")
func f(s []rune)(o string){V,F,C,K,G,Q,I:="AIUEO","54862",Fields(".KS TNH MYR XW."),"KSTH","GZDB",CutPrefix,Index
for _,k:=range s{n,_:=Q(Name(k),"HIRAGANA LETTER ")
n,s:=Q(n,"SMALL ")
a,v:=IndexByte(G,n[0]),n[1:]
if len(n)==1{if n=="N"{o+="W8"}else{o+="A"+string(F[I(V,n)])}}else if k=='ー'{o+="W6"}else if k=='〜'{o+="W2"}else if k=='（'{o+="Y4"}else if k=='）'{o+="Y6"}else{if v=string(F[I(V,v)]);a<0{if n[0]=='P'{o+="H"+v+"X6"}else{for _,R:=range C{if i:=I(R,n[0:1]);i>-1{o+=R[i:i+1]+v}}}}else{o+=K[a:a+1]+v+"X4"}}
if s{o+="X5"}}
return}

```

You Cannot Attempt This Online!

Do it on the Playground instead!

An extremely scuffed, straightforward solution. Uses the `Name` function from `golang.org/x/text/unicode/runenames` to get the name of each kana, then selects the flick input based on that.

Output is a concatenated string of the form `Cn` where `C` is the uppercase consonant of the flick input, and `n` is one of `54862`.

## Ungolfed Explanation

```
func f(inputString []rune) (o string) {
    VOWEL := "AIUEO"
    FLICKS := "54862"
    CONSONANTS := Fields(".KS TNH MYR XW.")
    UNVOICED := "KSTH"
    VOICED := "GZDB"
// for each kana in the string...
    for _, kana := range inputString {
// cutout the Unicode prefixes
        name, _ := CutPrefix(Name(kana), "HIRAGANA LETTER ")
// we need to know if it's a small kana or not
        name, hasSmall := CutPrefix(name, "SMALL ")
// we also need to know if it's a voiced ("GZDB") kana
        voicedIndex := IndexByte(VOICED, name[0])
// and the vowel of the kana
        vowel := name[1:]
// if the kana is あいうえお or ん, just output it
        if len(name) == 1 {
            if name == "N" {
                o += "W8"
            } else {
                o += "A" + string(FLICKS[Index(VOWEL, name)])
            }
// special cases for punctuation
        } else if kana == 'ー' {
            o += "W6"
        } else if kana == '〜' {
            o += "W2"
        } else if kana == '（' {
            o += "Y4"
        } else if kana == '）' {
            o += "Y6"
// if not a voiced kana...
        } else if voicedIndex < 0 {
// if it's a handakuten kana, add to the output immediately
            if name[0] == 'P' {
                o += "H" + string(FLICKS[Index(VOWEL, vowel)]) + "X6"
// otherwise, find the kana's location
            } else {
                for _, row := range CONSONANTS {
                    i := IndexByte(row, name[0])
                    if i > -1 {
// if the (unvoiced) consonant is found, add it to the output
                        o += row[i:i+1] + string(FLICKS[Index(VOWEL, vowel)])
                    }
                }
            }
        } else {
// otherwise, it's a voiced kana, and needs the extra X
            o += UNVOICED[voicedIndex:voicedIndex+1] + string(FLICKS[Index(VOWEL, vowel)])
            o += "X4"
        }
// if it's small, add the extra X.
        if hasSmall {
            o += "X5"
        }
    }
    return o
}

```

Do the ungolfed version on the Playground!

---
Tags: code-golf, string, natural-language, unicode
---