title: Happy Birthday V!

text:
# Question
Title: Happy Birthday V!
*Thanks to @KritixiLithos for helping me out with this challenge!*

---

is a programming language that I wrote so that I could use and extend vim for code-golf challenges. The very first commit was on March 3rd, 2016, meaning that today V turns one year old! *Woo-hoo*

Over V's first year of existence, there have been 176 commits from four different contributors, 140 answers from 12 different users, and too many broken duplicate operators to count. It has an online interpreter, generously hosted by @Dennis, which has been run almost 8,000 times since December.

Let's have a challenge to celebrate V's birthday! Since most features in V are designed with string manipulation and in mind, it just seems natural that any challenge celebrating V should be about ascii art. So your challenge for today is to take a word as input, and reshape that word in the shape of a V. For example, the input "Hello" should give the following V:

```
Hello         olleH
 Hello       olleH
  Hello     olleH
   Hello   olleH
    Hello olleH
     HellolleH
      HellleH
       HeleH
        HeH
         H

```

Here are some details about what your V should look like. If the input string is *n* characters long, the V should be `n*2` lines tall. The very first line should consist of:

```
<input string><(n*2) - 1 spaces><input string reversed>

```

On each new line, one space is added to the beginning, and the two sides of the string move towards each other, removing any overlapping characters. Until the very last line, which is just the first character of input. Trailing whitespace on each line is acceptable, and a trailing newline is allowed too.

You can assume that the input will always be printable ASCII without any whitespace in it, and you may take input and output in any reasonable method. Here are some more sample inputs:

```
Happy:

Happy         yppaH
 Happy       yppaH
  Happy     yppaH
   Happy   yppaH
    Happy yppaH
     HappyppaH
      HapppaH
       HapaH
        HaH
         H

Birthday:

Birthday               yadhtriB
 Birthday             yadhtriB
  Birthday           yadhtriB
   Birthday         yadhtriB
    Birthday       yadhtriB
     Birthday     yadhtriB
      Birthday   yadhtriB
       Birthday yadhtriB
        BirthdayadhtriB
         BirthdadhtriB
          BirthdhtriB
           BirthtriB
            BirtriB
             BiriB
              BiB
               B

V!:

V!   !V
 V! !V
  V!V
   V

~:

~ ~
 ~

```

Of course, since this is , standard loopholes are banned and your goal is to write the shortest possible program to complete this task. Happy golfing!

---

*For what it's worth, I have a soft spot for vim answers, so imaginary bonus points for using vim or V, although any language is acceptable. :)*

# Answer
# MATL, ~~21~~ 14 bytes

*MATL wishes V a happy birthday!*

```
tnEXyY+c3MZvZ)

```

Try it online!

### Explanation

Consider the input

```
'Hello'

```

of length `n=5`. The code computes the 2D convolution of this string with the identity matrix of size `2*n`,

```
[1 0 0 0 0 0 0 0 0 0;
 0 1 0 0 0 0 0 0 0 0;
 0 0 1 0 0 0 0 0 0 0;
 0 0 0 1 0 0 0 0 0 0;
 0 0 0 0 1 0 0 0 0 0;
 0 0 0 0 0 1 0 0 0 0;
 0 0 0 0 0 0 1 0 0 0;
 0 0 0 0 0 0 0 1 0 0;
 0 0 0 0 0 0 0 0 1 0;
 0 0 0 0 0 0 0 0 0 1]

```

The result of the convolution, converted to char and with char 0 shown as space, is

```
['Hello         ';
 ' Hello        ';
 '  Hello       ';
 '   Hello      ';
 '    Hello     ';
 '     Hello    ';
 '      Hello   ';
 '       Hello  ';
 '        Hello ';
 '         Hello']

```

Then the columns `[1, 2, ..., 2*n-1, 2*n, 2*n-1, ..., 2, 1]` are selected from this char matrix, producing the desired result:

```
['Hello         olleH';
 ' Hello       olleH ';
 '  Hello     olleH  ';
 '   Hello   olleH   ';
 '    Hello olleH    ';
 '     HellolleH     ';
 '      HellleH      ';
 '       HeleH       ';
 '        HeH        ';
 '         H         ']

```

### Commented code

```
t      % Implicitly input string. Duplicate
nE     % Length, say n. Multiply by 2
Xy     % Identity matrix of that size
Y+     % 2D convolution. This converts chars to ASCII codes
c      % Convert to char
3M     % Push 2*n, again
Zv     % Push symmetric range [1, 2, ..., 2*n, 2*n-1, ..., 1]
Z)     % Apply as column indices. This reflects the first 2*n columns
       % symmetrically, and removes the rest. Implicitly display

```
> 46 votes

# Answer
# , ~~24, 23~~, 20 bytes

```
3Ù2Ò Íî
Xæ$òâÙHãêxx>

```

Try it online!

*Much shorter now that V has a 'reverse' operator*.

Not that impressive compared to the other golfing languages that have answered, but it had to be done. Hexdump:

```
00000000: 33d9 32d2 20cd ee0a 58e6 24f2 e2d9 48e3  3.2. ...X.$...H.
00000010: ea78 783e                                .xx>

```

Explanation:

```
3Ù                  " Make three extra copies of this current line
  2Ò                " Replace each character on this line and the next line with spaces
     Íî             " Join all lines together
X                   " Delete one space
 æ$                 " Reverse the word under the cursor

```

At this point, the buffer looks like this:

```
Happy         yppaH

```

No, we'll recursively build the triangle down.

```
ò                   " Recursively:
 â                  "   Break if there is only one non-whitespace character on this line
  Ù                 "   Make a copy of this line
   H                "   Move to the first line
    ã               "   Move to the center of this line
     ê              "   Move to this column on the last line
      xx            "   Delete two characters
        >           "   Indent this line

```

Here is where I get to show off one of my favorite features of V. Lots of commands require an argument. For example, the `>` command will indent a variable number of lines depending on the argument:

```
>>    " Indent this line (this command is actually a synonym for '>_')
>j    " Indent this line and the line below
>k    " Indent this line and the line above
6>>   " Indent 6 lines
>}    " Indent to the end of this paragraph
>G    " Indent to the last line
...   " Many many many more

```

but most commands will be forced to end with a default argument (usually the current line) if it is at the end of the program and not specified. For example, what V *actually runs* for our recursive loop is:

```
òâÙHãêxx>>ò

```

The second `ò` is implicitly filled in. The cool thing is that implicitly ended commands apply several layers deep, so even though we only wrote `>`, V will implicitly give `_` for it's argument, and it will indent the current line.
> 40 votes

# Answer
# Brainfuck, 152 bytes

This is such a momentous occasion, I decided to crack out the ol' BF interpreter and give this a spin.

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

```

## With Comments

```
++++++++++
[->+>+++<<] Insert 0 into the first buffer (Which we don't care about) 10 into the second and 30 into the thrd
>>++    Raise the third buffer to 32 making us our space
>   This buffer is reserved for the Insertable spaces counter
>
+>>>    Raise our incrementer This will be used to fill the other half of the string with spaces
,[  Read a byte
    [<]<<   Move to the back of the string buffer which is our incrementer
    +       increment it
    >>>[>]      And move to the next space of the string
    ,       And then read a new byte
]
<[<]<<-     Decrement the incrementer and begin to add spaces
[
    -       Decrement the incrementer
    >+      Raise the incrementer in the padding
    >>[>]   Move to a new part of the string buffer
    >++++[-<++++++++>]< Write a space
    [<]<<   Move all the way back to the string counter
]
BEGIN WRITING!!
>
[->++<]>[-<+>]<Double the incrementer
[
    <[  Move to the space counter
        -<+<.>> Decrement the space counter increment the temporary one to the left of it then print the space we stored to the left of that then return
    ]<[->+<]>+> Move the temporary space counter back
    -   Decrement the incrementer
    >>[.>]  Print every character from left to right
    <[-]    Snip the end off this
    <[.<]   Print every character from right to left
    <   Move back ot the incrementer
    <<<<.>>>> Print a newline aswell
]

```

Try it online!
> 31 votes

# Answer
# \>\<\>, 221 bytes

I spent **way** too much time on this. *Happy birthday, V!*

```
l:2*01           p84*/v
 !@:$-1         /!?:$<
  1.v/ ^       v\~~>a
   vv\}o<     >ao  /
    1\/84/   :}o:$-
     \\!?<: l;!?\v
      p10-1:g10r\
       >  :>?\vv
        v:$-1/~
         </r+*
          </~
           l

```

You can try it online, but it's a lot more fun to get this interpreter and run it using the `--play` flag

```
python3 fish.py v.fish -s "ppcg" --tick 0.05 --play

```

which results in the animation below.

## Example

*(it takes a little under two minutes)*

## Explanation

Because the interesting part of this answer is wrapping it in the `V` shape, here is an explanation that conforms to it. We use following line-numbered version for reference.

```
1. l:2*01           p84*/v
2.  !@:$-1         /!?:$<
3.   1.v/ ^       v\~~>a
4.    vv\}o<     >ao  /
5.     1\/84/   :}o:$-
6.      \\!?<: l;!?\v
7.       p10-1:g10r\
8.        >  :>?\vv
9.         v:$-1/~
10.         </r+*
11.          </~
12.           l

```

Sometimes arrows (→↓←) are used to indicate the direction in which a snippet is reached.

1. **Initialisation**

```
   1.→l:2*01           p84*/v
   2.  !@:$-1   X     /!?:$<
   3.   1.            \~~>a

```

The first line will push *2n* to \[0,1\], leave *n* on the stack and append one space. Next, we go up and wrap around to the second line on the right, where we will start going left. There is a loop for appending *n + 1* spaces. This works as follows.

```
                Initial:                 "ppcg4 "
!@:$-1 /!?:$<
           $     Swap.                   "ppcg 4"
          :      Duplicate.              "ppcg 44"
         ?       If more spaces to add:
    -1            Subtract 1.            "ppcg 3"
   $              Swap.                  "ppcg3 "
  :               Duplicate.             "ppcg3  "
 @                Rotate top 3.          "ppcg 3 "
!                 Jump over stored value
                         and wrap around.
                Else:
        /         Go to next part.

```

After this is finished, it bounces down to line 3. There the top two stack elements (0 and a space) are removed (`~~`) and we jump to the `X` at location \[10,1\] (`a1.`), continuing rightwards. We bump up at the `/`, wrap around to line 7 and start the main program loop.
2. **Main loop** (*2n* times do)

```
 6.              ;!?\
 7.       p10-1:g10r\   ←

```

This is the loop condition. At first, the stack is reversed for printing. Then we get the counter from \[1,0\] (`01g`) and store a decremented version (`:1-01p`). By wrapping around and bumping up and right, we encounter the conditional for terminating the program. If we don't terminate, we jump into the first printing loop.

* **First printing loop (left half)**

    ```
    5.    1\   /   :}o:$-
    6.     \\!?<: l         ←

    ```

    We start with the length on top of the stack and execute the following code as long as the top element is not 0.

    ```
    1-$:o}

    1-        Subtract 1.    "ppcg3"
      $       Swap.          "ppc3g"
       :      Duplicate.     "ppc3gg"
        o     Output.        "ppc3g"
         }    Rotate right.  "gppc3"

    ```

    This will print the stack without discarding it. If the loop terminates, we jump to the right on line 5, preparing for the next printing loop.
    * **Preparation of right half**

    ```
    5.  →    /84/
    6.       \
    7.            :
    8.            >
    9.         v:$-1/~
    10.         </r+*
    11.          </~
    12.           l

    ```

    This was one of the hardest parts to fit. Below is a version stripped of all direction wrapping to indicate what happens.

    ```
                 Initial stack:   "    gcpp0"
    84*+r~
    84*          Push 32 == " ".  "    gcpp0 "
       +         Add 32 and 0.    "    gcpp "
        r        Reverse.         " gcpp    "
         ~       Remove top.      " gcpp   "

    ```

    We then push the length of what is to be printed and start the second printing loop (with an initial duplicate not part of the loop).
    * **Second printing loop (right half)**

    ```
    3.     / ^
    4.     \}o<
    5.
    6.           ↓
    7.
    8.       >  :>?\vv
    9.        v:$-1/~

    ```

    The code being executed is completely the same as in the first printing loop, with the `o}` being placed a bit further because there were available locations. Upon finishing, we have a few things left to do before we can verify the main loop invariant again. After the `~` on line 9 is executed we wrap around vertically, ending up at the following piece of code.

    ```
                    ↓
    2.          X     /
    3.  1.v/             >a
    4.              >ao  /

    ```

    First `ao` will print a newline. Then we bounce up and arrive at exactly the same spot from after the initialisation, namely jumping to the `X`.
> 26 votes

# Answer
# Brain-Flak, 486 + 1 = 489 bytes

*Happy Birthday V from Brain-Flak!*

*Also a Thank you to 0 ' who provided some of the code used in this answer*

+1 due to the `-c` flag which is required for ASCII in and out

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

```

Try it online!

This is without a doubt the hardest thing I have ever done in Brain-Flak.

Brain-Flak is notoriously terrible at duplicating and reversing strings and this challenge consists of nothing but duplicating and reversing strings.

I managed to get this almost working snippet in just under an hour of hard work, but adding in the last few spaces turned out to be one of the most difficult things I have ever done in Brain-Flak.

# Explanation

The basic Idea is that we will create the top of the V first and each iteration remove two characters from the middle and add a space to the beginning.

In practice this becomes quite difficult.

Existing algorithms exist for copy and reverse so I used one of those to create a reversed copy of the code on the offstack. Once I've done that I put `2n-1` spaces on top of the original stack and move the offstack back onto the onstack to create a sandwich.

Now we have our top row. Now we want to remove two characters from the beginning and add a space to the front. This turns out to be the most difficult part. The reason for this is that we need to essentially store two values, one for the depth of the current snippet and one for the depth to the center of the V where the deletion has to occur.

This is hard.

Because of all the duplication and reversal that is going on both of the stacks are in full use all of the time. There really is nowhere on these stacks to put anything. Even with all of the Third Stack Magic in the world you can't get the type of access you need to solve this problem.

So how do we fix it? In short we don't really; we ignore the spaces for now and patch them in later we will add zeros to the code to mark where the spaces are intended to go but other than that we won't really do anything.

So on each iteration we make a copy of the last iteration and put it onto the offstack. We use the depth we stored to split this in half so we have the left half of the V on the right stack and the right half of the V on the left stack. We remove two elements and patch the two back together. We add a newline for good measure and start the next iteration. Each time the depth to the center of the V decreases by one and when it hits zero we stop the loop.

Now we have the bulk of the V constructed. We are however lacking proper spaces and our V is currently a bit (read: completely) upside-down.

So we flip it. To flip it onto the other stack we have to move each element over one by one. As we are moving elements we check for zeros. If we encounter one we have to put the spaces back in where they belong. We chuck the zero and add in a bunch of spaces. How do we know how many? We keep track; flipping a stack unlike duplicating or reversing one is a very un-intensive task so we actually have the memory to store and access an additional counter to keep track of how many spaces to add. Each time we add some spaces we decrement the counter by one. The counter should hit zero at the last newline (the top of the V) and thus we are ready to print.

Lastly we clean up a few things hanging around and terminate the program for implicit output.
> 19 votes

# Answer
# Python 3, 65 bytes

```
s=input();s+=' '*len(s)
for _ in s:s=' '+s[print(s+s[-2::-1]):-1]

```

Try it online!

---

# Python 2, 65 bytes

```
s=input();s+=' '*len(s)
for _ in s:print s+s[-2::-1];s=' '+s[:-1]

```

Try it online!
> 18 votes

# Answer
# Jelly, ~~15~~ 12 bytes

```
⁶ṁ⁸;;\Uz⁶ŒBY

```

Try it online!

### How it works

```
⁶ṁ⁸;;\Uz⁶ŒBY  Main link. Argument: s (string)

⁶ṁ            Mold ' ' like s, creating a string of len(s) spaces.
  ⁸;          Prepend s to the spaces.
    ;\        Cumulative concatenation, generating all prefixes.
      U       Upend; reverse each prefix.
       z⁶     Zip/transpose, filling empty spots with spaces.
         ŒB   Bounce; map each string t to t[:-1]+t[::-1].
           Y  Join, separating by linefeeds.

```
> 16 votes

# Answer
## JavaScript (ES6), ~~108~~ ~~106~~ ~~98~~ 94 bytes

```
f=
s=>s.repeat((j=l=s.length*4)*2).replace(/./g,_=>--j?s[j+j<l?j-i:l-i-j]||` `:(j=l,++i,`
`),i=1)
```

```
<input oninput=o.textContent=f(this.value)><pre id=o>
```
> 15 votes

# Answer
## Retina, ~~51~~ 47 bytes

*Happy birthday from a fellow string-processing language!*

Byte count assumes ISO 8859-1 encoding.

```
$
$.`$*
$
¶$`
O$^r`.\G

;{*`.¶

(\S.*).¶.
 $1¶

```

Try it online!

### Explanation

```
$
$.`$*

```

This appends `n` spaces (where `n` is the string length), by matching the end of the string, retrieving the length of the string with `$.``, and repeating a space that many times with `$*`.

```
$
¶$`

```

We duplicate the entire string (separated by a linefeed), by matching the end of the string again and inserting the string itself with `$``.

```
O$^r`.\G

```

This reverses the second line by matching from right-to-left (`r`), then matching one character at a time (`.`) but making sure that they're all adjacent (`\G`). This way, the matches can't get past the linefeed. This is then used in a sort-stage. By using the sort-by mode (`$`) but replacing each match with an empty string, no actual sorting is done. But due to the `^` option, the matches are reversed at the end, reversing the entire second line.

```
;{*`.¶

```

This stage is for output and also affects the rest of the program. `{` wraps the remaining stages in a loop which is repeated until those stages fail to change the string (which will happen because the last stage won't match any more). The `;` disables output at the end of the program. The `*` turns this stage into a dry-run which means that the stage is processed and the result is printed, but afterwards the previous string is restored.

The stage itself simply removes a linefeed and the preceding character. Which gives us one line of the desired output (starting with the first line).

```
(\S.*).¶.
 $1¶

```

Finally, this stage turns each line into the next. This is done by inserting a space in front of the first non-space character, removing the last character on the first line, as well as the first character on the second line. This process stops once there is only one non-space character left on the first line, which corresponds to the last line of the output.
> 11 votes

# Answer
# Japt, ~~22~~ ~~20~~ ~~16~~ 14 + 2 bytes

*Japt wishes V many more successful years of golfing!*

```
²¬£²îU²ç iYU)ê

```

Requires the `-R` flag. Test it online!

### Explanation

This makes use of the `ç` and `î` functions I added a few days ago:

```
²¬£²îU²ç iYU)ê    Implicit: U = input string
²                 Double the input string.
 ¬                Split into chars.
  £               Map each char X and index Y by this function:
     U²             Take the input doubled.
       ç            Fill this with spaces.
         iYU        Insert the input at index Y.
    î       )       Mask: repeat that string until it reaches the length of
   ²                the input doubled.
                    This grabs the first U.length * 2 chars of the string.
             ê      Bounce the result ("abc" -> "abcba").
                  Implicit: output result of last expression, joined by newlines (-R flag)

```

Dennis's technique is a byte longer:

```
U+Uç)å+ mw y mê

```
> 9 votes

# Answer
# 05AB1E, 12 bytes

```
Dgð×J.p€ûR.c

```

Try it online!

**Explanation**

```
D             # duplicate input
 g            # length of copy
  ð×J         # append that many spaces to input
     .p       # get a list of all prefixes
       €û     # turn each into a palindrome
         R    # reverse the list
          .c  # pad each line until centered

```

Or for the same byte count from the other direction.

```
Âsgú.sí€ûR.c

```

**Explanation**

```
Â             # push a reversed copy of input
 s            # swap the input to the top of the stack
  g           # get its length
   ú          # prepend that many spaces
    .s        # get a list of all suffixes
      í       # reverse each
       €û     # turn each into a palindrome
         R    # reverse the list
          .c  # pad each line until centered

```
> 9 votes

# Answer
## GNU sed, ~~110~~ 100 + 1(r flag) = 101 bytes

**Edit:** 9 bytes shorter thanks to Riley

*As another string manipulation language, **sed** wishes **V** the best!*

```
h;G
:;s:\n.: \n:;t
h;:r;s:(.)(\n.*):\2\1:;tr
H;x
s:\n\n ::
:V
h;s:\n::p;g
s:^: :;s:.\n.:\n:
/\n$/!tV

```

**Try it online!**

**Explanation:** assuming the input is the last test case ('V!'). I will show the pattern space at each step for clarity, replacing spaces with 'S's.

```
h;G                       # duplicate input to 2nd line: V!\nV!
:;s:\n.: \n:;t            # shift each char from 2nd line to 1st, as space: V!SS\n
h;:r;s:(.)(\n.*):\2\1:;tr # save pattern space, then loop to reverse it: \nSS!V
H;x                       # append reversed pattern to the one saved V!SS\n\n\nSS!V
s:\n\n ::                 # convert to format, use \n as side delimiter: V!SS\nS!V
:V                        # start loop 'V', that generates the remaining output
h;s:\n::p;g               # temporarily remove the side delimiter and print pattern
s:^: :;s:.\n.:\n:         # prepend space, delete char around both sides: SV!S\n!V
/\n$/!tV                  # repeat, till no char is left on the right side
                          # implicit printing of pattern left (last output line)

```
> 5 votes

# Answer
# Python, 110 bytes

Try it online!

I'm sure this isn't optimal, but it's pretty Pythonic at least:

```
def f(s):n=len(s)*2-1;return''.join(i*' '+s[:n+1-i]+(n-2*i)*' '+s[n-i-1::-1]+'\n'for i in range(n))+n*' '+s[0]

```
> 4 votes

# Answer
## Batch, ~~186~~ 185 bytes

```
@set e=@set
%e%/ps=
%e%t=%s%
%e%r=
:l
%e%s=%s%
%e%r= %r%%t:~-1%
%e%t=%t:~,-1%
@if not "%t%"=="" goto l
:g
%e%r=%r:~1%
@echo %s%%r%
%e%s= %s:~,-1%
@if not "%r%"=="" goto g

```

Lines 1 and 6 have a trailing space. Edit: Saved 1 byte thanks to @ConorO'Brien.
> 4 votes

# Answer
# Jolf, 31 bytes

*Jolf begrudgingly wishes V a happy birthday!*

```
RΜwzΒώlid+γ_pq_ l+*␅Hi0ΒΒ␅ L_γ1S

```

Try it here!  should be 0x05.

## Explanation

```
RΜzΒώlid+γ_pq_ l+*␅Hi0ΒΒ␅ L_γ1S  i = input
     li                                  i.length
    ώ                                2 *
   Β                             Β =
  z                              range(1, Β + 1)
 Μ     d                         map with: (S = index, from 0)
                +                 add:
                 *␅H               S spaces
                    i              and the input
               l                  slice (^) from
                     0Β            0 to Β
           pq_         Β␅         pad (^) with spaces to the right
         γ_                       γ = reverse (^)
        +                 L_γ1    γ + behead(γ)
R                             S  join with newlines

```
> 4 votes

# Answer
# Charcoal, 29 bytes

*Happy birthday V, from your fellow disappointingly-long-for-this-challenge ASCII-art language!*

```
ＳσＦ…·¹Ｌσ«Ｆι§σκＭι←↖»Ｆσ«Ｐσ↖»‖Ｏ→

```

Try it online!

### Explanation

Our strategy: print the left half of the V, starting from the bottom and moving to the upper left; then reflect it.

```
Ｓσ                                    Input σ as string
                                       The bottom len(σ) half-rows:
   Ｆ…·¹Ｌσ«           »               For ι in inclusive range from 1 to length(σ):
            Ｆι                          For κ in range(ι):
               §σκ                         Print character of σ at index κ
                  Ｍι←                   Move cursor ι spaces leftward
                      ↖                  Move cursor one space up and left
                                       The top len(σ) half-rows:
                        Ｆσ«    »      For each character ι in σ:
                            Ｐσ          Print σ without moving the cursor
                               ↖         Move cursor one space up and left
                                 ‖Ｏ→  Reflect the whole thing rightward, with overlap

```

(If only Charcoal had string slicing... alas, it appears that hasn't been implemented yet.)
> 4 votes

# Answer
# Pip, ~~32~~ 25 bytes

```
a.:sX#aL#a{OaDQaPRVaaPUs}

```

Takes the input string as a command-line argument. Try it online!

### Explanation

```
                           a is 1st cmdline arg, s is space (implicit)
     #a                    Len(a)
   sX                      Space, string-multiplied by the above
a.:                        Concatenate that to the end of a
       L#a{             }  Loop len(a) times (but NB, a is now twice as long as it was):
           Oa                Output a (no trailing newline)
             DQa             Dequeue one character from the end of a
                PRVa         Print reverse(a) (with trailing newline)
                    aPUs     Push one space to the front of a

```
> 4 votes

# Answer
# R with stringi package, 225 Bytes

```
library(stringi)
f=function(){
s=scan(,'',1,sep="\n")
m=2*nchar(s)
l=stri_pad(sapply(1:m-1,function(x)substr(paste(paste(rep(" ",x),collapse=""),s),1,m)),m,"right")
r=substr(stri_reverse(l),2,m)
message(paste0(l,r,"\n"))}
f()

```

If you run R in interactive code, after pasting my answer just input anything. You will need the stringi R package to be installed (I hope it's not against the rules).

# Explanation:

The basic idea is to add spaces to the left side, then cut it to the right length. After that, paste it with its reversed version as the right side. Here is a longer, human-readable version of the function:

```
library(stringi)
make_V <- function(){                  # declaring the function
  string <- scan(, '', n=1, sep="\n")  # reading input
  max_length <- 2*nchar(string)        # number of chars in each half row

  # creating the left side of the V

  left <- stri_pad(
            sapply(1:max_length-1,     # for each row
                   function(x){
                    substr(
                      paste0(
                        paste0(rep(" ", x),
                               collapse=""), string), # add spaces to left side
                           1,
                           max_length) # cut the unneeded end
                    }),
            width=max_length,
            side="right")              # add spaces to the right side

  # creating the right side of the V

  right <- substr(stri_reverse(left), 2, max_length)

  # print it without any symbols before the strings
  message(paste0(left, right, "\n"))
}

# run the function
make_V()

```
> 4 votes

# Answer
# Ruby, ~~92~~ ~~89~~ 85 bytes

```
s=gets.chomp
s<<" "*n=s.size*2
n.times{s=s[0..(n-1)]
puts s+s.reverse[1..-1]
s=" "+s}

```

My process was to remove the first character from the right half of each line after reversing the first half. Like this:

```
Hello     |    olleH
 Hello    |   olleH
  Hello   |  olleH
   Hello  | olleH
    Hello |olleH
     Hello|lleH
      Hell|leH
       Hel|eH
        He|H
         H|

```

I'm not used to trying to golf things so let me know if there's anything I can do to get it shorter.
> 4 votes

# Answer
# Haskell, 76 bytes

`v` is the main function, taking a `String` argument and giving a `String` result.

```
v i=unlines.r$i++(' '<$i)
r""=[]
r s|t<-init s=(s++reverse t):map(' ':)(r t)

```

Try it online!

# Notes:

* `i` is the initial argument/input.
* `s` is initially `i` with `length i` spaces appended.
* `v i` calls `r s`, then joins the result lines.
* `r` returns a list of `String` lines.
* `t` is `s` with the last character chopped off.
* The recursion `r t` produces the lines except the first, minus the initial space on each line.
> 3 votes

# Answer
# Jelly, 13 bytes

```
⁶ṁ;@µḣJUz⁶ŒBY

```

**Try it online!**

### How?

```
⁶ṁ;@µḣJUz⁶ŒBY - Main link: string s
⁶             - space character
 ṁ            - mould like s: len(s) spaces
  ;@          - concatenate s with that
    µ         - monadic chain separation (call that t)
      J       - range(length(t))
     ḣ        - head (vectorises): list of prefixes from length to all
       U      - upend: reverse each of them
        z     - transpose with filler:
         ⁶    -     space: now a list of the left parts plus centre
          ŒB  - bounce each: reflect each one with only one copy of the rightmost character
            Y - join with line feeds
              - implicit print

```
> 3 votes

# Answer
# PHP, ~~95~~ ~~92~~ ~~85~~ ~~80~~ ~~78~~ 77 bytes

Note: uses IBM-850 encoding

```
for($s.=strtr($s^$s=$argn,~ ,~▀);~$s[$i++];)echo$s,strrev($s=" $s"^$s^$s),~§;
          # Note that this ^ char is decimal 255 (negating it yields "\0")

```

Run like this:

```
echo "Hello" | php -nR 'for($s.=strtr($s^$s=$argn,"\0",~▀);~$s[$i++];)echo$s,strrev($s=" $s"^$s^$s),~§;'
> Hello         olleH
>  Hello       olleH
>   Hello     olleH
>    Hello   olleH
>     Hello olleH
>      HellolleH
>       HellleH
>        HeleH
>         HeH
>          H

```

# Explanation

```
for(
  $s.=strtr(             # Set string to the input, padded with spaces.
    $s^$s=$argn,         # Input negated with itself, leads to string with
                         # only null bytes with the same length.
    ~ ,                  # Replace null bytes...
    ~▀                   # ... with spaces.
  );
  ~$s[$i++];             # Iterate over the string by chars, works because
                         # there are just as many lines as the padded
                         # string has chars.
)
  echo                   # Output!
    $s,                  # The string.
    strrev(              # The reverse of the string.
      $s=" $s"^$s^$s     # After each iteration, prefix string with a
    ),                   # space, and trim the last character.
    ~§;                  # Newline.

```

# Tweaks

* Saved 3 bytes by getting rid of the pad character (`str_pad` defaults to space, which is what we need)
* Saved 7 bytes by using binary operations on the string to truncate it instead of `substr`
* Saved 5 bytes by rotating the string when printing the reverse. Prevents the need for printing a backspace, but results in a trailing space on each line.
* Saved 2 bytes by padding string using a more convoluted, but shorter method.
* Saved a byte due to the fact that there is no need to account for the `~"0"` case (ASCII 207), as all input may be assumed to be printable ascii (Thx @Titus)
> 3 votes

# Answer
# Ruby, ~~85~~ 83 bytes

*edit: removed excess whitespace*

```
s=ARGV[0];s+=' '*s.length;s.length.times{|i|puts s+s[i..-2].reverse;s=' '+s[0..-2]}

```

I actually found it pretty difficult to golf this one down in Ruby. After adding whitespace, it expands to a pretty readable snippet of code:

```
s = ARGV[0]
s+=' ' * s.length

s.length.times do |i|
  puts s + s[i..-2].reverse
  s = ' ' + s[0..-2]
end

```
> 3 votes

# Answer
# MATLAB (R2016b), 223 183 bytes

```
r=input('');l=nnz(r)*2;for i=1:l;m=l+1-2*i;c={' '};s=cell(1,i-1);s(:)=c;x=cell(1,m);x(:)=c;e=r;y=flip(r);if(m<1);e=r(1:2*end-i+1);y=r(l/2+end-i:-1:1);end;disp(cell2mat([s e x y]));end

```

First time Code Golfing. Tips are welcome!

**Program Output:**

**Edit:**

Saved 40 bytes thanks to Luis Mendo.
> 3 votes

# Answer
# Vyxal, 21 bytes

```
Ld(n⁰n⁰Ldεwi꘍⁰Ln-꘍øm,

```

Try it Online!

This was interesting. Here's a bugged version.

```
Ld(                   # Length * 2 times do...
   n                  # Iteration number...
            ꘍         # Spaces, plus...
    ⁰                 # Input string...
          wi          # Sliced to first...
         ε            # Absolute difference of...
     n                # Iteration number...
         ε            # And...
        d             # Double...
      ⁰L              # The original string's length...
                ꘍     # Plus...
               -      # Difference of...
            ⁰L        # Original string's length
               -      # And...
              n       # Iteration number
                ꘍     # Spaces.
                 øm   # Palindromised
                   ,  # And outputted.

```
> 3 votes

# Answer
# Vyxal `C`, 5 bytes

```
L꘍¦Ṙʁ

```

Try it Online!

Less than half the bytecount of Jelly and 05AB1E, and less than a fourth of the bytecount of emanresu's Vyxal! *evil laugh*

```
L꘍¦Ṙʁ
 ꘍    # Append as many spaces to the input as...
L     # Its length
  ¦   # Get all prefixes of this
   Ṙ  # Reverse this
    ʁ # Palindromize each (for each x, x + x[::-1][1:])
      # C flag centers and joins on newlines

```

Think I'm cheating with flags?

# Vyxal, 6 bytes

```
L꘍¦Ṙøṗ

```

Try it Online!

```
L꘍¦Ṙøṗ
 ꘍     # Append as many spaces to the input as...
L      # Its length
  ¦    # Get all prefixes of this
   Ṙ   # Reverse this
    øṗ # Palindromize each (for each x, x + x[::-1][1:]), center, and join on newlines

```
> 3 votes

# Answer
## PowerShell, ~~126 bytes~~ 124 bytes

```
$l=($s="$args")|% Le*;$r=-join$s[-1..-$l];0..($l*2-1)|%{' '*$_+($s+' '*$l).substring(0,$l*2-$_)+(' '*$l+$r).substring($_+1)}

```

Call it with a single parameter, such as `.\V.ps1 Hello`.

Edit: 2 bytes saved with tip from AdmBorkBork
> 2 votes

# Answer
# JavaScript (ES6), ~~169~~ 157 bytes

*(-10 bytes thanks to Conor O'Brien)*

```
V=(j,i=0,p="")=>i<(f=j.length)*2?V(j,-~i,p+" ".repeat(i)+j.slice(0,f-i*(i>f))+" ".repeat(i<f?(f-i)*2-1:0)+[...j.slice(0,f+~i*(i>=f))].reverse().join``+`
`):p

```

A recursive solution. I am new to JavaScript, so please be gentle! Any golfing tips are greatly appreciated. :)

And, of course, a very happy birthday to you `V`!

## Test Snippet

```
V=(j,i=0,p="")=>i<(f=j.length)*2?V(j,-~i,p+" ".repeat(i)+j.slice(0,f-i*(i>f))+" ".repeat(i<f?(f-i)*2-1:0)+[...j.slice(0,f+~i*(i>=f))].reverse().join``+`
`):p
```

```
<input oninput=o.textContent=V(this.value)><pre id=o>
```
> 2 votes

# Answer
# PowerShell, ~~88~~ ~~86~~ ~~80~~ 76 bytes

```
param($n)0..($l=$n.length*2-1)|%{-join((" "*$_+$n+" "*$l)[0..$l+($l-1)..0])}

```

Try it online!

*Happy Birthday, V!*

This takes the input `$n`, then we loop from `0` up to `2 * $length - 1`. Each iteration, we slice into (pre-pended spaces + `$n` \+ appended spaces) from `0` up to the last character, and then back down to `0`. That's `-join`ed together into a string and left on the pipeline.

All those strings are gathered from the pipeline, and an implicit `Write-Output` happens at program completion with a newline in between elements.

*Golfed 6 bytes by eliminating `$b`. Golfed another four by redoing `$n` calculations.*
> 2 votes

# Answer
# CJam, 26 bytes

*Happy birthday from your old pal CJam!*

```
q_,2*:L,\f{LS*+m>L<_W%(;N}

```

Try it online!

**Explanation**

```
q                           Push the input
 _,2*:L                     Push 2 times the length of the input, store it in L
       ,                    Take the range from 0 to L-1
        \                   Swap top stack elements
         f{                 Map over the range, using the input as an extra parameter
           LS*+               Append L spaces to the input
               m>             Rotate the resulting string right i positions (where i is the
                               current number being mapped)
                 L<           Take the first L characters of the string
                   _W%        Duplicate it and reverse it
                      (;      Remove the first character from the copy
                        N     Add a newline
                         }  (end of block)
                            (implicit output)

```
> 2 votes

# Answer
# Pyke, 14 bytes

```
l}j Fd*R+j^j<s

```

Try it online!
> 2 votes

# Answer
## JavaScript (ES6), 94 bytes

```
f=(s,y=0,x=0,l=s.length*2-1)=>(s[(x>l?l*2-x:x)-y]||' ')+(x<l*2?f(s,y,x+1):y<l?`
`+f(s,y+1):'')

```

### Test cases

```
f=(s,y=0,x=0,l=s.length*2-1)=>(s[(x>l?l*2-x:x)-y]||' ')+(x<l*2?f(s,y,x+1):y<l?`
`+f(s,y+1):'')

console.log(f('Happy'))
console.log(f('Birthday'))
console.log(f('V!'))
console.log(f('~'))
```
> 2 votes

# Answer
# J, 44 Bytes

```
(([(,}.@|.)@{."1-@i.@[|."0 1(,#&' ')~)~+:@#)

```
> 2 votes

# Answer
# Perl 5, 58 + 1 (`-n`) = 59 bytes

```
$_.=$"x(($l=2*y///c)+3).reverse;say while s/(.{$l})../ $1/

```

Try it online!
> 2 votes

# Answer
## Mathematica (101 bytes)

*Happy birthday to V from Mathematica!*

Anonymous function, takes input as a string.

```
""<>NestList[" "<>StringDrop[#,{n,n+1}]&,#<>{" "~Table~{n=2StringLength@#-1},StringReverse@#,"
"},n]&

```

The newline is meant to be there.

Explanation: First, we generate the top line by joining the input, 2m-1 spaces (where m is the length of the input), the input reversed, and a newline. Then, each line is the previous one without the (2m-1)th and (2m)th characters, with a space added to the start.
> 1 votes

# Answer
# Perl, 71 + 5 (`-nlaF` flag) = 76 bytes

Based on Dom Hastings solution.

```
push@F,($")x@F;print$"x$_,@F[0..$#F-$_],reverse@F[0..@F-$_-2]for 0..$#F

```

Try it online.

# Perl, 81 + 5 (`-nlaF` flag) = 86 bytes

Previous version.

```
@F=(@s=(' ')x($l=@F*2),@F,@s);say@h=@F[-$_..$l-$_-1],reverse@h[0..@h-2]for-$l..-1

```

Try it online.
> 1 votes

# Answer
# Pyth, 22 bytes

```
+Rt_dm<+*;d+Q*lQ;ylQyl

     m              yl for d from 0 to double of length of input (exclusive)
                ;          space character
             *lQ           repeat as many times as length of input
           +Q              prepend input
       +*;d                prepend space repeated as many times as d
      <          ylQ       extract first (input length doubled) characters
 R                     for each string d obtained above
+                          append
  t_d                      tail of reverse of d (tail means d[1:])

```

Try it online! (a `j` is prepended to the code to make the output more beautiful)
> 1 votes

# Answer
# SmileBASIC, ~~131~~ ~~127~~ ~~125~~ ~~109~~ ~~105~~ ~~91~~ ~~85~~ 84 bytes

Possibly some room for improvement here...

```
LINPUT S$K=LEN(S$)*2FOR J=1TO K
FOR I=1-K TO K?(" "*J+S$+" "*K)[K-ABS(I)];
NEXT?NEXT

```

Explanation:

(Input=`V!`)

The program uses `k-ABS(x-k)-y` (where `k=length*2-1`) to convert a position to a number:

```
 0 1 2 3 2 1 0
-1 0 1 2 1 0-1
-2-1 0 1 0-1-2
-3-2-1 0-1-2-3

```

To get rid of negative numbers, `k` is added:

```
3 4 5 6 5 4 3
2 3 4 5 4 3 2
1 2 3 4 3 2 1
0 1 2 3 2 1 0

```

Now we can just uses these as indexes into the input string, padded with `k` spaces on each end (`...V!...`).

```
V ! . . . ! V
. V ! . ! V .
. . V ! V . .
. . . V . . .

```
> 1 votes

# Answer
# Ruby, 70 bytes

I wasn't sure I could beat the other Ruby submissions, but I managed to do it. Those last three lines are killing me, though.

```
->s{z=s.size*2-1
s+=" "*z+s.reverse
z.times{s[z,2]=""
puts s
s=" "+s}}

```

Try it online!
> 1 votes

# Answer
# Julia, ~~88~~ 86 bytes

```
w=" ";a%b=b<w?a:a*b*(w*chop(a)%b[2:end]);!r=r[1:(n=end)]*w^n%(w^(n-1)*reverse(r)*"\n")

```

Explained:

```
#Assign space char to w.
w=" ";

#Redefine modulo operator so it is a V generator:
#In the base case (when b is lexographically before a space, which
#occurs when b consists of a newline), print a.
#In the recursive case, concatenate a, b and the result to a recursive
#call with arguments consisting of a shifted right, and b shifted
#left.
a%b=b<w?a:a*b*(w*chop(a)%b[2:end]);

#Frontend function for the V-generator, which automatically feeds the
#V-generator with the correct arguments.
!r=r[1:(n=end)]*w^n%(w^(n-1)*reverse(r)*"\n")

```
> 1 votes

# Answer
# Canvas, 8 bytes

```
ｌ«＊＼ｌｍ││

```

Try it here!

Explanation:

```
l         push length of input
 «        multiply by 2
  *       push an array of the input repeated that many times
   \      pad with a space triangle
    l     push the height of that
     m    and mold the width to that, discarding anything after
      ││  palindromize horizontally

```
> 1 votes

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

*-1 byte thanks to steffan.*

```
ðs∍«η€ûR.C

```

Try it online!

```
ðs∍«η€ûR.C  # full program
        .C  # push centered lines of...
       R    # reversed list of...
     €û     # palindromized...
    η       # prefixes of...
  ∍         # length of...
 s          # implicit input...
ð           # spaces...
   «        # concatenated to...
            # implicit input
            # implicit output

```
> 1 votes

# Answer
# Charcoal, 23 bytes

```
Ａ×²ＬθαＦθ«Ｐ↘…ια→Ａ⁻α¹α»‖Ｂ

```

Try it online!

This just draws lines downrightwards with the characters of the input and then reflect the canvas horizontally (skipping the central line). Verbose version here.

# Charcoal, 26 bytes

```
Ａ×²ＬθαＦθ«ＧＨ>αιＭ⁻×²α³→Ａ⁻α¹α

```

Try it online!

This answer just draws consecutively smaller "V"-shaped polygons using the characters in the input. Verbose version here.
> 0 votes

# Answer
# Stax, 10 bytes

```
ßë♠♂æÄ|Åò▓

```

Run and debug it
> 0 votes

# Answer
# Excel, 125 bytes

```
=LET(n,LEN(A1),y,SEQUENCE(1,4*n),z,2*n-ABS(2*n-y)+1-SEQUENCE(2*n),m,IF((z>0)*(z<=n),MID(A1,z,1)," "),CONCAT(IF(y=4*n,"
",m)))

```

Try it online
> 0 votes

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


title: Construct the natural numbers with sets

text:
# Question
Title: Construct the natural numbers with sets
This construction is a way of representing the Natural Numbers.

In this representation, 0 is defined as the empty set and for all other numbers, n is the union of {0} and {n-1}.

For example to construct 3 we can follow the algorithm:

```
3 =
{ø, 2} =
{ø, {ø, 1}} =
{ø, {ø, {ø}}}

```

# Task

As you may have guessed your task is to take in a natural number (including zero) and output its construction.

You may output as a either a string or as a set object if your language of choice supports such objects.

If you choose to output as a string you should represent a set with curly braces (`{}`). You may optionally represent the empty set as `ø` (otherwise it should be a set with no entries `{}`). You may also choose to add commas and whitespace between and after entries in the set.

Order is not important, however you may ***not*** have any repeated elements in the sets you output (e.g. `{ø,ø}`)

This is so the goal is to have the fewest bytes

# Test cases

Here are some test cases with some example outputs.

```
0 -> {}
1 -> {{}}
2 -> {{}{{}}}
3 -> {{}{{}{{}}}}
4 -> {{}{{}{{}{{}}}}}

```

# Answer
> 13 votes
# Python, 28 bytes

```
lambda x:"{{}"*x+x*"}"or"{}"

```

Try it online!

This is a pretty bland solution to the problem. For numbers greater than zero you can get the representation with the string formula `"{{}"*x+"}"*x`. However this doesn't work for zero where this is the empty string. We can use this fact to short circuit an `or` to return the empty set.

I wanted to use python's builtin set objects to solve this problem but unfortunately:

```
TypeError: unhashable type: 'set'

```

You cannot put sets inside of sets in python.

# Answer
> 9 votes
# Haskell, 37 bytes

```
f 0="{}"
f n=([1..n]>>)=<<["{{}","}"]

```

Try it online!

Until 10 minutes ago an answer like this would have made no sense to me. All credits go to this tips answer.

Basically, we use `>>` as `concat $ replicate` (but passing it a list of n elements instead of simply n), and `=<<` as `concatMap`, replicating then n times each of the strings in the list and concatenating the result into a single string.

The `0` case is treated separately as it would return an empty string.

# Answer
> 6 votes
## JavaScript, 28 bytes

```
f=n=>n?--n?[[],f(n)]:[[]]:[]

```

Represents sets using arrays. 38-byte nonrecursive solution:

```
n=>'{{}'.repeat(n)+'}'.repeat(n)||'{}'

```

Returns the example output strings.

# Answer
> 6 votes
## Mathematica, 27 bytes

I've got two solutions at this byte count:

```
Nest[{{}}~Union~{#}&,{},#]&
Union//@Nest[{{},#}&,{},#]&

```

# Answer
> 5 votes
# Perl 6, 37 bytes

```
{('{}','{{}}',{q:s'{{}$_}'}...*)[$_]}

```

Try it

## Expanded:

```
{   # bare block lambda with implicit parameter ｢$_｣

  (
    # generate a sequence

    '{}',   # seed it with the first two values
    '{{}}',

    {   # bare block lambda with implicit parameter ｢$_｣

      q         # quote
      :scalar   # allow scalar values

      '{{}$_}'  # embed the previous value ｢$_｣ in a new string

    }

    ...         # keep using that code block to generate values

    *           # never stop

  )[ $_ ] # get the value at the given position in the sequence
}

```

# Answer
> 5 votes
# Röda, 37 bytes

```
f n{[[[],f(n-1)]]if[n>1]else[[[]]*n]}

```

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

### Code

```
ƒ)¯sÙ

```

Uses the **CP-1252** encoding. Try it online! or Verify all test cases!.

### Explanation

```
ƒ       # For N in range(0, input + 1)..
 )      #   Wrap the entire stack into an array
  ¯     #   Push []
   s    #   Swap the two top elements
    Ù   #   Uniquify the array

```

# Answer
> 4 votes
## Retina, 22 bytes

```
.+
$*
\`.
{{}
{

^$
{}

```

Try it online!

### Explanation

```
.+
$*

```

Convert the input to unary.

```
\`.
{{}

```

Replace each unary digit with `{{}` and print the result without a trailing linefeed (`\`).

```
{

```

Remove the opening `{`s, so that the remaining `}` are exactly those we still need to print to close all the sets. However, the above procedure fails for input `0`, where we wouldn't print anything. So...

```
^$
{}

```

If the string is empty, replace it with the empty set.

# Answer
> 4 votes
# Brain-Flak, 135 bytes

Includes +1 for `-A`

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

```

Try it online!

```
(({}())<                 # Replace Input with input + 1 and save for later
  {({}[()]<              # For input .. 0
    (...)                # Push '}'
  >)}{}                  # End for and pop counter
  ({}[()()])             # change the top '}' to '{'. This helps the next stage
                         # and removes the extra '}' that we got from incrementing input
>)                       # Put the input back on

(({})<                   # Save input
  {({}[()]<              # For input .. 0
    (((({}()())[()()]))) # Replace the top '{' with "{{{}"
  >)}{}                  # end for and pop the counter
>[()])                   # Put down input - 1
{(<{}{}{}>)}             # If not 0, remove the extra "{{}"
{}{}{}                   # remove some more extras

```

# Answer
> 4 votes
# CJam, 11 bytes

```
Lri{]La|}*p

```

Prints a set-like object consisting of lists of lists. CJam prints empty lists as empty strings, since lists and strings are almost interchangeable.

Try it online!

**Explanation**

```
L            Push an empty array
 ri          Read an integer from input
   {    }*   Run this block that many times:
    ]          Wrap the entire stack in an array
     La        Wrap an empty list in an array, i.e. [[]]
       |       Set union of the two arrays
          p  Print the result

```

# Old answer, ~~21~~ 18 bytes

This was before it was confirmed that it was OK to print a nested list structure. Uses the string repetition algorithm.

*Saved 3 bytes thanks to Martin Ender!*

```
ri{{}}`3/f*~_{{}}|

```

**Explanation**

```
ri                  Read an integer from input
  {{}}`             Push the string "{{}}"
       3/           Split it into length-3 subtrings, gives ["{{}" "}"]
         f*         Repeat each element of that array a number of times equal to the input
           ~_       Dump the array on the stack, duplicate the second element
             {{}}|  Pop the top element, if it's false, push an empty block, which gets
                      printed as "{}". An input of 0 gives two empty strings on the
                      repetition step. Since empty strings are falsy, we can correct the
                      special case of 0 with this step.

```

# Answer
> 4 votes
# Jelly, 6 bytes

```
⁸,⁸Q$¡

```

This is a niladic link that reads an integer from STDIN and returns a ragged array.

Try it online!

### How it works

```
⁸,⁸Q$¡  Niladic link.

⁸       Set the return value to [].
    $   Combine the three links to the left into a monadic chain.
 ,⁸     Pair the previous return value with the empty array.
   Q    Unique; deduplicate the result.
     ¡  Read an integer n from STDIN and call the chain to the left n times.

```

# Answer
> 3 votes
# Cardinal, ~~51~~ 50 bytes

```
%:#>"{"#? v
x  ^?-"}{"<
v <8/ ?<
>  8\
v"}"<
>?-?^

```

Try it online!

## Explanation

```
%:#
x

```

Receive input and send down and left from the #

```
   >"{" ? v
   ^?-"}{"<

```

Print "{" one time then print "{}{" n-1 times if n\>1 then print "{}" if n\>0

```
       #

v <8/ ?<
>  8\

```

Hold onto the input value until the first loop completes

```
v"}"<
>?-?^

```

Print "}" once then repeat n-1 times if n\>1

# Answer
> 3 votes
# Python 3, 32 bytes

```
f=lambda n:[[],n and f(n-1)][:n]

```

Not the shortest way, but I just *had to* do this with recursion.

Try it online!

# Answer
> 2 votes
# AHK, 55 bytes

```
IfEqual,1,0
s={{}{}}
Loop,%1%
s={{ 2}{}}%s%{}}
Send,%s%

```

It's not the shortest answer but I enjoyed this because the idiosyncrasies of AutoHotkey make this recursion method look *super* wrong. `If` and `Loop` statements assume the next line is the only thing included if brackets aren't used. Curly brackets are escape characters so you have to escape them with other curly brackets to use them as text. Also, the variable `1` is the first passed argument. When I read the code without knowing those tidbits, the logic *looks* like this:

* If 1=0, then set `s` equal to the wrong answer
* Loop and add a bunch of brackets to the beginning and a few to the end every time
* Return by sending the resulting string to the current window

Without all the bracket escape characters, it would look like this:

```
IfEqual,1,0
   s={}
Loop,%1%
   s={{}%s%}
Send,%s%

```

# Answer
> 1 votes
# JavaScript 50 bytes

```
g=n=>n==0?"":"{{}"+g(n-1)+"}"
z=m=>m==0?"{}":g(m)

```

# Answer
> 1 votes
# Pure Bash, ~~49~~ ~~48~~ 41 bytes

```
for((;k++<$1;)){ s={{}$s};};echo ${s-{\}}

```

Try it online!

# Answer
> 1 votes
# tinylisp, 52 bytes

```
(d f(q((n)(i n(i(e n 1)(c()())(c()(c(f(s n 1))())))(

```

Try it online! (test harness).

### Explanation

Note that `(cons x (cons y nil))` is how you build a list containing `x` and `y` in Lisp.

```
(d f           Define f to be
 (q(           a quoted list of two items (which acts as a function):
  (n)           Arglist is a single argument n
  (i n          Function body: if n is truthy (i.e. nonzero)
   (i(e n 1)     then if n equals 1
    (c()())       then cons nil to nil, resulting in (())
    (c            else (if n > 1) cons
     ()            nil to
     (c            cons
      (f(s n 1))    (recursive call with n-1) to
      ())))         nil
   ()))))        else (if n is 0) nil

```

# Answer
> 1 votes
# C (gcc), 52 bytes

```
n(i){putchar(123);i>1&&n(0);i&&n(i-1);putchar(125);}

```

Taking advantage of some short circuit evaluation and recursion.

Try it online!

# Answer
> 1 votes
# dc, 46 bytes

```
[[{}]]sx256?^dd3^8d^1-/8092541**r255/BF*+d0=xP

```

Try it online!

Input on stdin, output on stdout.

This works by computing a formula for the desired output as a base-256 number. The P command in dc is then used to print the base-256 number as a string.

---

Further explanation:

Let n be the input n. The dc program computes the sum of

A = floor(256^n / 255) * 125 (BF is interpreted by dc as 11\*10+15 = 125)

and

B = floor((256^n)^3 / (8^8-1)) * 8092541 * (256^n).

For A:

Observe that 1 + 256 + 256^2 + ... + 256^(n-1) equals (256^n-1)/255, by the formula for a geometric progression, and this equals floor(256^n / 255). So this is the number consisting of n 1's in base 256.

When you multiply it by 125 to get A, the result is the number consisting of n 125's in base 256 (125 is a single digit in base 256, of course). It's probably better to write the digits in base 256 as hex numbers; 125 is hex 7D, so A is the base-256 number consisting of n 7D's in a row.

B is similar:

This time observe that 1 + 16777216 + 16777216^2 + ... + 16777216^(n-1) equals (16777216^n - 1)/16777215, and this equals floor(16777216^n/16777215).

Now, 256^3 = 16777216, and 8^8-1 = 16777215, so this is what we're computing as floor((256^n)^3 / (8^8-1)).

From the geometric series representation, this number in base 256 is 100100100...1001 with n of the digits being 1 and the rest of the digits being 0.

This is multiplied by 8092541, which is 7B7B7D in hexadecimal. In base 256, this is a three-digit number consisting of the digits 7B, 7B, and 7D (writing those digits in hex for convenience).

It follows that the product written in base 256 is a 3n-digit number consisting of the 3 digits 7B 7B 7D repeated n times.

This is multiplied by 256^n, resulting in a 4n-digit base-256 number, consisting of the 3 digits 7B 7B 7D repeated n times, followed by n 0's. That's B.

Adding A + B now yields the 4n-digit base-256 number consisting of the 3 digits 7B 7B 7D repeated n times, followed by n 7D's. Since 7B and 7D are the ASCII codes for `{` and `}`, respectively, this is the string consisting of n copies of `{{}` followed by n copies of `}`, which is exactly what we want for n \> 0. The P command in dc prints a base-256 number as a string, just as we need.

Unfortunately, n=0 has to be treated as a special case. The computation above happens to yield a result of 0 for n=0; in that case, I've just hard-coded the printing of the string `{}`.

# Answer
> 0 votes
# Java 7, 61 bytes

```
String p(int p){return p<1?"{}":p<2?"{{}}":"{{}"+p(p-1)+"}";}

```

Try it online!

# Answer
> 0 votes
## Batch, 88 bytes

```
@set s={}
@if %1 gtr 0 set s=&for /l %%i in (1,1,%1)do @call set s={{}%%s%%}
@echo %s%

```

# Answer
> 0 votes
# Brainf\***, 99 bytes

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

```

(newline for aesthetics) Since it's brainf\***, it takes input as ascii char codes (input "a" corresponds to 96)

# Braineasy, 60 bytes

Also, in my custom language (brainf\** based, interpreter here):

```
#123#[->+>+<<]>++<,[[-<+<+>>]<[->>>..<.<<]<[->>>.<<<]!]>>.<.

```

You have to hardcode the program input into the interpreter because i'm lazy.

# Answer
> 0 votes
# 05AB1E, ~~5~~ 3 bytes

```
F¯)

```

Try it online!

This version is after he clarified that sets are okay.

```
F   # From 1 to input...
 ¯  # Push global array (default value is []).
  ) # Wrap stack to array.

```

---

Old version (that makes use of ø):

# 05AB1E, ~~5~~ 4 bytes

```
FX¸)

```

Try it online!

Where `1` is equivalent to `ø`.

```
F    # From 1 to input...
 X   # Push value in register X (default is 1).
  ¸  # Wrap pushed value into an array.
   ) # Wrap whole stack into an array.
     # Implicit loop end (-1 byte).
     # Implicit return.

```

# Answer
> 0 votes
# dc, 33 bytes

```
[[{}]n1-d0<m]sr[[{]nd0<r[}]n]dsmx

```

Try it online!

Not as clever as the other dc answer, but rather shorter

---
Tags: code-golf, math, number, set-theory
---


# Question
Title: smallest number of steps for a knight in chess
If you place a knight on any square of a chessboard, what is the smallest amount of steps to reach every position?

**Rules**

* It is an 8 by 8 board.
* The knight starts at an arbitrary position, taken as input.
* The knight moves 2 squares in one direction and 1 square in the other, for example, a knight on the square marked N can move to any of the squares marked X:

```
. X . X .
X . . . X
. . N . .
X . . . X
. X . X .

```

**Example**
With input `1, 0`, we start by putting a 0 in that position:

```
. 0

```

We then put a 1 in the positions that are a knight's move away from that 0, i.e. they are 2 squares away in one direction and 1 square away in the other. We don't fill in the 0:

```
. 0 . .
. . . 1
1 . 1 .

```

Then, we fill in all the empty cells that are exactly two knight's moves away with 2s:

```
. 0 . 2 . 2
2 . 2 1 2 .
1 2 1 . . 2
2 . 2 . 2 .
. 2 . 2 . .

```

Then, the 3s:

```
3 0 3 2 3 2 3 .
2 3 2 1 2 3 . 3
1 2 1 . 3 2 3 .
2 3 2 3 2 3 . 3
3 2 3 2 3 . 3 .
. 3 . 3 . 3 . .
3 . 3 . 3 . . .

```

And we continue until we've filled the entire 8x8 board:

```
3 0 3 2 3 2 3 4
2 3 2 1 2 3 4 3
1 2 1 4 3 2 3 4
2 3 2 3 2 3 4 3
3 2 3 2 3 4 3 4
4 3 4 3 4 3 4 5
3 4 3 4 3 4 5 4
4 5 4 5 4 5 4 5

```

**Challenge** The pattern printed for a knight, as short as possible, in any reasonable format.

# Answer
> 3 votes
# Jelly,  ~~24 23~~  22 bytes

```
W8p¤ạṢ€ċØ½ʋƇ$ƬŒṬĖP€o/’

```

A monadic Link that accepts a pair of integers and yields a list of lists of integers.

**Try it online!** (The footer pretty prints the grid)

### How?

Repeatedly finds coordinates reachable from the current list of coordinates starting with just the given coordinate. Then creates grids from each of these lists with their grid number at the identified coordinates and reduces these with logical OR to keep the first non-zero value at each coordinate. This has the initial position as \\$1\\$ rather than \\$0\\$, so all numbers are then reduced by one.

```
W8p¤ạṢ€ċØ½ʋƇ$ƬŒṬĖP€o/’ - Link: integers [x, y]
W                      - wrap -> [[x, y]]
             Ƭ         - collect up while distinct applying:
            $          -   last two links as a monad:
   ¤                   -     nilad followed by link(s) as a nilad:
 8                     -       eight
  p                    -       ([1..8]) Cartesian power ([1..8]) -> all coordinates
           Ƈ           -     keep those for which:
          ʋ            -       last four links as a dyad:
    ạ                  -         absolute difference (vectorises)
     Ṣ€                -         sort each
        Ø½             -         [1,2]
       ċ               -         count occurrences
              ŒṬ       - convert to grids of zeros with ones at the coordinates
                Ė      - enumerate -> [[1, 1st grid], [2, 2nd grid], ...]
                 P€    - product of each -> grids with 1s replaced by grid number
                    /  - reduce by:
                   o   -   logical OR (vectorises)
                     ’ - decrement

```

---

Alternative 22, same method just identifying the existence of `[1,2]` and `[2,1]` by filtering for those which, when sorted, are invariant under the operation of getting the range of their length (`[1,2]`):

```
W8p¤ạṢJƑ$Ƈ¥Ƈ$ƬŒṬĖP€o/’

```

# Answer
> 11 votes
# Knight, ~~272~~ ~~264~~ ~~193~~ ~~190~~ 188 bytes

```
;=nF;=xP;=yP;=sS*'9'64+*8y xT0;W>9=n+1n;=r~1W>8=r+1r;=c~1W>8=c+1c;=a~3W>4=a+1a;=b~3W>4=b+1b&?5+*a a*b b&&&&>8=x+a r<~1x&>8=y+b c<~1y>E Gs+x*8yT=qGs+r*8cT=sSs+x*8yT+1q;=i~8W>64=i+8iO Gs i 8

```

Input is 0-based horizontal and vertical coordinates, each on separate lines.

A fitting language for this challenge... or maybe not...

Try it Online!

Here's the Knight code translated to Python: Try It Online!

# Answer
> 9 votes
# MATL, ~~34~~ ~~32~~ ~~31~~ 29 bytes

```
8t&Oli(9:"tt3Zv&+3=Z+g<@Q*+]q

```

Input is a cell array with the vertical and horizontal coordinates, starting at top left, 1-based.

Try it online!

### How it works

```
8t&O      % Push 8×8 array of zeros
li(       % Write 1 at the position taken as input
9:"       % For each k in [1, 2, ..., 9]
  t       %   Duplicate. This is the current pattern, to be extended. A 0 in an
          %   entry means position not yet reached. A non-zero value indicates
          %   the required number of moves plus 1
  t       %   Duplicate again
  3Zv     %   Symmetric range: [1 2 3 2 1]
  &+      %   5x5 matrix of pair-wise additions
  3=      %   True for entries that equal 3. This gives a 5×5 matrix containing
          %   the 8 possible moves for a knight
  Z+      %   2-dimensional convolution of the two above matrices, maintaining
          %   the size of the former (8×8) in the output
  g       %   Convert the result to logical: non-zeros become 1
  <       %   Less than (element-wise)? This indicates *new* available positions
  @Q*     %   Multiply element-wise by k+1
  +       %   Add, element-wise. This updates the pattern with the new values
]         % End
q         % Subtract 1 element-wise. Implicit display

```

# Answer
> 8 votes
# gbz80 machine code on Better Game Boy, 128 127 124 123 118 117 bytes

```
11 03 04 21 80 FF 06 08 0E 08 7C 22 0D 20 FC 3E
0D 22 3E 0A 22 05 20 F0 70 26 2F CD 7A 01 52 18
08 64 64 01 00 80 FF 00 00 76 24 3E 37 BC 28 43
3E 07 BA 38 3E BB 38 3B 3E 80 2E 0A 83 2D 20 FC
82 4F F2 BC 38 2D 7C E2 D5 14 1C 1C CD 7A 01 14
1D CD 7A 01 1D 1D CD 7A 01 15 1D CD 7A 01 15 15
CD 7A 01 15 1C CD 7A 01 1C 1C CD 7A 01 14 1C CD
7A 01 D1 25 C9

```

Eight more bytes can be saved from severe compromises to printed data, read the assembly source to learn more.

As a detail of the Game Boy platform, it must be placed at 0x150, and be jumped to from the entrypoint at 0x100. I opted to not count that because of it being standard GB dev practice (the entrypoint gives you only four bytes to work with).

I know that this answer sucks in terms of length (all those calls!), but I was overcome by the urge to do it for a problem after seeing someone else do x86 real-mode machine code elsewhere, and for this problem to get it to 0x80 bytes. I have no idea why I did this, I'm an ASM noob, but here we are.

BGB is specified because of the desire to print the answer. BGB has a debug print function that is only usable by its debugger (and that of no$gmb and a few others).

The initial position is encoded in the second and third byte and zero-indexed: second is y, third is x.

As for checking my answer, I suppose the only way is to have you download my ROM, or for you to assemble my assembly using rgbds. I have put both on GitHub. My assembly is incredibly undercommented.

Edit 1: Shortened corrective increments and decrements into a push and pop, saving one byte.

Edit 2: Moving various things around allowed saving 3 bytes, as well as much better pruning.

Edit 3: Remove decrement that was never necessary, saving 1 byte. That's embarrassing.

Edit 4: Removing a useless load and moving things around in the init loop to allow use of postincrement indexing saved 5 bytes, and the ability to remove 9 8 bytes with severe compromises was identified.

Edit 5: thejonymyster reminded me that I may assume valid input, moving one byte from compromises to saved.

# Answer
> 5 votes
# Wolfram Language (Mathematica), 55 bytes

```
GraphDistance[8~KnightTourGraph~8,#+8#2+1]~Partition~8&

```

Try it online!

Using the built-in `KnightTourGraph` function.

---

If the strict output format is required:

# Wolfram Language (Mathematica), 69 bytes

-6 bytes and fixed a bug thanks to @att and @Steffan

```
StringRiffle[GraphDistance[8~KnightTourGraph~8,#+8#2+1]~Partition~8]&

```

Try it online!

# Answer
> 5 votes
# Python 3 with numpy, ~~138~~ ~~136~~ 133 bytes

```
lambda*a:(S:=sum(D:=-abs(mgrid[:8,:8].T-a).T,0))-(amin([*D//2,S//3,2//S],0)+S&-2)+equal(*D)*(S&-~amin(S)//6==-4)*2
from numpy import*
```

Attempt This Online!

Example, with arguments 1,2 (a=`[1,2]`):

```
mgrid[:8,:8]
[[[0 0 0 0 0 0 0 0]   [[0 1 2 3 4 5 6 7]
  [1 1 1 1 1 1 1 1]    [0 1 2 3 4 5 6 7]
  [2 2 2 2 2 2 2 2]    [0 1 2 3 4 5 6 7]
  [3 3 3 3 3 3 3 3]    [0 1 2 3 4 5 6 7]
  [4 4 4 4 4 4 4 4]    [0 1 2 3 4 5 6 7]
  [5 5 5 5 5 5 5 5]    [0 1 2 3 4 5 6 7]
  [6 6 6 6 6 6 6 6]    [0 1 2 3 4 5 6 7]
  [7 7 7 7 7 7 7 7]]   [0 1 2 3 4 5 6 7]]]

```

This produces two matrices that hold the co-ordinates.

```
D:=-abs(mgrid[:8,:8].T-a).T
[[[-1 -1 -1 -1 -1 -1 -1 -1]  [[-2 -1  0 -1 -2 -3 -4 -5]
  [ 0  0  0  0  0  0  0  0]   [-2 -1  0 -1 -2 -3 -4 -5]
  [-1 -1 -1 -1 -1 -1 -1 -1]   [-2 -1  0 -1 -2 -3 -4 -5]
  [-2 -2 -2 -2 -2 -2 -2 -2]   [-2 -1  0 -1 -2 -3 -4 -5]
  [-3 -3 -3 -3 -3 -3 -3 -3]   [-2 -1  0 -1 -2 -3 -4 -5]
  [-4 -4 -4 -4 -4 -4 -4 -4]   [-2 -1  0 -1 -2 -3 -4 -5]
  [-5 -5 -5 -5 -5 -5 -5 -5]   [-2 -1  0 -1 -2 -3 -4 -5]
  [-6 -6 -6 -6 -6 -6 -6 -6]]  [-2 -1  0 -1 -2 -3 -4 -5]]]

```

Transpose, subtract `a`, and transpose again: this subtracts the arguments from the two matrices, respectively. Also take the absolute value and negate.

This produces the negative vertical and horizontal distances from the given square.

```
S:=sum(D,0)
[[ -3  -2  -1  -2  -3  -4  -5  -6]
 [ -2  -1   0  -1  -2  -3  -4  -5]
 [ -3  -2  -1  -2  -3  -4  -5  -6]
 [ -4  -3  -2  -3  -4  -5  -6  -7]
 [ -5  -4  -3  -4  -5  -6  -7  -8]
 [ -6  -5  -4  -5  -6  -7  -8  -9]
 [ -7  -6  -5  -6  -7  -8  -9 -10]
 [ -8  -7  -6  -7  -8  -9 -10 -11]]

```

Add the two matrices for the negative taxicab distance from the given square.

The reason for the negation is that we really want rounding-up division, but only have easy access to rounding-down division with `//`.

\\$\lfloor\frac{-n}{d}\rfloor = -\lceil\frac{n}{d}\rceil\\$

```
O:=amin([*D//2,S//3,2//S],0)
[[-1 -1 -2 -1 -1 -2 -2 -3]
 [-1 -2  0 -2 -1 -2 -2 -3]
 [-1 -1 -2 -1 -1 -2 -2 -3]
 [-2 -1 -1 -1 -2 -2 -2 -3]
 [-2 -2 -2 -2 -2 -2 -3 -3]
 [-2 -2 -2 -2 -2 -3 -3 -3]
 [-3 -3 -3 -3 -3 -3 -3 -4]
 [-3 -3 -3 -3 -3 -3 -4 -4]]

```

The `*D//2,S//3` part produces concentric octagons corresponding to the furthest points the knight can reach in a number of moves. `2//S` is 0 with a RuntimeWarning for S=0, −2 for S=1, −1 for S≥2; it makes a difference only in the case S=1, changing the values of the squares adjacent to the given square from −1 to −2.

```
S-(O+S&-2)
[[1 2 3 2 1 2 3 4]
 [2 3 0 3 2 3 2 3]
 [1 2 3 2 1 2 3 4]
 [2 1 2 1 2 3 2 3]
 [3 2 3 2 3 2 3 4]
 [2 3 2 3 2 3 4 3]
 [3 4 3 4 3 4 3 4]
 [4 3 4 3 4 3 4 5]]

```

A correction for parity: the number of moves should have the same parity as the the taxicab distance `S`. Add `S`, round down to the nearest multiple of 2 (by zeroing the low bit), and subtract `S`; also negate and simplify.

Finally, some more adjustments:

`+equal(*D)*(S&-~amin(S)//6==-4)*2`

* The squares two steps away along a diagonal should have value 4 instead of 2.
* If the given square is a corner square, the diagonally adjacent square should also have value 4 instead of 2.
* `equal(*D)` checks for squares sharing a diagonal with the given square.
* `amin(S)`, the negated highest taxicab distance, is −14 if the given square is a corner square, and otherwise ranges from −8 (for a centre square) to −13.
* `-~amin(S)` is one higher: −13 for corner squares, −7 to −12 otherwise.
* Floor-dividing by 6 produces −3 for corner squares and −2 otherwise.
* On the diagonals, S is even. ANDing with −2 = ...11102 leaves it unchanged, whereas ANDing with −3 = ...11012 zeroes the twos bit, mapping both −2 and −4 to −4.

The result:

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

```

# Answer
> 5 votes
# Python (*without* numpy), ~~142~~ 135 bytes

```
lambda x,y,k=[9]*64,r=range(64):[k:=[(x*8+y!=i)*k[i]and-~min(k[j]for j in r if(i%8-j%8)**2^(i//8-j//8)**2==5)for i in r]for _ in r][-1]

```

Attempt This Online!

Takes in x and y coordinate as separate inputs, outputs a flattened square list. The code for finding if two positions are a knight's move from each other is taken from Arnauld's answer to "Where can the knight be in N moves?".

---

-7 bytes from @CursorCoercer by moving the code onto a single line & into a lambda

# Answer
> 5 votes
# Python Numpy, 126 bytes

```
lambda*z:H[z]
from numpy import*
x=mat(tri(8)).I
x-=x*x
x+=x.T
H=8-inner(*([kron(x,x)-eye(64)<0,1]**c_[:8]).T).A
H.shape=4*[8]
```

Attempt This Online!

## How

The entire solution is precomputed, the function itself does no more than a simple lookup.

The finalised lookup table is 8x8x8x8, but while building it is reduced to 64x64.

We start by setting up the single step matrix and then take powers to cover sequences of moves.

#### 1 1D considerations

The 1D case is easy but useful to build on. We can go 1 or 2 units up or down. If we represent that in a 2D source-target matrix *x* this means that the two diagonals just above the main diagonal must be set and the two below.

#### 2 Go 2D

The two dimensions must be combined in an AND like way because the restriction 1 or 2 up or down holds along both axes. The Kronecker product does that, but there is the additional constraint that if it is 1 or 2 along one axis it must be the other along the other axis. This can be enforced by giving the 1. and 2. off diagonals different signs. After Kroneckering the valid bits will all be negative.

#### 3. Construct 1D

There are many ways to construct *x*. The shortest I found was: Get the upper or lower triangle. Take the inverse. This is almost what we want only shifted one unit to the centre. This can be fixed by taking the difference with the square. Finally, we must add (or OR) the transpose.

#### 4. Putting the bits together

After taking the Kronecker product we need to add the identity matrix so taking nth power gives the indicator of what's reachable in up to n steps. Conveniently, as the matrix at this point is boolean valued multiple paths to the same target are only counted as one. To get the right distance indices we must count in how many powers a target does not occur. Therefore, the type of the matrices must be changed to int *after* taking powers but *before* adding them together. We do this by taking the inner product with a vector of ones which forces coercion to int and then sums.

### Previous Python Numpy, 131 bytes

```
lambda y,x:65-((D:=Z==y*8+x)+sum(D:=D|M@D for _ in Z)).reshape(8,8)
import numpy
Z=numpy.c_[:64];X=Z//8+Z%8*1j
M=abs((X-X.T)**2)==5
```

Attempt This Online!

Conceptually straight-forward approach. Form the full 64-by-64 indicator matrix of knight's moves (by checking for Euclidean distance \\$=\sqrt 5\\$). Repeatedly multiply by it the indicator vector of the starting position.

# Answer
> 5 votes
# JavaScript (ES7),  ~~129 123~~  122 bytes

*Saved 1 byte thanks to a suggestion from @Coder on my answer to a previous challenge*

```
f=(x,y,n=0,m=[...s=1/0+''].map(_=>[...s]))=>m.map((r,Y)=>r.map((V,X)=>V<=n|((x-X)*(y-Y))**2^4||f(X,Y,n+1,m)),m[y][x]=n)&&m

```

Try it online!

### Commented

```
f = (                // f is a recursive function taking:
  x, y,              //   the current position (x, y)
  n = 0,             //   a move counter n
  m = [...           //   the output matrix m[], initialized to an array
    s = 1 / 0 + ''   //   of 8 arrays made of the string "Infinity"
  ].map(_ => [...s]) //   i.e. ["I", "n", "f", "i", "n", "i", "t", "y"]
) =>                 //
m.map((r, Y) =>      // for each row r[] at position Y in m[]:
  r.map((V, X) =>    //   for each entry at position X in m[]:
    V <= n |         //     do nothing if V is less than or equal to n
    (                //     or if the squared product of
      (x - X) *      //       x - X and
      (y - Y)        //       y - Y
    ) ** 2 ^ 4 ||    //     is not equal to 4
    f(               //     otherwise, do a recursive call:
      X, Y,          //       pass the new position (X, Y)
      n + 1,         //       increment the move counter
      m              //       pass m[] unchanged
    )                //     end of recursive call
  ),                 //   end of inner map()
  m[y][x] = n        //   set the current square to n
) && m               // end of outer map(); return m[]

```

# Answer
> 3 votes
# Charcoal, ~~59~~ 58 bytes

```
⊞υ⟦⁰ＮＮ⟧Ｆυ«≔⊟ιη≔⊟ιθＪηθＩΣιＦ⁸Ｆ⁸«Ｊλκ¿›⁼⁵⁺Ｘ⁻λη²Ｘ⁻κθ²℅ＫＫ⊞υ⟦⊕Σικλ

```

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

```
⊞υ⟦⁰ＮＮ⟧

```

Start a breadth-first search by placing a `0` at the input coordinates.

```
Ｆυ«

```

Loop over the squares as they are discovered.

```
≔⊟ιη≔⊟ιθＪηθＩΣι

```

Set this square to the current number of steps.

```
Ｆ⁸Ｆ⁸«Ｊλκ

```

Loop over the whole board.

```
¿›⁼⁵⁺Ｘ⁻λη²Ｘ⁻κθ²℅ＫＫ

```

If this is an empty square that is a Euclidean distance of √5 from the current square, then...

```
⊞υ⟦⊕Σικλ

```

... save this square as being one more step away.

# Answer
> 3 votes
# C (clang), 153 bytes

12 bytes thanks to ceilingcat!

```
e;r(*b,x,y,l,i){for(;i--&&x>0&y>0&x<9&y<9&l<9;b[e=x+y*8]>l?b[e]=l:0)e="XVTPJFDB"[i]-65,r(b,x+e%5-2,y+e/5-2,l+1,8);}f(*b,x,y){r(memset(b,1,324),x,y,0,8);}

```

Try it online!

# Answer
> 2 votes
# C (gcc), ~~191~~ ~~179~~ 176 bytes

*-15 bytes thanks to @ceilingcat*

```
f(a,x,y)int*a;{a[x=x*8+y]=!memset(a,1,256);r(a,x);}r(a,x,b,y)int*a;{for(b=0;++b<9;x/8==y>>3&a[x]+1<a[y-=8*~(~b&1)*~-(b&2)]&x>>6==y>>6&&r(a,y,a[y]=a[x]+1))y=x-~(b&1)*~-(b/2&2);}

```

Try it online!

# Answer
> 2 votes
# Retina, 121 bytes

```
.+
*#8*$(8*_ ¶
^(#)*((?<-1>.)*)_
$2$#1
s)+`(?<=(\d)(....|.{11}|.{13})?.{7})_|_(?=.{7}(....|.{11}|.{13})?(\d))
$.(_$1*_$4*

```

Try it online! Takes input as a pair of 0-indexed digits. Explanation:

```
s)`

```

Run the whole script in single-line mode where `.` also matches newlines.

```
.+
*#8*$(8*_ ¶

```

Treat the input as base 10 and insert that many `#`s followed by an empty chessboard of 8 rows of 8 `_`s terminated by spaces and newlines to bring each row up to 10 characters.

```
^(#)*((?<-1>.)*)_
$2$#1

```

Replace the `n`th character of the chessboard with a `0`, removing `n`. (`$#1` is just a weird way of saying `0`; I can't use `0` literally because it will tokenise with the previous `2`.)

```
+`

```

Repeat until no more changes can be made.

```
(?<=(\d)(....|.{11}|.{13})?.{7})_|_(?=.{7}(....|.{11}|.{13})?(\d))

```

Search for all empty squares that are a knight's move away from a square that already contains a digit (which will always be the largest digit so far).

```
$.(_$1*_$4*

```

Replace them with the next digit.

# Answer
> 2 votes
# K (ngn/k), ~~48~~ 46 bytes

```
8 8#{x&1+&/'x@&'4=*/4#i-\:'i:!8 8}/9*~(!64)=8/

```

Try it online!

# Answer
> 1 votes
# Perl 5, 155 bytes

```
sub{$_=$"x64;($x,$y,$i,@_)=@_,"$x$y"=~/^[0-7]{2}$/&&s/(?<=^.{@{[$x+$y*8]}}) /0+$i/e&&push@_,map{/./;$x+$&-3,$y+$'-3,$i+1}21,41,12,52,25,45,14,54while@_;$_}

```

Try it online!

Somewhat ungolfed:

```
$f=

sub {
  $_ = $"x64;                      #init board string to 64 spaces
  ($x, $y, $i, @_) = @_            #move x, y and i from head of @_ param array
  ,
  "$x$y"=~/^[0-7]{2}$/             #if x,y within board
  &&                               #and
  s/(?<=^.{@{[$x+$y*8]}}) /0+$i/e  #space found+replaced by i+1 in current x,y
  &&                               #and
  push @_,                         #push possible jump to cells to todo-queue
    map {/./; $x+$&-3, $y+$'-3, $i+1 }
    21, 41, 12, 52, 25, 45, 14, 54 #knight pos cells digits x-3,y-3
        while @_;                  #...all that while there's more to do
  $_                               #return filled up 64 char board string
}

;print &$f( 1 , 0 ) =~ s/.{8}/$&\n/gr,"\n";

```

Output:

```
30323234
23212343
12143234
23232343
32323434
43434345
34343454
45454545

```

---
Tags: code-golf, grid, graph-theory, chess
---


title: Conway's Monster

text:
# Question
Title: Conway's Monster
This challenge is in honor of mathematician John Conway who passed away April 11, 2020 due to COVID-19. He was famous for coming up with the Game of Life cellular automaton and many other mathematical contributions such as the surreal numbers and the monster group.

The advanced math of those topics is out scope for this programming challenge, though I strongly recommend people watch the various Numberphile videos about Conway. In one of those videos Conway says that he'd like to know why the monster group exists before he dies. It's unfortunately too late for that now but we can honor his memory in a very small way by exploring in code the strange number associated with the group.

# Challenge

The monster group is the largest sporadic simple group in the branch of group theory in mathematics. But the only thing to know for this challenge is that its order, or number of elements it contains is:

```
808017424794512875886459904961710757005754368000000000

```

Your task is to write a program that outputs this number. *However*, to keep this from being trivial, your program may not contain any digits, 0 through 9. That is, **your program may not contain any of the ten characters `0123456789`**.

Your output must be the precise digits of the number:

```
808017424794512875886459904961710757005754368000000000

```

or the digits with appropriate commas:

```
808,017,424,794,512,875,886,459,904,961,710,757,005,754,368,000,000,000

```

(Commas `,` are allowed in your code.)

Any usual output method is valid. No input should be required. **The shortest program in bytes wins.**

If it helps anyone the factorization of the number is:

```
2^46 * 3^20 * 5^9 * 7^6 * 11^2 * 13^3 * 17 * 19 * 23 * 29 * 31 * 41 * 47 * 59 * 71

```

(Factorization is not valid output.)

# Answer
# Sledgehammer, 4 bytes

 31 bits, to be overly specific
please upvote the author of this awesome language instead of me

```
⣶⣖⡥⣕

```

(this is a very awesome Mathematica compressor, and it ***really*** excels at compressing code with only a few powerful built-ins)

In this case, the built-ins are `GroupOrder` and `MonsterGroupM`, because of course they exist.

In case this somehow helps, the exact bits contained in the code are `01110111 01110101 10110010 1011010`, the corresponding Mathematica code is `GroupOrder@MonsterGroupM[]`, and the internal suffix code is `call["MonsterGroupM", 0], call["GroupOrder", 1]`, where 0 and 1 are the argument counts.
> 22 votes

# Answer
# Python 2, 61 bytes

Port of Neil's answer.

*-5 bytes thanks to @Surclose Sputum!*

```
for i in"  @@G^dddrstuuuvwxxy{|~~~~~":True*=ord(i)
print True

```

Try it online!

---

# Python 3, ~~60~~ 58 bytes

*Thanks to @Surculose Sputum for saving 2 more bytes!*

```
k=True
for i in b"?G^dddrstuuuvwxxy{|~~~~":k*=i+i
print(k)

```

Try it online!
> 16 votes

# Answer
# Jelly, 21 bytes

```
⁴Ḥ®x“ÆÑ¥©µ"µ£€× œ‘;Æ¡

```

**Try it online!**

### How?

$$|M|=13\times 43!+16\times 42!+4\times 41!+6\times 40!+9\times 39!+34\times 38!+9\times 37!+2\times 36!+12\times 35!+17\times 34!+32\times 33!+30\times 32!$$

So...

```
⁴Ḥ®x“ÆÑ¥©µ"µ£€× œ‘;Æ¡ - Main Link: no arguments
⁴                     - literal 16
 Ḥ                    - double = 32
  ®                   - recall from register = 0
   x                  - times = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    “ÆÑ¥©µ"µ£€× œ‘    - list of code-page indices = [13,16,4,6,9,34,9,2,12,17,32,30]
                  ;   - concatenate = [13,16,4,6,9,34,9,2,12,17,32,30,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
                   Æ¡ - convert from factorial base to integer

```

---

For what it's worth a naive base-250 compression is 25 bytes AND contains digits: `“Æ4Ḍ⁹|oGO⁷pNJ6þḤ)Ė⁽u2ẏẏż’`
> 15 votes

# Answer
# Charcoal, ~~32~~ 29 bytes

```
ＩΠＥ/Gdddrstuuuvwxxy{|~~~~~⊗℅ι

```

Try it online! Explanation: Converts the characters to their ASCII character codes, doubles them, then takes the product. Edit: Saved 3 bytes by porting @SurculoseSputum's golf of @dingledooper's Python 3 answer.

However, Charcoal can just compress the output text... except that compression of the whole text includes an `8`, so you have to print it in two parts:

```
”)¶″³L⬤j$a◧EτB⊟[βω⁵↓≧Ｏ””|～ⅉE

```

(Compressing the string in the first program doesn't help as the resulting string contains a digit.)

Try it online! Link is to verbose version of code.
> 12 votes

# Answer
# Wolfram Language (Mathematica), ~~34~~ 32 bytes

*Thanks @my pronoun is monicareinstate for shaving 2 bytes!*

Someone has to do this...

```
Print@GroupOrder@MonsterGroupM[]

```

Try it online!
> 8 votes

# Answer
# Ruby, 67 bytes

```
"nn/HM|Q:iv^YxO[e}%W}}WTBn}}}}}}}}".bytes{|i|$><<(i+?A.ord)%?_.ord}

```

Try it online!

By coincidence, the range of digit pairs is 0 to 94, which only just fits in the ASCII range.

`(i+?A.ord)%?_.ord` = `(i+65)%95`. The 65 offset ensures no digit characters in the magic string.

By default numbers are printed without leading zeros, so digit pairs in the range `00..09` require two characters in the magic string. The other digit pairs require one character.
> 6 votes

# Answer
# MATL, 35 bytes

```
'nTIFBCAAAAA@A@A@A@@A'tfYqwIEW-^X$p

```

Try it online!

### Explanation

This uses the prime factorization of the number:

\\$ 808017424794512875886459904961710757005754368000000000 \\ = 2^{46} · 3^{20} · 5^9 · 7^6 · 11^2 · 13^3 · 17 · 19 · 23 · 29 · 31 · 41 · 47 · 59 · 71. \\$

```
'nTIFBCAAAAA@A@A@A@@A' % Push this string
t                      % Duplicate
f                      % Indices of nonzero chars: gives [1 2 3 ... 19 20]
Yq                     % n-th prime, element-wise: gives [2 3 5 ... 67 71]
w                      % Swap
IEW                    % Push 3, multiply by 2, exponential with base 2: gives 64
-                      % Subtract, element-wise: subtracts 64 from the code point
                       % of each character of the string. Gives [46 20 9 ... 0 1]
^                      % Element-wise power. Gives [2^46 3^20 5^9 ... 1 71]
X$                     % Convert to symbolic (to achieve arbitrary precision)
p                      % Product. Implicit display

```
> 5 votes

# Answer
# Java 8, 86 bytes

```
v->"ᾑ䐑Ἂ㉌⊡▒д᭞ᵸ᪑".chars().forEach(c->System.out.print(~-c))

```

Try it online.

**Explanation:**

```
v->  // Method with empty unused parameter and no return-type
  "ᾑ䐑Ἂ㉌⊡▒д᭞ᵸ᪑".chars().forEach(c->
     //  Loop over the characters of this string as integer codepoints:
    System.out.print(~-c))
     //   Print this integer - 1 to STDOUT

```

The string contains the characters with the codepoints:

```
8081,17425,7946,12876,8865,59905,9618,1076,7006,7544,6801,1,1,1,1,1,1,1

```
> 5 votes

# Answer
# Jelly, ~~37~~ 30 bytes

```
ØẠiⱮ“tTIFBC”;⁽<(B¤
³ÆRṁ¢ż¢*/€P

```

Encodes the number as a list of exponents to primes, probably could be optimized with cleverer builtins

```
ØẠiⱮ“tTIFBC”;⁽<(B¤
    “tTIFBC”       the string "tTIFBC"
  iⱮ               find indices of each character in
ØẠ                 the alphabet in both cases "A..Za..z"
             ⁽<( ¤ the number 16041
                B¤ converted to binary
            ;      append

```

```
³ÆRṁ¢ż¢*/€P
 ÆR         all primes below
³           100
   ṁ        shaped like
    ¢       the above line
     ż      zipped with
      ¢     the above line
       */€  exponent for each pair
          P product

```

-7 bytes by encoding the final 0/1 sequence as binary

Try it online!
> 4 votes

# Answer
# 05AB1E, ~~29~~ ~~28~~ 27 bytes

-1 byte thanks to @KevinCruijssen

```
•∍ýö/V$Éb´‰ŒrƶÜλFÄôS•¦¾T<×«

```

Try it online!

---

# 05AB1E, 21 bytes

Answer suggested by @KevinCruijssen as a port of the Jelly answer by @JonathanAllen

```
₆ÍRžwŸ!•Pǝ½ζÄž,Ā•₆в*O

```

Try it online!
> 4 votes

# Answer
# Haskell, 91 bytes

```
import Data.Numbers.Primes
product[p^length[';'..c]|(c,p)<-zip"hNC@<=;;;;;:;:;:;::;"primes]

```

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

Probably suboptimal but I had a lot of fun writing it. I encode the prime exponents (including zeroes for the primes it doesn't have prior to 71) as a string using the character's relative distance from `:`. the rest is a simple matter of zipping the exponents against an infinite list of all primes, raising those primes to that power, and taking the product.

Edit: forgot to take the `x=` out of the source code on here.
> 4 votes

# Answer
# C (gcc), ~~84~~ \\$\cdots\\$ ~~81~~ 83 bytes

Saved a byte thanks to ceilingcat!!!
Added 2 bytes to fix a bug kindly pointed out by gastropner.

```
*s;f(){for(s=L"nn/HM|Q:iv^YxO[e}%W}}WTBn}}}}}}}}";*s;)printf("%d",(*s+++'A')%'_');}

```

Try it online!

Port of Level River St's Ruby answer.
> 4 votes

# Answer
# Vyxal, ~~27~~ 25 bytes

*Thanks to Underslash for -2 bytes because numbers.*

```
»$⇩∪£¼ɾǏ℅yṙ`₆gǏ¦¨λ»kεk×**

```

Try it Online!

Unfortunately, the compressed form of the number contains a `2` and a `0`. This is a different number, multiplied by another number multiplied by another number, to get the target number.

```
»$⇩∪£¼ɾǏ℅yṙ`₆gǏ¦¨λ»        # Push 11482618231106483731969943632999939453125
                   kε      # Push 32768
                     k×    # 2147483648
                       **  # Multiply all the numbers
                           # Implicit output

```
> 4 votes

# Answer
# Wolfram Language (Mathematica), 93 bytes

```
FromDigits[LetterNumber/@Characters@"h h agdbdgideabhgehhfdeii difaga geg  egedcfh         "]

```

Try it online!
> 3 votes

# Answer
# Bash \+ Core utilities, 67 bytes

```
tr o-z /-:<<<xpxpqwtrtwytuqrxwuxxvtuyyptyvqwqpwuwppuwutsvxppppppppp

```

Try it online!
> 3 votes

# Answer
# Octave, 50 bytes

```
prod(primes('G').^sym('hNC@<=;;;;;:;:;:;::;'-':'))

```

Try it online!
> 3 votes

# Answer
# brainfuck, ~~183~~ ~~171~~ 170 bytes

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

```

Try it online!

Linebreaks added for readability so not included in the byte count.
> 3 votes

# Answer
# C++ (gcc), ~~82~~, 76 bytes

### *Kudos to @ceilingcat for -6 bytes*

```
void f(){for(auto s:L"ƴ")printf("%i",s);printf("%i%i%i",!f,!f,!f);};

```

Try it online!

# C++ (gcc), 82 bytes

```
void f(){for(auto s:L"ƴ")printf("%i",s);printf("%i%i%i",NULL,NULL,NULL);};

```

Try it online!

My first ever Code Golf submission! :)

Explanation: The loop part of the function prints a decimal representation for each Unicode character in the string. I was really stumped as to how to print zeros without being allowed to have `0` in the code. I just added `NULL` characters cast to `int`.
> 3 votes

# Answer
# Jelly, 14 bytes

```
“ ½‘!P×“ḥɗeŀƊ’

```

Try it online!

Just saw alephalpha's answer before edit and thought "what if I port it to Jelly?" and it worked.

Uses the formula from this comment:

> `31!10!27079205916672`

then I noticed that `27079205916672` is a multiple of 32, so I changed the formula to

> `32!10!846225184896`

cutting one more byte from the compressed number.

The Jelly code does "`“ ½‘` (32, 10) `!P` factorial each and product `×` times `“ḥɗeŀƊ’` 846225184896".
> 3 votes

# Answer
# JavaScript (Node.js),  ~~79 78~~  58 bytes

*Saved 20 (!) bytes thanks to @tsh*

A port of Neil's approach.

```
_=>eval(Buffer("?@^ddrtuuuvwxxy{|~~~~Ȁ掀").join`n*`+'n')

```

Try it online!

---

# JavaScript (Node.js), 93 bytes

```
_=>eval('ZxEDCCCCBAECEBBBBn*ZxEAAFEEEFECn*ZxFFCn*ZxFDDAAEn*ZxAZZZZZZZZZZn'.replace(/Z/g,+[]))

```

Try it online!

The idea here was to look for factorizations of \\$N\\$ with factors whose hexadecimal representation only contains letters and \\$0\\$'s, so that we only need to replace \\$0\\$'s with a substitute character.

There are countless possibilities. We use this one:

```
0xEDCCCCBAECEBBBB * 0xEAAFEEEFEC * 0xFFC * 0xFDDAAE * 0xA0000000000

```

---

# JavaScript (Node.js), 101 bytes

```
_=>eval("FxHOOFdNebfLLMHOGdFMcFGKKffKn*In**HFn<<JLn".replace(/[A-Z]/g,c=>c.charCodeAt()%(~[]+[+[]])))

```

Try it online!

The encoded expression is:

```
0x2990d8ebf667291d07c0155ff5n*3n**20n<<46n

```
> 2 votes

# Answer
# Java (JDK), 81 bytes

```
v->"XPXPQWTRTWYTUQRXWUXXVTUYYPTYVQWQPWUWPPUWUTSVXPPPPPPPPP".chars().map(n->n-' ')

```

Try it online!

If Java's `int` allowed for (much) more than 32 bits, the following (65 bytes) would have worked:

```
v->",--------<?DGLRT\\^hhhpppptv|".chars().reduce(',',(a,b)->a*b)

```
> 2 votes

# Answer
# Ruby, ~~50~~ 47 bytes

```
p eval (%w(Gv/ R>t. &DhP)*" @QQH}bMA").bytes*?*

```

Try it online!

Thanks histocrat for -1 byte, ad Jo King for pointing out some silliness in the original answer.
> 2 votes

# Answer
# K4, 64 bytes,

**Solution:**

```
,/$.Q.a?"iaiabhecehjefbcihfiigefjjaejgbhbahfhaafhfedgiaaaaaaaaa"

```

**Explanation:**

Really boring, lookup each letter in the alphabet (e.g. "b" =\> 1), convert to string and flatten

```
    ,/$.Q.a?"iaiabhecehjefbcihfiigefjjaejgbhbahfhaafhfedgiaaaaaaaaa" / solution
            "iaiabhecehjefbcihfiigefjjaejgbhbahfhaafhfedgiaaaaaaaaa" / a -> 0, b -> 1 etc
       .Q.a?                                                         / lookup in built-in alphabet a-z
      $                                                              / convert to string
    ,/                                                               / flatten

```
> 2 votes

# Answer
# Perl 6, 42 bytes

```
say [*] ²X*'``}}}~~~~~yuuuwr\t|{^;G'.ords

```

Try it online!

Uses the same strategy of reducing the ordinal values of a string by multiplication as other answers, but also multiplies each element by 2 beforehand to save a byte on representing all those powers of two.
> 2 votes

# Answer
# Red, ~~88~~ 78 bytes

```
foreach c"XPXPQWTRTWYTUQRXWUXXVTUYYPTYVQWQPWUWPPUWUTSVXPPPPPPPPP"[prin c - sp]

```

Try it online!
> 1 votes

# Answer
# Io, 79 bytes

```
"ᾑ䐑Ἂ㉌⊡▒д᭞ᵸ᪑"foreach(i,(-i)bitwiseComplement print)

```

Try it online!
> 1 votes

# Answer
# Pyth, 41 bytes

```
*F^MC,fP_TSC\G+C\.xLG"ujgcdbbbbbabababaab

```

Try it online!

```
*F^MC,fP_TSC\G+C\.xLG"ujgcdbbbbbabababaab    Implicit: G=lower case alphabet

                   L "ujgcdbbbbbabababaab    For each character in the string...
                  x G                        ... find it's index in the alphabet
              +C\.                           Prepend 46 (character code of .) - these are the prime powers
           C\G                               71
          S                                  Range 1-71
      fP_T                                   Filter keep the primes in the above
     ,                                       Pair the primes with the prime powers
    C                                        Transpose
  ^M                                         Map exponent operator over each pair
*F                                           Take product of the result, implicit print

```
> 1 votes

# Answer
# Deadfish~, 164 bytes

```
iiisdo{d}oiiisdo{d}oioisiiiodddoddosoiiioiiodddddoioddddoioisdododdoiiiooddoddoioddsoo{d}oiisodsodddo{d}ioisiiio{d}iodoiisiiioddoiio{d}ooiisioiioddododoiiioii{o{d}}

```

Try it online!
> 1 votes

# Answer
## C (gcc), 77 bytes

```
*s;f(){for(s=L"pp!'JO~S<kx`[zQ]g kf YVDp        ";*s;)printf("%d",*s++-' ');}

```

Assumes that `wchar_t` and `int` have the same size. This way we can make the string wide and we can omit the type when declaring `s`.

A naive approach: group the digits in blocks of 1–3, each of which is an integer between 0 and 127 with no leading 0. Since character 0 can't be present in the string, characters are encoded as their value plus some constant. The constant is 32, which has the advantage of keeping all characters printable.

### C (gcc), 78 bytes

Bonus: without relying on `wchar_t` and `int` having the same size. We save 1 byte (the `L`) by not having a wide string, but lose 1 byte because the implicit-int declaration `*s` is replaced by the explicit type name `char`.

```
f(){for(char*s="pp!'JO~S<kx`[zQ]g kf YVDp        ";*s;)printf("%d",*s++-' ');}

```

Try it online!
> 1 votes

# Answer
# \>\<\>, 36 bytes

`|.ab*n!?+il"ØØØØØØÕìëöøèúúæò÷õîÐÐÄp"`

Try it online!

It's based on a hand-optimized list of partial products of the prime factors of the number, each fitting within a byte.
> 1 votes

# Answer
# MathGolf, 18 bytes

```
8462NG4896]y♂!♥!**

```

Try it online.

**Explanation:**

```
8462NG4896    # Push the integers 8,4,6,2,25,18,4,8,9,6
          ]   # Wrap the stack into a list
           y  # Join it together, and implicitly convert it to an integer: 846225184896
♂!            # Push 10!: 3628800
♥!            # Push 32!: 263130836933693530167218012160000000
**            # Multiply all three values on the stack together
              # (after which the entire stack is output implicitly as result)

```
> 1 votes

# Answer
### Javascript, 93 characters

```
_=>'ÉÉŠ£¨×¬•ÄÑ¹´Óª¶ÀyÄ¿y~Ä¤½yyyyyyyyy'.split``.map(c=>c.charCodeAt()-'y'.charCodeAt``).join``

```

The function returns `"808017424794512875886459904961710757005754368000000000"`.

Explanation: Each character in the string is encoding two characters in the target. Because low character codes are a mess, we offset them by 121 ("y"). I also had to pad some extra 0s (y's) into the string because for instance a "y" and "yy" both convert to "0".

### Port of Kevin Crujissen's answer (63 characters):

```
v=>"ᾑ䐑Ἂ㉌⊡▒д᭞ᵸ᪑".split``.map(c=>~-c.charCodeAt()).join``

```
> 0 votes

# Answer
# R, 99 bytes

```
cat(match(strsplit("iaiareyhjefmihfiigefjjaejgrkhfhaafhfedgiaaaaaaaaa","")[[T]],letters)-T,sep="")

```

Fairly simple zero-based mapping from digits to letters, and using `T` as a substitute for `1`.
> 0 votes

# Answer
# BRASCA, ~~72~~ 66 bytes

```
`B:B:;A><>AC>?;<BA?BB@>?CC:>C@;A;:A?A::?A?>=@B:::::::::`![al-mA{]x

```

Try it online!

## Explanation

```
`B:B:;A><>AC>?;<BA?BB@>?CC:>C@;A;:A?A::?A?>=@B:::::::::`            - Push the number, with the ASCII code shifted by 10
                                                        ![a  mA{]x  - Foreach in stack:
                                                           l-       -    Subtract 10 from the charcode
                                                                    - Implicitly output it

```
> 0 votes

# Answer
# PARI/GP, 60 bytes

```
print(vecprod(Vec(Vecsmall("$$$G^ddhhhprstvwxxxxy{|~~~~"))))
```

Attempt This Online!

Takes the product of the ASCII codes of the characters.

Here is the Mathematica code to find the string `"$$$G^ddhhhprstvwxxxxy{|~~~~"`.
> 0 votes

# Answer
# C#, 61 bytes

```
_=>"ᾐ䐐Ἁ㉋⊠░г᭝ᵷ᪐␀␀␀␀␀␀␀".Select(x=>+x+"")

```

Try it online!

---

Converts a series of characters to their codepoints and then converts that to a string:

```
ᾐ  8080
䐐  17424
Ἁ  7945
㉋  12875
⊠  8864
  59904
░  9617
г  1075
᭝  7005
ᵷ  7543
᪐  6800
␀  0

```

here is a null byte (U+0000)
> 0 votes

---
Tags: code-golf, math, kolmogorov-complexity, integer, restricted-source
---