title: Could you make me a hexagon please?

text:
# Question
Title: Could you make me a hexagon please?
Today, we're going to make an ASCII hexagon. You must write a program or function that takes a positive integer *n*, and outputs a hexagon grid of size *n*, made up of asterisks. For example, a hexagon of size 2 looks like this:

```
 * *
* * *
 * *

```

While a hexagon of size 3 looks like this:

```
  * * *
 * * * *
* * * * *
 * * * *
  * * *

```

You may use any of the default input and output methods, for example STDIO/STDOUT, function arguments and return values or reading/writing a file.

You may assume that input is always valid, so if it's not a positive integer, your program may do whatever you want. You *do* however have to handle the special case of a size 1 hexagon, which happens to be a single asterisk:

```
*

```

Leading and trailing whitespace is allowed as long as the output is visually the same.

# Examples:

```
1:
*

2:
 * *
* * *
 * *

3:
  * * *
 * * * *
* * * * *
 * * * *
  * * *

4:
   * * * *
  * * * * *
 * * * * * *
* * * * * * *
 * * * * * *
  * * * * *
   * * * *

5:
    * * * * *
   * * * * * *
  * * * * * * *
 * * * * * * * *
* * * * * * * * *
 * * * * * * * *
  * * * * * * *
   * * * * * *
    * * * * *

6:
     * * * * * *
    * * * * * * *
   * * * * * * * *
  * * * * * * * * *
 * * * * * * * * * *
* * * * * * * * * * *
 * * * * * * * * * *
  * * * * * * * * *
   * * * * * * * *
    * * * * * * *
     * * * * * *

12:
           * * * * * * * * * * * *
          * * * * * * * * * * * * *
         * * * * * * * * * * * * * *
        * * * * * * * * * * * * * * *
       * * * * * * * * * * * * * * * *
      * * * * * * * * * * * * * * * * *
     * * * * * * * * * * * * * * * * * *
    * * * * * * * * * * * * * * * * * * *
   * * * * * * * * * * * * * * * * * * * *
  * * * * * * * * * * * * * * * * * * * * *
 * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * *
 * * * * * * * * * * * * * * * * * * * * * *
  * * * * * * * * * * * * * * * * * * * * *
   * * * * * * * * * * * * * * * * * * * *
    * * * * * * * * * * * * * * * * * * *
     * * * * * * * * * * * * * * * * * *
      * * * * * * * * * * * * * * * * *
       * * * * * * * * * * * * * * * *
        * * * * * * * * * * * * * * *
         * * * * * * * * * * * * * *
          * * * * * * * * * * * * *
           * * * * * * * * * * * *

```

As usual, this is , so standard loopholes apply, and you should try to write the shortest possible program measured in bytes. Of course, some languages are inherently shorter or longer than others, so remember that the goal is not necessarily to have the shortest overall byte count, but to beat submissions in the same or similar languages.

May the best golfer win!

# Answer
# Hexagony \+ Bash Coreutils, 0+3+8 = 11 Bytes

Includes +3 for `-g` flag and +8 for `|tr . \*` non-standard invocation (see this meta post)

```

```

Input is given as an argument to Hexagony. When the Hexagony interpreter is called with the `-g N` option it prints a hexagon of `.`s. We then use tr to replace those with `*`s.
> 41 votes

# Answer
## Python 2, 61 bytes

```
i=n=input()
while~-n+i:i-=1;j=abs(i);print' '*j+'* '*(2*n+~j)

```

Prints a trailing space at the end of each line.

Thanks to Erik the Outgolfer for saving a byte.
> 20 votes

# Answer
# Hexagony, ~~91~~ ~~87~~ 86 bytes

```
?{2'*=&~}=&}='P0</0P}|@..;>;'.\};0Q/..\&(<>"-_"&}=\?_&\/8.=-\<><;{M/.(.(/.-{><.{&'/_.\

```

Try it online!

Finally did it.

Initially (before realizing how expensive loops are) I expect this may be able to fit in side length 5, but now it's hard enough to fit it into side length 6.

To get this I actually have to modify the linear code a little. In fact, writing this makes me realize a way to golf the linear code down by ~~1~~ 2 byte.
> 15 votes

# Answer
# JavaScript (ES6), 77 ~~81 84~~

@Upvoters: don't miss the answer by @ETHproductions, that is 76 bytes

*Edit* Revised after change in spec, trailing space allowed

Just for the hat ... hey! No hat?

```
f=(n,b='* '.repeat(n+n-1),o=b)=>--n?f(n,b=` ${b}`.slice(0,-2),b+`
${o}
`+b):o

```

**Test**

```
f=(n,b='* '.repeat(n+n-1),o=b)=>--n?f(n,b=` ${b}`.slice(0,-2),b+`
${o}
`+b):o

function update()
{
  O.textContent=f(+I.value)
}

update()
```

```
<input id=I type=number min=1 value=3 oninput='update()'>
<pre id=O></pre>
```
> 13 votes

# Answer
# JavaScript (ES6), ~~77~~ 76 bytes

```
g=(n,s=`
*`+' *'.repeat(n*2-2),c=s,q=c.replace('*',''))=>--n?g(n,q+s+q,q):s

```

I told myself I wouldn't sleep until I had set a new ES6 record without looking at the other answers, so here it is...

### Test snippet

```
g=(n,s=`
*`+' *'.repeat(n*2-2),c=s,q=c.replace('*',''))=>--n?g(n,q+s+q,q):s

for(var i = 1; i < 7; i++) console.log(g(i)) // joe
```
> 12 votes

# Answer
# C, ~~91~~ ~~89~~ ~~80~~ 74 bytes

```
w,y;f(s){for(y=-s;++y<s;)for(w=printf("\n%*s",y,"");++w<s*printf(" *"););}

```

I pretty much tweaked around to get the correct formulas, then mashed it all together.

Call `f` with the number *n*, and it will print the hexagon to stdout.

**Ungolfed and explained (80-byte version):**

```
w,y;
f(s) {
    // y iterates over [-s + 1 ; s - 1] (the number of rows)
    for(y = -s; ++y < s;)
        // w iterates over [abs(y) + 2 ; s * 2 - 1] (the number of stars on the row)
        for(
            // This prints a backspace character (ASCII 8)
            // padded with abs(y) + 2 spaces, effectively
            // printing abs(y) spaces to offset the row.
            // Also initializes w with abs(y) + 2.
            printf("\n%*c", w = abs(y) + 2, 8);

            // This is the for's condition. Makes use
            // of the 2 returned by printf, since we coïncidentally
            // need to double the upper bound for w.
            w++ < s * printf("* ");

            // Empty for increment
        )
            ; // Empty for body
}

```

See it live on Coliru

**Notes:**

* `printf` can handle negative padding, which results in a left-aligned character with the padding on the right. Thus I tried something to the effect of `w = printf("%*c*", y, ' ')` so it would take care of the absolute value, and I could retrieve it from its return value. Unfortunately, both zero and one padding widths print the character on its own, so the three center lines were identical.
**Update:** Jasen has found a way to do exactly this by printing an empty string instead of a character -- 6 bytes shaved off!
* The backspace character is handled incorrectly by Coliru -- executing this code on a local terminal does remove the leading space on each line.
> 11 votes

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

Code:

```
F¹N+„ *×})û.c

```

Explanation:

```
F       }        # Input times do (N = iteration number)
 ¹N+             #   Calculate input + N
    „ *×         #   Multiply by the string " *"
         )       # Wrap everything into an array
          û      # Palindromize the array
           .c    # Centralize

```

Uses the **CP-1252** encoding. Try it online!
> 8 votes

# Answer
# Jelly, 24 bytes

```
R+’µạṀx@€⁶żx@K¥€”*$F€ŒḄY

```

Try it online!

Jelly is ashamed of the fact that it does not have a centralization atom, so it's beaten by 05AB1E and V. By 11 and 7 bytes respectively!

If you find any way to golf this, please comment. Any help is appreciated.

**Explanation**:

```
R+’µạṀx@€⁶żx@K¥€”*$F€ŒḄY Main link. Arguments: z.
R+’                      The sizes of the hexagon's rows. (implicit argument)
   µ                     Start a new monadic chain with the above argument.
    ȧṀx@€⁶               The spaces you must prepend to each row. (implicit argument)
           x@K¥€”*$      The stars (points) of each row, space-joined, as a single link. (implicit argument)
          ż        F€    Conjoin and merge the leading spaces with the stars appropriately.
                     ŒḄ  Create the second half of the hexagon without the middle row.
                       Y Join the rows with newlines. This makes the shape look like a hexagon.

```

Bonus: To find how many stars are there in a hexagon, use this:

```
Ḷ×6S‘

```
> 8 votes

# Answer
# Octave , ~~62~~ 58 bytes

```
@(n)' *'(dilate(impad(1,2*--n,n),[k='01010'-48;~k;k],n)+1)

```

Previous answer:

```
@(n)' *'(dilate(impad(1,2*(m=n-1),m),[k='01010'-48;~k;k],m)+1)

```

that can be called as

```
(@(n)' *'(dilate(impad(1,2*(m=n-1),m),[k='01010'-48;~k;k],m)+1))(5)

```

Try (paste) it on Octave Online

For example the base image for `n=5` is

```
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 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 0 0 0 0
0 0 0 0 0 0 0 0 1 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 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 0 0 0 0 0 0 0 0 0 0 0 0

```

that can be created with

```
impad(1,2*(n-1),n-1)

```

The `dilation morphological operator` applied 4 times on the image using the following neighbor mask:

```
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0

```

that can be created with `[k='01010'-48;~k;k]`

result of dilation:

```
0 0 0 0 1 0 1 0 1 0 1 0 1 0 0 0 0
0 0 0 1 0 1 0 1 0 1 0 1 0 1 0 0 0
0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 0
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 0
0 0 0 1 0 1 0 1 0 1 0 1 0 1 0 0 0
0 0 0 0 1 0 1 0 1 0 1 0 1 0 0 0 0

```

then replace 0 and 1 with ' ' and '\*' respectively

```
    * * * * *
   * * * * * *
  * * * * * * *
 * * * * * * * *
* * * * * * * * *
 * * * * * * * *
  * * * * * * *
   * * * * * *
    * * * * *

```
> 7 votes

# Answer
# APL (Dyalog Unicode), ~~40~~ ~~36~~ ~~35~~ ~~33~~ ~~27~~ 25 bytes

```
(⍉⊖⍪1↓⊢)⍣2∘↑⍳↓¨∘⊂'* '⍴⍨+⍨

```

Assumes `⎕IO←0`, i.e. zero-based indexing. The output contains one leading and one trailing spaces on each line.

Many thanks to @FrownyFrog and @ngn for lots of golfing.

Try it online!

### How it works

```
(⍉⊖⍪1↓⊢)⍣2∘↑⍳↓¨∘⊂'* '⍴⍨+⍨  ⍝ Main function train
                 '* '⍴⍨+⍨  ⍝   Repeat '* ' up to length 2×⍵
            ⍳↓¨∘⊂          ⍝   Generate lower-right corner of the hexagon
          ∘↑               ⍝   Convert to matrix
(⍉⊖⍪1↓⊢)                   ⍝   Palindromize vertically and transpose
        ⍣2                 ⍝   ... twice

```
> 6 votes

# Answer
# , 17 bytes

```
é*Àñ>{MÄpXA *Î.

```

Try it online!

As usual, here is a hexdump, since this contains unprintable characters:

```
00000000: e92a c0ad f13e 7b4d c470 5841 202a 1bce  .*...>{M.pXA *..
00000010: 2e                                       .

```
> 5 votes

# Answer
## postgresql9.6, 290 bytes

```
do language plpgsql $$ declare s constant smallint:=4;declare n smallint;declare a constant int[]:=array(select generate_series(1,s));begin foreach n in array a||array(select unnest(a)t order by t desc offset 1)loop raise info'%',concat(repeat(' ',s-n),repeat(' *',s+(n-1)));end loop;end;$$

```

formatted sql is here:

```
do language plpgsql $$
declare s constant smallint := 4;
declare n smallint;
declare a constant int[] := array(select generate_series(1, s));
begin
foreach n in array a || array(select unnest(a)t order by t desc offset 1) loop
    raise info '%', concat(repeat(' ', s - n), repeat(' *', s + (n - 1)));
end loop;
end;
$$;

```

output:

```
INFO:      * * * *
INFO:     * * * * *
INFO:    * * * * * *
INFO:   * * * * * * *
INFO:    * * * * * *
INFO:     * * * * *
INFO:      * * * *

```
> 5 votes

# Answer
# Python 2, ~~100~~ ~~97~~ ~~89~~ ~~88~~ ~~87~~ ~~81~~ 79 bytes

-1 from @Flp.Tkc

-6 again from @Flp

-2 with thanks to @nedla2004. I was trying to find how to get rid of the second slice but didn't think of that one :)

```
i=input()
a=[" "*(i-x)+"* "*(i+x)for x in range(i)]
print'\n'.join(a+a[-2::-1])

```

Try it online!

Creates an array for the top half then adds the reversed array minus the middle line then prints. Prints exactly "as is" apart from `1` which prints with a leading space (I guess that is allowed as a `*` is visually the same as a `*` with or without a leading space).
> 5 votes

# Answer
# JavaScript (ES6), 83 81 bytes

This is my first (code golf) answer. I hope I formatted everything correctly.

```
a=>{for(b=c=2*a-1;c;)console.log(" ".repeat(d=Math.abs(a-c--))+"* ".repeat(b-d))}

```

Unlike the 2 current ES6 answers, I'm not recursively calling a function and I am using the console for output.
> 5 votes

# Answer
## Haskell, ~~99~~ ~~97~~ 79 bytes

```
h n=mapM_(putStrLn.(\k->([k..n]>>" ")++([2..n+k]>>"* ")))([1..n-1]++[n,n-1..1])

```

Explanation: This program is based on the observation that each line of a n-Hexagon contains (n-k) spaces followed by (n+k-1) asterisks, for some k dependent on the line number.

```
h n=                                             h is a function of type Int -> IO ()
  mapM_                                          mapM_ executes a function returning
                                                 monadic actions on all objects
                                                 in a list, in order. Then it executes
                                                 these actions, in order. For this code, it
                                                 transforms each value in the list into a
                                                 monadic action that prints
                                                 the corresponding line

      (                                          the function consists of two components
        putStrLn                                 the second part is printing the result of
                                                 the first part to stdout

        .                                        concatenating both components

        (\k->                                    the first parts first prints (n-k) spaces
                                                 and then (n+k-1) asterisks

          ([k..n]>>" ")                          create the list of the integers from
                                                 k to n (That is actually one more entry
                                                 than necessary, but just results in a
                                                 leading whitespace per line, while
                                                 saving 2 bytes compared to [1..n-k]).
                                                 Then create a new list where
                                                 each element of that first list is
                                                 replaced with the string " " and
                                                 concatenate that result into one string

          ++                                     concatenate both lists

          ([2..n+k]>>"* ")                       create the list of the integers
                                                 from 2 to n+k (of length n+k-1).
                                                 Then create a new list where each
                                                 element of that first list is replaced
                                                 with the string "* " and concatenate
                                                 that result into one big string
        )

      )
      ([1..n-1]++[n,n-1..1])                     the list simply goes from 1 to n and
                                                 back, supplying the k

```

Edit: Switched to mapM\_. I was not aware that was available without using import
> 5 votes

# Answer
# Canvas, 9 bytes

```
╷⁸＋* ×］／─

```

Try it here!

Beating the built-in :D

Explanation:

```
{╷⁸+* ×]/─  implicit "{"
{      ]    map over 1..input
 ╷            decrement: 0..input-1
  ⁸+          add the input: input..(input*2-1)
    * ×       repeat "* " that many times
        /   diagonalify that - pad each line with 1 less space than the previous
         ─  palindromize vertically

```

<sub>~~No idea why there's the huge padding, but it's allowed & I'm fixing that soon™.~~ fixed? Hope I didn't break stuff</sub>
> 5 votes

# Answer
## JavaScript (ES6), 83 bytes

```
f=
n=>[...Array(n+--n)].map((_,i,a)=>a.map((_,j)=>j<n-i|j<i-n?``:`*`).join` `).join`
`
```

```
<input type=number min=1 oninput=o.textContent=f(+this.value)><pre id=o>
```
> 4 votes

# Answer
## Batch, 161 bytes

```
@echo off
set s=*
set l=for /l %%i in (2,1,%1)do call
%l%set s= %%s%% *
%l%echo %%s%%&call set s=%%s:~1%% *
echo %s%
%l%set s= %%s:~0,-2%%&call echo %%s%%

```

Note: Trailing space on line 2. Ungolfed:

```
@echo off
set s=*
rem build up the leading spaces and stars for the first row
for /l %%i in (2,1,%1) do call :s
rem output the top half of the hexagon
for /l %%i in (2,1,%1) do call :t
rem middle (or only) row
echo %s%
rem output the bottom half of the hexagon
for /l %%i in (2,1,%1) do call :b
exit/b
:s
set s= %s% *
exit/b
:t
echo %s%
rem for the top half remove a space and add a star to each row
set s=%s:~1% *
exit/b
:b
rem for the bottom half add a space and remove a star from each row
set s= %s:~0,-2%
echo %s%
exit/b

```
> 3 votes

# Answer
# Perl 6, 49 bytes

```
->\n{say " "x n*2-1-$_~"*"xx$_ for n...n*2-1...n}

```

Try it online!

### How it works

```
->\n{                                           }  # Lambda accepting edge size (e.g. 3)
                               for n...n*2-1...n   # For each row-size (e.g. 3,4,5,4,3):
                       "*"xx$_                     # List of stars     (e.g. "*","*","*")
         " "x n*2-1-$_                             # Spaces to prepend (e.g. "  ")
                      ~                            # Concatenate.      (e.g. "  * * *")
     say                                           # Print

```
> 3 votes

# Answer
# PHP, ~~83~~ 79 bytes

```
for($p=str_pad;++$y<2*$n=$argn;)echo$p($p("
",1+$k=abs($n-$y)),4*$n-$k-2,"* ");

```

Run as pipe with `-nR` or try it online.

---

This is close to Kodos´ answer; but `str_pad` is shorter than `str_repeat` even when golfed.
And the `++` in the loop head saves some more.
> 3 votes

# Answer
# Powershell, ~~91~~ ~~89~~ ~~78~~ ~~68~~ ~~63~~ ~~52~~ 48 bytes

```
param($n)$n..1+1..$n|gu|%{' '*$_+'* '*(2*$n-$_)}

```

Test script:

```
$script = {
param($n)$n..1+1..$n|gu|%{' '*$_+'* '*(2*$n-$_)}
}

12,6,5,4,3,2,1 |%{
    $_
    . $script $_
}

```

Output (extra leading space):

```
12
            * * * * * * * * * * * *
           * * * * * * * * * * * * *
          * * * * * * * * * * * * * *
         * * * * * * * * * * * * * * *
        * * * * * * * * * * * * * * * *
       * * * * * * * * * * * * * * * * *
      * * * * * * * * * * * * * * * * * *
     * * * * * * * * * * * * * * * * * * *
    * * * * * * * * * * * * * * * * * * * *
   * * * * * * * * * * * * * * * * * * * * *
  * * * * * * * * * * * * * * * * * * * * * *
 * * * * * * * * * * * * * * * * * * * * * * *
  * * * * * * * * * * * * * * * * * * * * * *
   * * * * * * * * * * * * * * * * * * * * *
    * * * * * * * * * * * * * * * * * * * *
     * * * * * * * * * * * * * * * * * * *
      * * * * * * * * * * * * * * * * * *
       * * * * * * * * * * * * * * * * *
        * * * * * * * * * * * * * * * *
         * * * * * * * * * * * * * * *
          * * * * * * * * * * * * * *
           * * * * * * * * * * * * *
            * * * * * * * * * * * *
6
      * * * * * *
     * * * * * * *
    * * * * * * * *
   * * * * * * * * *
  * * * * * * * * * *
 * * * * * * * * * * *
  * * * * * * * * * *
   * * * * * * * * *
    * * * * * * * *
     * * * * * * *
      * * * * * *
5
     * * * * *
    * * * * * *
   * * * * * * *
  * * * * * * * *
 * * * * * * * * *
  * * * * * * * *
   * * * * * * *
    * * * * * *
     * * * * *
4
    * * * *
   * * * * *
  * * * * * *
 * * * * * * *
  * * * * * *
   * * * * *
    * * * *
3
   * * *
  * * * *
 * * * * *
  * * * *
   * * *
2
  * *
 * * *
  * *
1
 *

```

## Explanation:

```
param($n)           # define script parameter
$n..1+              # int range from n to 1 step -1; append
1..$n|              # int range from 1 to n
gu|                 # alias for Get-unique eliminates equal neighbors - here is 1,1 -> 1
%{                  # for each int from [n, n-1, n-2, ... 2, 1, 2, ... n-2, n-1, n]
    ' '*$_+         # string (' ' have repeated $_ times) append
    '* '*(2*$n-$_)  # string ('* ' have repeated 2*n-$_ times)
}

```
> 3 votes

# Answer
# Hexagony (linear), ~~128~~ ~~127~~ 126 bytes

Note that this is **not** Hexagony, just a (meta-)language Timwi supported in Esoteric IDE, so this is **not** eligible for the bounty.

However this can be converted to a Hexagony solution ~~(and I think it will be smaller than this solution) I may do that later. It takes more effort~~ I did it over here.

The initial  takes 3 bytes (`e2 9d a2`). Each newline takes 1 byte (`0a`).

```
❢?{2'*=(
A
if > 0
 "-"&}=&~}=&}=?&
 B
 if > 0
  }P0;'(
  goto B
 &{&'-{=-(
 C
 if > 0
  'P0;Q0;}(
  goto C
 {M8;{(
 goto A
@

```

No Try it online!. This **only** works in Esoteric IDE.

Annotated code:

```
❢?        # read input n
[n]
{2'*=(     # x = 2n-1
[x]
A
if > 0    # loop (x) from 2n-1 to 1
 "-      # a = x - n
 [a]
 "&}=&~}=&    # a = abs(a). Let K be this amount
 }=?&
 B
 if > 0       # print ' ' (a) times
  }P0;'(
  goto B
 &        # current cell = a (= K)
 {&       # a = n if K>0 else x
          # Note that K=abs(x-n). So if K==0 then x==n.
          # Therefore after this step a is always equal to n.
 '-{=-    # compute n-(K-n) = 2n+K
 (        # decrement, get 2n+K-1
 C
 if > 0   # print ' *' this many times
  'P0;Q0;}(
  goto C
 {M8;{    # print a newline, goto x
 (        # x -= 1
 goto A
@

```
> 3 votes

# Answer
# Ruby, 54 bytes

```
->n{(1-n..n-1).map{|j|i=j.abs;' '*i+'* '*(n*2+~i)}*$/}

```

lambda function takes n as argument and returns a string separated by newlines. (`$/` is a variable containing the default line separator.)

**in test program**

```
f=->n{(1-n..n-1).map{|j|i=j.abs;' '*i+'* '*(n*2+~i)}*$/}

puts f[gets.to_i]

```
> 2 votes

# Answer
# Javascript (ES6), 143 bytes

It's finally Christmas break (merry Christmas!), so I have some time for golfing.
And boy has it been a while - hence the large byte count.
Here goes:

```
c=[];a=a=>{for(i=0;i<a;i++){c.push(" ".repeat(a-i-1)+"* ".repeat(i+a-1)+"*")}for(j=c.length-2;j>-1;j--)c.push(c[j]);return a==1?"*":c.join`\n`}
console.log(a(3));
```
> 2 votes

# Answer
# Charly, 125 bytes

```
let i="".promptn()let o=0let j=0let w=write loop{w(" "*(i-1-o),"* "*(i+o))w("
")if j<i-1{o+=1}else{o-=1}if o<0{break}j+=1}

```

Charly GitHub Page: https://github.com/KCreate/charly-lang
> 2 votes

# Answer
# Python 2, 111 bytes

```
n=input()
l=range(n,2*n-1)
S=l+[2*n-1]+l[::-1]
W=range(1,n)
for w in W[::-1]+[0]+W:print" "*w+"* "*S[0];S=S[1:]

```

A boring, straightforward implementation (and a full program). Outputs a trailing whitespace at each line.

# Testcases:

```
1:
*

2:
 * *
* * *
 * *

3:
  * * *
 * * * *
* * * * *
 * * * *
  * * *

4:
   * * * *
  * * * * *
 * * * * * *
* * * * * * *
 * * * * * *
  * * * * *
   * * * *

```
> 2 votes

# Answer
# SmileBASIC, 74 bytes

```
FOR I=0TO N-1P
NEXT
FOR I=N-2TO.STEP-1P
NEXT
DEF P?" "*(N-I);"* "*(N+I)END

```

Adds a leading and trailing space.

These "hexagons" look horrible when the characters have the same width and height...
> 2 votes

# Answer
# Java, ~~157~~ ~~149~~ ~~129~~ ~~127~~ ~~93~~ 92 bytes

```
s->{for(int j=~--s,t;j++<s;System.out.println(repeat(" ",t=j<0?-j:j)+repeat("* ",s-~s-t)));}

```
* 8 bytes removed by Jonathan Frech.
* 56 bytes removed by Kevin Cruijssen.
* 1 byte removed by ceilingcat.

Try it online!
> 2 votes

# Answer
# Japt `-R`, ~~11~~ 10 bytes

```
Æ°çSi*Ãû ê

```

Try it (or use TIO to run multiple tests)

---

## Explanation

```
               :Implicit input of integer U
Æ              :Map the range [0,U)
 °             :  Postfix increment U
  ç            :  Repeat
   S           :    Space
    i*         :    Prepend asterisk
      Ã        :End map
       û       :Centre pad each string with spaces to the length of the longest string
         ê     :Palindromise
               :Implicitly join with newlines and output

```
> 2 votes

# Answer
# racket/scheme

```
(define (f n)
  (define (s t n)
    (if (= n 0) t (s (~a t "* ") (- n 1))))
  (define (h t p a i)
    (if (= i 0)
        (display t)
        (let ((x (~a t (make-string p #\space) (s "" a) "\n"))
              (q (if (> i n) (- p 1) (+ p 1)))
              (b (if (> i n) (+ a 1) (- a 1))))
          (h x q b (- i 1)))))
  (h "" (- n 1) n (- (* 2 n) 1)))

```

## testing:

```
(f 1)
*

(f 4)
   * * * *
  * * * * *
 * * * * * *
* * * * * * *
 * * * * * *
  * * * * *
   * * * *

```
> 2 votes

# Answer
# Vyxal `C`, 8 bytes

```
ʁ+×*vṄøm

```

Try it Online!

```
ʁ        # Range(n) (0...n-1)
 +       # Plus n (n...2n-1)
  ×*     # That many asterisks
    vṄ   # Join each by spaces
      øm # Palindromise
         # (C flag) Center and join by newlines

```
> 2 votes

# Answer
# tcl, 123

Based in Python 2 ...

```
gets stdin i;set n $i;while {$n+[incr i -1]} {puts [string repe " " [expr abs($i)]][string repe "* " [expr 2*$n+~abs($i)]]}

```
> 1 votes

# Answer
## PHP, 91 bytes

```
for($r=str_repeat;$j<$h=($n=$argv[1])*2-1;)echo$r(' ',$a=abs(++$j-$n)).$r('* ',$h-$a)."\n";

```

Run it in the command line like this:

```
php -d error_reporting=0 -r "for($r=str_repeat;$j<$h=($n=$argv[1])*2-1;)echo$r(' ',$a=abs(++$j-$n)).$r('* ',$h-$a).\"\n\";" "5"

```

Ungolfed:

```
<?php
// Store reference to str_repeat function for repeated uses
$r = str_repeat;

// Loop through each line until n*2+1 (the height of the hexagon)
for(;$j < $h = ($n = $argv[1]) * 2 - 1;) {

    // Add spacing to the beginning of each line.
    echo $r(' ', $a = abs(++$j - $n));

    // Add asterisks for each line
    echo $r('* ', $h - $a);

    // Add newline to the end of the line
    echo "\n";
}

```
> 1 votes

# Answer
# Python 3, 111 Bytes

```
d=int(input());i=' *';y=''
for x in range(d-1):y+=(' '*(d-x-1)+i*(d+x)+' '*(d-x)+'\n')
print(y+i*(2*d-1)+y[::-1])

```

Builds the top section, copies the reverse for the bottom and slots a line in the middle. Best approach I could think of.
> 1 votes

# Answer
## QBIC, ~~82~~ 76 bytes

Because you said please.

```
:~a=1|?A\[a-1|H=space$(a-b)┘G=A[a+b-2|G=G+@* `┘]Z=H+_tG|+H+@┘`+Z]?_fZ|+B+G+A

```

This can ~~definitely~~probably be golfed further.
> 1 votes

# Answer
# PostgreSQL, 86

I was gonna write a CJam answer, but I saw somebody did Postgres and I had to compete :)

```
\prompt n
select lpad('',@i)||repeat('* ',2*:n-1- @i)from generate_series(1-:n,:n-1)i;

```

Run it like this: `psql -Atf hex.sql dbname username` and type in the number (or append e.g. `<<<3` to the command).
> 1 votes

# Answer
# **Pyth - 60 57 50 bytes**

```
p*tQd*Q"* "VtQp*-Q+2Nd*h+QN"* ";VtQp*hNd*-*tQ2N"*

```

Try it online!

```
p                    print the next item (without trailing newline)
*tQd                multiply (input-1) by " "
*Q"*"                (implicit print) input times "* "
VtQ                 for all numbers 0 through (input-1) (as represented by N)
p                    print the next item (without trailing newline)
*-Q+2Nd              input-(N+2)  times " " (as represented by d)
*h+QN"*"            (implicit print) input+N+1  times "* "
;                    end for statement
V-Q1                 for all numbers 0 through input-1 (as represented by N)
p                    print the next item (without trailing newline)
*hNd                N+1 times " "
*-*tQ2N"*          (2*(input-1))-N   times "* " (implicit end string with EOF)
(implicit end of for loop with EOF)
(EOF == End of file)

```
> 1 votes

# Answer
# Groovy, ~~64~~ ~~63~~ ~~62~~ ~~58~~ 56 bytes

```
{n->(1-n..n-1)*.abs().any{println' '*it+'* '*(2*n+~it)}}

```

Example call:

```
{n->(1-n..n-1)*.abs().any{println' '*it+'* '*(2*n+~it)}}(4)

```

produces:

```
   * * * *
  * * * * *
 * * * * * *
* * * * * * *
 * * * * * *
  * * * * *
   * * * *

```
> 1 votes

# Answer
# Retina, 81 bytes

Assumes ISO 8859-1 encoding. All whitespace is significant.

```
\d+
$* $&$*a
^

.*
$0¶$0
m+`^(( *) (a+))¶\1
$1¶$2a$3¶$2a$3¶$1
m`^(a+)¶\1
$1
a
*

```

Try it online!

**Explanation**

The code consists of 6 regex replacements on the input.

```
\d+
$* $&$*a

```

This replaces the input (we'll call it **n**) with **n** spaces and **n** `a`s. I use `a` during most of program and replace it with `*` in the end because `*` is a reserved regex character and would need to be escaped if used directly.

```
^

```

(Note the space after `^`) This removes the first space in the text. The result is a line consisting of **n-1** spaces followed by **n** `a`s.

```
.*
$0¶$0

```

The line is duplicated.

```
m+`^(( *) (a+))¶\1
$1¶$2a$3¶$2a$3¶$1

```

The most complicated stage in the program. It will replace any line that consists of a non-zero number of spaces followed by some number of `a`s that *also* has an exact copy of itself following on the next line. It will be replaced with itself, a line consisting of 1 less space and 1 more `a`, that same line again, followed by the original line. More simply, it takes any two identical, directly adjacent lines and inserts two copies of a line with 1 less space and 1 more a in between them. This replacement will be made continually until the text stops changing, which happens when two lines consisting of only `a`s have been inserted.

```
m`^(a+)¶\1
$1

```

This removes the duplicate of the line consisting of all `a`s (since this line is the middle of the hexagon).

```
a
*

```

Finally, replace all instances of `a` with `* `.
> 1 votes

# Answer
# , 72 bytes

```
function(n,a=n-1)for(i in abs(a:-a))cat(rep(c('','*'),c(i,2*n-1-i)),'
')

```

Try it online!
> 1 votes

# Answer
# Kotlin, ~~113~~ 89 bytes

24 bytes saved thanks to mazzy

```
{n:Int->for(o in 1-n..n-1){val c=Math.abs(o)
println("".padEnd(c)+"* ".repeat(2*n-c-1))}}

```

Try it online!
> 1 votes

# Answer
# Sisi, 233 bytes

```
0set n3
1set i1
2set d1
3set o""
4set j n-i
5jumpif j7
6jump10
7set o o+" "
8set j j-1
9jump5
10jumpif o12
11set d0-1
12set j n+i
13set j j-1
14jumpif j16
15jump19
16set o o+"* "
17set j j-1
18jump14
19print o
20set i i+d
21jumpif i3

```

Try it online!

Note: because Sisi has no way of taking input, this meta consensus allows for input to be inserted into the source code. For this program, the value of *n* should be inserted directly after `n` on line 1. In the code above, the value *n* = 3 is used.

### Pseudocode

Because of Sisi's limitations, we have to generate and print one line at a time in order. So we run a loop in which `i` will go from `1` up to `n` and back down to `1`:

```
i = 1
d = 1
while i > 0
  construct string of (n-i) spaces
  append to that (n+i-1) copies of "* "
  print it
  if i = n
    d = -1
  end
  i = i + d
repeat

```

### Ungolfed version

```
10 set n 3
20 set i 1
30 set d 1

100 set o ""
110 set j n-i
120 jumpif j 140
130 jump 200
140 set o o+" "
150 set j j-1
160 jump 120

200 jumpif o 300
210 set d 0-1

300 set j n+i
310 set j j-1
320 jumpif j 340
330 jump 400
340 set o o+"* "
350 set j j-1
360 jump 320

400 print o
410 set i i+d
420 jumpif i 100

```
> 1 votes

# Answer
# QBasic, 76 bytes

```
INPUT n
FOR i=-n+1TO n-1
s=ABS(i)
?SPC(s)
FOR j=2TO 2*n-s
?"* ";
NEXT
?
NEXT

```

(This requires real QBasic, in which `?SPC(s)` is expanded to `PRINT SPC(s);`, unlike QB64, in which it becomes `PRINT SPC(s)`.)

Similar approach to my Sisi answer, except QBasic has `ABS` and so it's more efficient to run a `FOR` loop from `-n+1` to `n-1`.
> 1 votes

# Answer
# K (oK), ~~44~~ ~~38~~ 34 bytes

**Solution:**

```
{(-a+3*x)$(2*x+a,:1_|a:!x)#\:"* "}

```

Try it online!

**Example:**

```
{(-a+3*x)$(2*x+a,:1_|a:!x)#\:"* "}4
("    * * * * "
"   * * * * * "
"  * * * * * * "
" * * * * * * * "
"  * * * * * * "
"   * * * * * "
"    * * * * ")

```

**Explanation:**

Create lists of `*` of the desired length and then left-pads them the required amount.

```
{(-a+3*x)$(2*x+a,:1_|a:!x)#\:"* "} / the solution
{                                } / lambda taking implicit argument x, e.g. 4
                             "* "  / the string "* "
                          #\:      / take (#), each-left (\:)
          (              )         / do this together
                       !x          / til x, range 0..x, e.g. 0 1 2 3
                     a:            / assign to variable a
                    |              / reverse it, e.g. 3 2 1 0
                  1_               / drop the first, e.g. 2 1 0
               a,:                 / append that to a, e.g. 0 1 2 3 2 1 0
             x+                    / add x, e.g. 4 5 6 7 6 5 4
           2*                      / multiply by 2, e.g. 8 10 12 14 12 10 8
         $                         / pad (negative means left-pad)
 (      )                          / do this together
     3*x                           / x multiply by 3, e.g 12
   a+                              / add a, e.g. 12 13 14 15 14 13 12
  -                                / negate, e.g. -12 -13 -14 -15 -14 -13 -12

```

**Extra:**

There is a leading space, this can be removed at the cost of 1 extra byte:

```
{(1-a+3*x)$(2*x+a,:1_|a:!x)#\:"* "}

```

**Edits:**

* -1 byte thanks to ngn (reuse `a` rather than defining b)
* -3 bytes by returning list of strings rather than printing to STDOUT
> 1 votes

# Answer
# C# (.NET Core), ~~106~~ 105 bytes

Private method, takes the size as input and returns a string containing the hexagon.

*Edit: Holy cow. I stared at this single-for-loop version for so long, finally figured out how to make it one byte shorter than the double-for-loop version!*

```
string h(int s){var o="";for(int q=2*s,y=q;q*q>++y;o+=y%q>y/q-s&y%q>s-y/q?"* ":y%q<1?"\n":" ");return o;}

```

Try it online!

`s` is the size, `x` and `y` represent "coordinates" in the output string (position on the line & current line). In an earlier version I wrote this nice little passage: `h>e?x>h-e:x`. I found it very fitting, but unfortunately had to scrap it when optimizing my code.

I was initially worried about handling `size = 1`, but it turns out my code worked just fine. Phew!

Suggestions are welcome! :)

---

**Previous 106 byte version** with two for-loops: Try it online!
> 1 votes

# Answer
# ABAP, 172 bytes

```
FORM h USING s.DO s * 2 - 1 TIMES.WRITE /''.DATA(y) = sy-index.DO s * 2 - 1 TIMES.IF sy-index > s - y AND sy-index > y - s.WRITE'*'.ELSE.WRITE ``.ENDIF.ENDDO.ENDDO.ENDFORM.

```

For ABAP I am pretty impressed by how short it turned out to be. I suppose having written the C# answer beforehand was helpful, but merely from an "understanding what to do" perspective, since the languages are so vastly different. There *might* be potential to save some bytes by using a single `do`-loop instead, but that would require a few calculations which in turn would have so much whitespace in them that it's likely going to be worse.

### Test Cases

Size = 1, 5, 13
Has some leading and trailing whitespace thanks to how `WRITE` works, but luckily it's not an issue. In fact this saves us *a whole byte* with `WRITE'*'` including an implicit trailing space. *Wow!*

### Explanation (also on Pastebin with syntax highlighting)

```
FORM h USING s. "ABAP subroutine
  DO s * 2 - 1 TIMES. "basically a simple for loop; loop over each line top to bottom
    WRITE /''. "Newline. No effect on first line for some reason. *shrug*
    "Also, WRITE /. works, too, but outputs TWO line feeds here. Ugh.
    DATA(y) = sy-index. "Save current index in loop to Y
    DO s * 2 - 1 TIMES. "Loop for each character left to right
      IF sy-index > s - y      "Check if we need to write a '*'
         AND sy-index > y - s. "by subtracting size from current line and vice versa
        WRITE'*'. "Print the '*'. WRITE has an implicit space after the output!
      ELSE.
        WRITE ``. "Empty literal. CANNOT be '' or ' ' because then we don't get any output.
      ENDIF.      "Yeah, WRITE is odd. Don't ask.
    ENDDO.        "End of inner loop
  ENDDO.          "End of outer loop
ENDFORM.          "End of subroutine

```
> 1 votes

# Answer
# VBA (Excel), 77 bytes

Using Immediate Window and `A1` as input.

```
a=[a1]-1:for x=-a to a:y=Abs(x):?space(y)StrConv(String(1+a*2-y,"*"),64):next

```

And for fun.

```
    a=[A1
   ]-1:For
   x=-a To
 a:y=Abs(x):
?Space(y)StrC
 onv(String(
  1+a*2-y,"
   *"),64)
    :Next

```
> 1 votes

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

```
f=(n,m=n+--n)=>[...Array(m)].map((_,i)=>m-Math.abs(i-n)).map(e=>' '.repeat(m-e)+'* '.repeat(e)).join`
`

```

Try it online!
> 1 votes

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

```
f=(n,i=n,w=" ".repeat(--i)+"* ".repeat(n++))=>w+(i?`
${f(n,i)}
`+w:"")

```

Try it online!

With one trailing space at the end of each line.
> 1 votes

# Answer
# APL(NARS) 60 chars, 120 bytes

```
{1≥k←⍵:'*'⋄⊃{(' '⍴⍨k-⍵+1),((2×k+⍵)⍴'* ')}¨(0..⍵-1),(⍵-2)..0}

```

test

```
  f←{1≥k←⍵:'*'⋄⊃{(' '⍴⍨k-⍵+1),((2×k+⍵)⍴'* ')}¨(0..⍵-1),(⍵-2)..0}
  f 1
*
  f 2
 * *
* * *
 * *
  f 3
  * * *
 * * * *
* * * * *
 * * * *
  * * *

```

the only difficult is that (2×7)⍴'\* ' would mean "repeat '\* ' until you write the 14th character" so that would repeat '\* ' 7 times...
> 1 votes

# Answer
# F#, ~~101~~ 98 Bytes

```
let r=String.replicate
let h n=for i in[0..n-1]@[n-2..-1..0]do(r(n-i)" ")+r(n+i)"* "|>printfn"%s"

```

Ungolfed:

```
let replicate = String.replicate
let ungolfed_hexagon n =
  for i in [0..n-1]@[n-2..-1..0] do // For each hexagon line index [0 .. n-1 .. 0]
      (replicate (n-i) " ")  // Space padding
    + (replicate (n+i) "* ") // Hexagon stars
    |> printfn "%s"

```

Usage: Call `h n`, where n is the hexagon size, and it will print the hexagon.
> 0 votes

# Answer
# C, ~~88~~, 83

This solution uses just one `for loop` unlike the other C solution using 2 `for loops` because of this I suspect it can be golfed much further, but it's 4:30am so I'll attempt that tomorrow.

`y,w;f(s){for(w=++s*2-1;y++<w*w-w*2;)printf(" %c",y%w?y%w-1<=abs(s-y/w-2)?0:42:13);}`

---

Revision history:

2) `y,w;f(s){for(w=++s*2-1;y++<w*w-w*2;)printf(" %c",y%w?y%w-1<=abs(s-y/w-2)?0:42:13);}`

1) `y,w;f(s){for(w=++s*2-1;y++<w*w-w*2;)printf("%s",y%w?y%w-1<=abs(s-y/w-2)?" ":"* ":"\n");}`
> 0 votes

# Answer
# Common Lisp, ~~97~~ 96 bytes

```
(lambda(x)(dotimes(i(1-(* x 2)))(format t"~v@t~v{* ~}~%"(set'c(abs(1+(- i x))))(-(* x 2)1 c)1)))

```

needed to figure out formula for:

a) how many spaces before text: `|1+x-i| ~~ (abs(1+(- i x)`

b) how many characters: `2x-1-|1+x-i| ~~ (-(* x 2)1 c)`

idea for using `dotimes` and `abs` for looping from Strigoides's answer here

Ideas for improvement are welcomed
> 0 votes

# Answer
# k, 51 bytes

```
`0:{x,|-1_x}@|{m:-1+2*x;{(x#" "),(2*m-x)#"* "}'!x}@

```

Explanation:

```
              {                                  }@ / function(x)
               m:-1+2*x;                            / m = (2*x)-1
                        {                    }'!x   / for x in range(0, x):
                         (x#" "),                   /   x*" " +
                                 (2*m-x)#"* "       /           m-x*"* "
             |                                      / reversed()
   {       }@                                       / function(x)
    x,                                              / x +
      |-1_x                                         /     reversed(x[1:])
`0:                                                 / print array line by line

```
> 0 votes

# Answer
## Perl 5 with `-na -M5.010`, 44 bytes

```
say$"x abs,"* "x(2*"@F"-1-abs)for 1-$_..$_-1

```

Try it online!

Uses the same range as a few of the other answers.
> 0 votes

# Answer
# Jelly, ~~16~~ 15 bytes

```
ḶU⁶ẋż+Ḷ⁾ *ẋƲŒḄY

```

Try it online!

---

Now beats V!
> 0 votes

# Answer
# Charcoal, ~~33~~ ~~31~~ 17 bytes

```
≔×*ＮθＦθ«Ｐ^θ→→»‖Ｂ↓

```

-14 bytes thanks to *@Neil*.

Try it online (verbose) or Try it online (pure).

**Explanation:**

Put a string in a variable consisting of the `input` amount of `*`:

```
Assign(Times("*", InputNumber()), q);
≔×*Ｎθ

```

Loop the `input` amount of times by doing a for-each over the characters of this string:

```
For(q){ ... }
Ｆθ« ... »

```

Print the string in both a down-left and down-right direction, without moving the cursor position:

```
Multiprint(:^, q);
Ｐ^θ

```

And move two positions to the right at the end of every iteration:

```
Move(:Right); Move(:Right);
→→

```

After the loop, reflect everything downwards with one line overlap:

```
ReflectButterfly(:Down);
‖Ｂ↓

```
> 0 votes

# Answer
# Pyth, 23 bytes

```
jm.[*4Q*"* "+Qd\ +PUQ_U

```

Try it online

Explanation:

```
jm.[*4Q*"* "+Qd\ +PUQ_UQ   Trailing Q inferred, Q=eval(input())
                     _UQ   Reversed 0-range, yields [Q-1, Q-2, ... , 1, 0]
                  PUQ      Tailless 0-range, yields [0, 1, ... , Q-3, Q-2]
                 +         Concatenate them, yields [0 ... Q-1 ... 0]
 m                         Map d in the above to:
            +Qd              Q+d
       *"* "                 Repeat *_ that many times
  .[*4Q        \             Centre pad the above to length 4*Q
j                          Join on newlines, implicit print

```
> 0 votes

# Answer
# Python 3, 117 113 bytes

```
def h(s):n="\n".join;t=[" "*(s-i-1)+"* "*(s+i)for i in range(s-1)];return"%s\n%s\n%s"%(n(t),"* "*(2*s-1),n(t[::-1])

```

Generates the top, then the middle, then reverses the top to generate the bottom half.
> 0 votes

# Answer
# JavaScript (Node.js), ~~121~~ 99 bytes

```
i=>[...t=[...Array(i)].map((_,z)=>''.padEnd(i-z)+'* '.repeat(z+i)),...t.reverse().slice(1)].join`
`

```

Try it online!
> 0 votes

# Answer
# C (gcc), ~~164~~ ~~125~~ ~~124~~ 123 bytes

```
i,h;main(z,b)int**b;{z=atoi(b[1]);for(i=z--+z;i--;puts(""))for(h=z<i?z-i+z:i,printf("%*s",z-h,""),h-=~z;h--;)printf("* ");}

```

Try it online!
> 0 votes

# Answer
# Excel, 63 bytes

```
=LET(r,2*A1-1,x,ABS(A1-SEQUENCE(r)),REPT(" ",x)&REPT("* ",r-x))

```

Link to Spreadsheet

The above spills the results to multiple cells. The 75 byte formula for a single cells answer is below.

```
=LET(r,2*A1-1,x,ABS(A1-SEQUENCE(r)),CONCAT(REPT(" ",x)&REPT("* ",r-x)&"
"))

```
> 0 votes

# Answer
# Knight, ~~58~~ 57 bytes

```
;=n+~1P;=i~1W>+1*2n=i+1iO+*' '=xI>=x-n iFx~x*'* '+1-*2n x

```

Try It Online!
> 0 votes

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


title: Unfolding the Hexagony source code

text:
# Question
Title: Unfolding the Hexagony source code
### Introduction

If you're not familiar with Hexagony, it's an esoteric language created by Martin Büttner. The thing is that this language accepts multiple forms for the program. The following programs are all equivalent:

```
abcdefg

```

and

```
 a b
c d e
 f g

```

So basically, the code has been rolled up into a regular hexagon. But note that adding a new command to the code, which would be `abcdefgh` would result into the following program:

```
  a b c
 d e f g
h . . . .
 . . . .
  . . .

```

As you can see, the first step is rolling up the code into a hexagon, and after that the hexagon is filled in with no-ops (`.`) to the next centered hexagonal number.

Your task is simple, when given a string (the source code), output the full hexagon source code.

### The rules

* You may provide a program or a function.
* Leading whitespace is allowed, but only when the hexagon doesn't get out of shape
* Trailing whitespace is allowed.
* Note that whitespace in the program **are ignored**. So `a b c` is equal to `abc`
* Only the printable ASCII characters (`32 - 126`) are used, so only the regular `Space` character is ignored.
* Assume that the length of the string is greater than 0.
* This is , so the submission with the least amount of bytes wins!

### Test cases

```
Input: ?({{&2'2':{):!/)'*/

Output:
  ? ( {
 { & 2 '
2 ' : { )
 : ! / )
  ' * /

Input: H;e;l;d;*;r;o;Wl;;o;*433;@.>;23<\4;*/

Output:
   H ; e ;
  l ; d ; *
 ; r ; o ; W
l ; ; o ; * 4
 3 3 ; @ . >
  ; 2 3 < \
   4 ; * /

Input: .?'.) .@@/'/ .!.>   +=(<.!)}    (  $>( <%

Output:
   . ? ' .
  ) . @ @ /
 ' / . ! . >
+ = ( < . ! )
 } ( $ > ( <
  % . . . .
   . . . .

```

# Answer
# Pyth, ~~57~~ ~~54~~ ~~50~~ ~~49~~ ~~48~~ 46

```
V+UJfgh*6sUTlK-zd1_UtJ+*d-JNjd:.[K\.^TJZ=+Z+JN

```

Test Suite

Prints a leading space on each line.

This version requires a proof that **10^n \>= 3n(n - 1) + 1** for all **n \>= 1**. Thanks to ANerdI and ErickWong for providing proofs.

Following these inequalities: **10^n \> (1+3)^n = 1 + 3n + 9n(n - 1) + ... \> 3n(n - 1) + 1** one can easily see that this is correct for **n \>= 2**. Examining the **n = 1** case is rather trivial, giving **10 \> 1**.

Alternatively, taking the derivatives of these equations twice shows that **10^n** has a greater second derivative for all **n \>= 1**, which can then be cascaded down to the first derivatives, and finally to the original equations.

### Explanation

```
              ##  Implicit: z=input(); Z=0
Jf...1        ##  Save to J the side length of the hexagon the code fills up
              ##  by finding the first number such that:
gh*6sUT       ##  the the T'th hexagonal number is greater than...
              ##  Computes 6 * T'th triangular number (by using sum 1..T-1) + 1
    lK-zd     ##  ...the length of the code without spaces (also save the string value to K)
V+UJ_UtJ      ##  For loop over N = [0, 1, ..., J-1, ..., 0]:
+*d-JN        ##  append J - N spaces to the front of the line
jd            ##  riffle the result of the next operation with spaces
:.[K\.yJ      ##  slice the string given by K padded to be the length of the Jth hexagon
              ##  number with noops
Z=+Z+JN       ##  from Z to Z + J + N, then set Z to be Z + J + N

```
> 13 votes

# Answer
## Hexagony, 271 bytes

I present to you, the first 3% of a Hexagony self-interpreter...

```
|./...\..._..>}{<$}=<;>'<..../;<_'\{*46\..8._~;/;{{;<..|M..'{.>{{=.<.).|.."~....._.>(=</.\=\'$/}{<}.\../>../..._>../_....@/{$|....>...</..~\.>,<$/'";{}({/>-'(<\=&\><${~-"~<$)<....'.>=&'*){=&')&}\'\'2"'23}}_}&<_3.>.'*)'-<>{=/{\*={(&)'){\$<....={\>}}}\&32'-<=._.)}=)+'_+'&<

```

Try it online! You can also run it on itself, but it will take about 5-10 seconds.

In principle this might fit into side-length 9 (for a score of 217 or less), because this uses only 201 commands, and the ungolfed version I wrote first (on side-length 30) needed only 178 commands. However, I'm pretty sure it would take forever to actually make everything fit, so I'm not sure whether I'll actually attempt it.

It should also be possible to golf this a bit in size 10 by avoiding the use of the last one or two rows, such that the trailing no-ops can be omitted, but that would require a substantial rewrite, as one of the first path joins makes use of the bottom left corner.

### Explanation

Let's start by unfolding the code and annotating the control flow paths:

That's still quite messy, so here is the same diagram for the "ungolfed" code which I wrote first (in fact, this is side-length 20 and originally I wrote the code on side-length 30 but that was so sparse that it wouldn't improve the readability at all, so I compacted it just a little bit to make the size a bit more reasonable):

Click for larger version.

The colours are exactly the same apart from a few very minor details, the non-control-flow commands are also exactly the same. So I'll be explaining how this works based on the ungolfed version, and if you really want to know how the golfed one works, you can check which parts there correspond to which in the larger hexagon. (The only catch is that the golfed code starts with a mirror so that the actual code begins in the right corner going left.)

The basic algorithm is almost identical to my CJam answer. There are two differences:

* Instead of solving the centred hexagonal number equation, I just compute consecutive centred hexagonal numbers until one is equal to or larger than the length of the input. This is because Hexagony does not have a simple way to compute a square root.
* Instead of padding the input with no-ops right away, I check later if I've already exhausted the commands in the input and print a `.` instead if I have.

That means the basic idea boils down to:

* Read and store input string while computing its length.
* Find the smallest side-length `N` (and corresponding centred hexagonal number `hex(N)`) which can hold the entire input.
* Compute the diameter `2N-1`.
* For each line, compute the indent and the number of cells (which sum to `2N-1`). Print the indent, print the cells (using `.` if the input is already exhausted), print a linefeed.

Note that there are only no-ops so the actual code starts in the left corner (the `$`, which jumps over the `>`, so the we *really* start on the `,` in the dark grey path).

Here is the initial memory grid:

So the memory pointer starts out on edge labelled *input*, pointing North. `,` reads a byte from STDIN or a `-1` if we've hit EOF into that edge. Hence, the `<` right after is a conditional for whether we've read all the input. Let's remain in the input loop for now. The next code we execute is

```
{&32'-

```

This writes a 32 into the edge labelled *space*, and then subtracts it from the input value in the edge labelled *diff*. Note that this can never be negative because we're guaranteed that the input contains only printable ASCII. It will be zero when the input was a space. (As Timwi points out, this would still work if the input could contain linefeeds or tabs, but it would also strip out all other unprintable characters with character codes less than 32.) In that case, the `<` deflects the instruction pointer (IP) left and the light grey path is taken. That path simply resets the position of the MP with `{=` and then reads the next character - thus, spaces are skipped. Otherwise, if the character was not a space, we execute

```
=}}})&'+'+)=}

```

This first moves around the hexagon through the *length* edge until its opposite the *diff* edge, with `=}}}`. Then it copies the value from opposite the *length* edge into the *length* edge, and increments it with `)&'+'+)`. We'll see in a second why this makes sense. Finally, we move the a new edge with `=}`:

(The particular edge values are from the last test case given in the challenge.) At this point, the loop repeats, but with everything shifted one hexagon northeast. So after reading another character, we get this:

Now you can see that we're gradually writing the input (minus spaces) along the northeast diagonal, with the characters on every other edge, and the length up to that character being stored parallel to the edge labelled *length*.

When we're done with the input loop, memory will look like this (where I've already labelled a few new edges for the next part):

The `%` is the last character we read, the `29` is the number of non-space characters we read. Now we want to find the side-length of the hexagon. First, there is some linear initialisation code in the dark green/grey path:

```
=&''3{

```

Here, `=&` copies the length (29 in our example) into the edge labelled *length*. Then `''3` moves to the edge labelled *3* and sets its value to `3` (which we just need as a constant in the computation). Finally `{` moves to the edge labelled *N(N-1)*.

Now we enter the blue loop. This loop increments `N` (stored in the cell labelled *N*) then computes its centered hexagonal number and subtracts it from the input length. The linear code which does that is:

```
{)')&({=*'*)'-

```

Here, `{)` moves to and increments *N*. `')&(` moves to edge labelled *N-1*, copies `N` there and decrements it. `{=*` computes their product in *N(N-1)*. `'*)` multiplies that by the constant `3` and increments the result in the edge labelled *hex(N)*. As expected, this is the Nth centered hexagonal number. Finally `'-` computes the difference between that and the input length. If the result is positive, the side-length is not large enough yet, and the loop repeats (where `}}` move the MP back to the edge labelled *N(N-1)*).

Once the side-length is large enough, the difference will be zero or negative and we get this:

First off, there is now the really long linear green path which does some necessary initialisation for the output loop:

```
{=&}}}32'"2'=&'*){=&')&}}

```

The `{=&` starts by copying the result in the *diff* edge into the *length* edge, because we later need something non-positive there. `}}}32` writes a 32 into the edge labelled *space*. `'"2` writes a constant 2 into the unlabelled edge above *diff*. `'=&` copies `N-1` into the second edge with the same label. `'*)` multiplies it by 2 and increments it so that we get the correct value in the edge labelled *2N-1* at the top. This is the diameter of the hexagon. `{=&')&` copies the diameter into the other edge labelled *2N-1*. Finally `}}` moves back to the edge labelled *2N-1* at the top.

Let's relabel the edges:

The edge we're currently on (which still holds the diameter of the hexagon) will be used to iterate over the lines of the output. The edge labelled *indent* will compute how many spaces are needed on the current line. The edge labelled *cells* will be used to iterate over the number of cells in the current line.

We're now on the pink path which computes *indent*. `('-` decrements the *lines* iterator and subtracts it from *N-1* (into the *indent* edge). The short blue/grey branch in the code simply computes the modulus of the result (`~` negates the value if it's negative or zero, and nothing happens if it's positive). The rest of the pink path is `"-~{` which subtracts the *indent* from the diameter into the *cells* edge and then moves back to the *indent* edge.

The dirty yellow path now prints the indentation. The loop contents are really just

```
'";{}(

```

Where `'"` moves to the *space* edge, `;` prints it, `{}` moves back to *indent* and `(` decrements it.

When we're done with that the (second) dark grey path searches for next character to print. The `=}` moves in position (which means, onto the *cells* edge, pointing South). Then we have a very tight loop of `{}` which simply moves down two edges in the South-West direction, until we hit the end of the stored string:

Notice that I've relabelled one edge there *EOF?*. Once we've processed this character, we'll make that edge negative, so that the `{}` loop will terminate here instead of the next iteration:

In the code, we're at the end of the dark grey path, where `'` moves back one step onto the input character. If the situation is one of the last two diagrams (i.e. there's still a character from the input we haven't printed yet), then we're taking the green path (the bottom one, for people who aren't good with green and blue). That one is fairly simple: `;` prints the character itself. `'` moves to the corresponding *space* edge which still holds a 32 from earlier and `;` prints that space. Then `{~` makes our *EOF?* negative for the next iteration, `'` moves a back a step so that we can return to the North-West end of the string with another tight `}{` loop. Which ends on the *length* cell (the non-positive one below *hex(N)*. Finally `}` moves back to the *cells* edge.

If we've already exhausted the input though, then the loop which searches for EOF? will actually terminate here:

In that case `'` moves onto the *length* cell, and we're taking the light blue (top) path instead, which prints a no-op. The code in this branch is linear:

```
{*46;{{;{{=

```

The `{*46;` writes a 46 into the edge labelled *no-op* and prints it (i.e. a period). Then `{{;` moves to the *space* edge and prints that. The `{{=` moves back to the *cells* edge for the next iteration.

At this point the paths join back together and `(` decrements the *cells* edge. If the iterator is not zero yet, we will take the light grey path, which simply reverses the MP's direction with `=` and then goes looking for the next character to print.

Otherwise, we've reached the end of the current line, and the IP will take the purple path instead. This is what the memory grid looks like at that point:

The purple path contains this:

```
=M8;~'"=

```

The `=` reverses the direction of the MP again. `M8` sets the sets its value to `778` (because the character code of `M` is `77` and digits will append themselves to the current value). This happens to be `10 (mod 256)`, so when we print it with `;`, we get a linefeed. Then `~` makes the edge negative again, `'"` moves back to the *lines* edge and `=` reverses the MP once more.

Now if the *lines* edge is zero, we're done. The IP will take the (very short) red path, where `@` terminates the program. Otherwise, we continue on the purple path which loops back into the pink one, to print another line.

---

*Control flow diagrams created with Timwi's HexagonyColorer. Memory diagrams created with the visual debugger in his Esoteric IDE.*
> 92 votes

# Answer
## CJam, ~~56~~ ~~52~~ ~~50~~ 48 bytes

My first thought was, "hey I already have code for this!" But then I couldn't be bothered to pull the necessary pieces together from the Ruby code, especially because they didn't seem very suitable to being golfed. So I tried something else in CJam instead...

```
lS-{_,4*(3/mq:D1%}{'.+}wD{D(2/-z_S*D@-@/(S*N@s}/

```

Test it here.

### Explanation

A bit of maths about centred hexagonal numbers first. If the regular hexagon has side length `N`, then it will contain `3N(N-1)+1` cells, which has to equal the source code length `k`. We can solve that `N` because it's a simple quadratic equation:

```
N = 1/2 ± √(1/4 + (k-1)/3)

```

We can ignore the negative root, because that gives a negative N. For this to have a solution, we need the square root be a half-integer. Or in other words, `√(1 + 4(k-1)/3) = √((4k-1)/3)` needs to be an integer (luckily, this integer happens to be the diameter `D = 2N-1` of the hexagon, which we'll need anyway). So we can repeatedly add a single `.` until that condition is met.

The rest is a simple loop which lays out the hexagon. A useful observation for this part is that the spaces in the indentation plus the non-spaces in the code in each line add up to the diameter.

```
lS-     e# Read input and remove spaces.
{       e# While the first block yields something truthy, evaluate the second...
  _,    e#   Duplicate the code and get its length k.
  4*(   e#   Compute 4k-1.
  3/    e#   Divide by 3.
  mq    e#   Take the square root.
  :D    e#   Store this in D, just in case we're done, because when we are, this happens
        e#   to be the diameter of the hexagon.
  1%    e#   Take modulo 1. This is 0 for integers, and non-zero for non-integers.
}{      e# ...
  '.+   e#   Append a no-op to the source code.
}w
D{      e# For every i from 0 to D-1...
  D(2/  e#   Compute (D-1)/2 = N, the side length.
  -z    e#   Subtract that from the current i and get its modulus. That's the size of the
        e#   indentation on this line.
  _S*   e#   Duplicate and get a string with that many spaces.
  D@-   e#   Subtract the other copy from D to get the number of characters of code
        e#   in the current line.
  @/    e#   Pull up the source code and split into chunks of this size.
  (S*   e#   Pull off the first chunk and riffle it with spaces.
  N     e#   Push a linefeed character.
  @s    e#   Pull up the remaining chunks and join them back into a single string.
}/

```

It turns out that we don't need to use double arithmetic at all (except for the square root). Due to the multiplication by 4, there are no collisions when dividing by 3, and the desired `k` will be the first to yield an integer square root.
> 18 votes

# Answer
## Perl, ~~203~~ ~~200~~ 198

*includes + 1 for `-p`*

```
s/\s//g;{($l=y///c)>($h=1+3*++$n*($n-1))&&redo}$s=$_.'.'x($h-$l);for($a=$n;$a<($d=2*$n-1);$a++){$s=~s/.{$a}/$&\n/,$s=reverse($s)for 0..1}$_=join$/,map{(' 'x abs($n-$i++-1)).$_}$s=~/\S+/g;s/\S/ $&/g

```

*run as: `echo abc | perl -p file.pl`*

A very naive approach:

```
#!/usr/bin/perl -p

s/\s//g;                            # ignore spaces and EOL etc.
{                                   # find the smallest hex number:
    ($l=y///c)                      # calc string length
    > ($h=1+3*++$n*($n-1))          #
    && redo                         # (should use 'and', but..)
}

$s = $_                             # save $_ as it is used in the nested for
   . '.' x ($h-$l);                 # append dots to fill hexagon

for ( $a = $n; $a < ($d=2*$n-1); $a++ )
{
        $s=~s/.{$a}/$&\n/,          # split lines
        $s=reverse($s)              # mirror
    for 0..1                        # twice
}

$_ = join$/,                        # join using newline
map {                               # iterate the lines
    (' 'x abs($n-$i++-1)) .$_       # prepend padding
} $s=~/\S+/g;                       # match lines

s/\S/ $&/g                          # prepend spaces to characters
                                    # -p takes care of printing $_

```

---

* *update 200* save a byte moving variable assignment, and another 2 by omitting final `;`; code itself under 200 bytes now!
* *update 198* save 2 bytes by using `$s=~/\S+/g` instead of `split/\n/,$s`
> 8 votes

# Answer
# JavaScript (ES6), 162 ~~172~~

Anonymous function

The hexagon size is found resolving the equation from wikipedia

```
3*n*(n-1)-1 = l

```

The solving formula is basically

```
n = ceil(3+sqrt(12*l-3))/6)

```

With some algebra and some approximation (thx to @user18655 too) it becomes

```
n = trunc(sqrt(l/3-1/12)+1.4999....)

```

```
s=>eval("s=s.match(/\\S/g);m=n=Math.sqrt(s.length/3-1/12)+1.49999|0;p=o=``;for(i=n+n;--i;i>n?++m:--m)for(o+=`\n`+` `.repeat(n+n-m),j=m;j--;o+=` `)o+=s[p++]||`.`")

```

More readable

```
s=>{
  s=s.match(/\S/g);
  m=n=Math.sqrt(s.length/3-1/12)+1.49999;
  p=o='';
  for(i=n+n; --i; i>n?++m:--m)
    for(o += '\n'+' '.repeat(n+n-m), j=m; j--; o += ' ')
      o+=s[p++]||'.';
  return o
}

```

**Test snippet (better full page - running time ~ 1 minute)**

```
f=s=>eval("s=s.match(/\\S/g);m=n=Math.sqrt(s.length/3-1/12)+1.49999|0;p=o=``;for(i=n+n;--i;i>n?++m:--m)for(o+=`\n`+` `.repeat(n+n-m),j=m;j--;o+=` `)o+=s[p++]||`.`")

t=0;
r='0';
(T=_=>t++<816?(O.innerHTML=f(r=t%10+r),setTimeout(T,20)):0)()
```

```
pre { font-size: 66% }
```

```
<pre id=O></pre>
```
> 7 votes

# Answer
# Pyth, ~~52~~ 51 bytes

```
Jfgh**3TtTl=H-zd1=+H*\.*lHTV+UJt_UJAcH]+JN+*-JNdjdG

```

Try it online. Test suite.

Each line has one extra leading space, as permitted by the OP.

### Explanation

```
 f              1          |   find first number n for which
             -zd           |           remove spaces from input
           =H              |         put result in H
          l                |       length of input without spaces
  g                        |     is less than or equal to
   h**3TtT                 |       nth centered hexagonal number
J                          | put result (hexagon side length) in J
                           |
      *lHT                 |      ten times length of input without spaces
   *\.                     |   that amount of dots
=+H                        | append to H
                           |
  UJ                       |    numbers 0 up to side length - 1
 +  t_UJ                   |   add numbers side length - 2 down to 0
V                          | loop over result
            +JN            |       current loop number + side length
         cH]               |     split to two parts at that position
        A                  |   put parts to G and H
                 -JN       |       side length - current loop number - 1
                *   d      |     that many spaces
                     jdG   |     join code on the line (G) by spaces
               +           |   concatenate parts and print

```
> 5 votes

# Answer
## Retina, 161 bytes

*Thanks to FryAmTheEggman for saving 2 bytes.*

This answer is non-competing. Retina has seen a few updates since this challenge, and I'm pretty sure I'm using some of the newer features (although I haven't checked).

Byte count assumes ISO 8859-1 encoding. The first line contains a single space. Note that most of the `·` are actually centre dots (0xB7).

```

^
$._$*·¶
^·¶
¶
((^·|\2·)*)·\1{5}·+
$2·
^·*
$.&$* ·$&$&$.&$*
M!&m`(?<=(?= *(·)+)^.*)(?<-1>.)+(?(1)!)|^.+$
+m`^( *·+)· *¶(?=\1)
$&
·
 ·
O$`(·)|\S
$1
·
.
G-2`

```

Try it online!

Well...

### Explanation

It seems easiest to build the layout first using just a single character (`·` in this case) and then fill the resulting layout with the input characters. The main reasons for this are that using a single character lets me make use of backreferences and character repetition, where laying out the input directly would require expensive balancing groups.

```

```

Although it doesn't look like much, this first stages removes spaces from the input.

```
^
$._$*·¶

```

We start by prepending an additional line which contains `M` centre dots, where `M` is the length of the input (after removing spaces).

```
^·¶
¶

```

If the input was a single character, we remove that centre dot again. This is an unfortunate special case that isn't covered by the next stage.

```
((^·|\2·)*)·\1{5}·+
$2·

```

This computes the required side length `N` minus 1. Here is how that works: centred hexagonal numbers are of the form `3*N*(N-1) + 1`. Since triangular numbers are `N*(N-1)/2`, that means hexagonal numbers are six times a triangular number plus 1. That's convenient because matching triangular numbers (which are really just `1 + 2 + 3 + ... + N`) in a regex is fairly easy with forward references. The `(^·|\2·)*` matches the largest triangular number it can. As a nice bonus, `$2` will then hold the index of this triangular number. To multiply it by 6, we capture it into group `1` and match it another 5 times. We make sure there are at least two more `·` with the `·` and the `·+`. This way the index of the found triangular number doesn't increase until there's one character more than a centred hexagonal number.

In the end, this match gives us two less than the side-length of the required hexagon in group `$2`, so we write that back together with one more centre dot to get `N-1`.

```
^·*
$.&$* ·$&$&$.&$*

```

This turns our string of `N-1` centre dots into `N-1` spaces, `2N-1` centre dots and another `N-1` spaces. Note that this is the maximum indentation, followed by the diameter of the hexagon, followed by the indentation again.

```
M!&m`(?<=(?= *(·)+)^.*)(?<-1>.)+(?(1)!)|^.+$

```

This is unpleasantly long, but it basically just gives us all *overlapping* matches, which are either a) `2N-1` characters long and on the first line or b) the second line. This expands the result from the previous stage into the full, but weirdly indented hexagon. E.g. for input `12345678` we'd get:

```
  ···
 ····
·····
····
···
12345678

```

This is why we needed to append spaces in the previous stage as well.

```
+m`^( *·+)· *¶(?=\1)
$&

```

This fixes the indentation of the lines after the centre, by repeatedly indenting any line that is shorter than the previous (ignoring trailing spaces), so we get this:

```
  ···
 ····
·····
 ····
  ···
12345678

```

Now we just insert some spaces with

```
·
 ·

```

Which gives us:

```
   · · ·
  · · · ·
 · · · · ·
  · · · ·
   · · ·
12345678

```

Phew, that's done.

```
O$`(·)|\S
$1

```

Time to fill the input string into the centre dots. This is done with the help of a sort stage. We match all centre dots and each character on the last line, and we sort them by the result of the given substitution. That substitution is empty for the characters on the last line and `·` for the centre dots, so what happens is that the centre dots are simply sorted to the end (since sorting is stable). This moves the input characters into place:

```
   1 2 3
  4 5 6 7
 8 · · · ·
  · · · ·
   · · ·
········

```

Just two things left now:

```
·
.

```

This turns centre dots into regular periods.

```
G-2`

```

And this discards the last line.
> 5 votes

# Answer
## JavaScript (ES6), 144 bytes

```
(s,n=1,l=0,p=0,m=s.match(/\S/g))=>m[n]?f(s,n+6*++l,l):[...Array(l+l+1)].map((_,i,a)=>a.map((_,j)=>j<l-i|j<i-l?``:m[p++]||`.`).join` `).join`\n`

```

Where `\n` represents the literal newline character. Uses a technique for creating a hexagon that I've previously used on several other answers. For ES7 taking square roots works out slightly shorter than the recursive approach:

```
(s,p=0,m=s.match(/\S/g),l=(~-m.length/3)**.5+.5|0)=>[...Array(l+l+1)].map((_,i,a)=>a.map((_,j)=>j<l-i|j<i-l?``:m[p++]||`.`).join` `).join`\n`

```
> 1 votes

# Answer
# Python 3, 144 bytes

```
c=input().replace(' ','')
n=x=1
while x<len(c):x+=n*6;n+=1
c=c.ljust(x,'.')
while c:print(' '*(x-n)+' '.join(c[:n]));c=c[n:];n-=(len(c)<x/2)*2-1

```

Try it online!

This uses a rather varying amount of leading whitespace for different sized hexagons, but the general shape survives.
> 1 votes

# Answer
# Nibbles, 27 bytes

```
+!/|.,~+.,;+-$~$::"\n"`<!=$_^-@~" "`'$~-,;+%_~,@$:@^~".":

```

That's 54 nibbles, each half a byte in the binary form (the " " and "\n" are only 2 nibbles each).

Run it like this (Nibbles isn't on TIO yet...):

```
> echo abcdef | nibbles hex.nbl

 a b
c d e
 f .

```

## How?

Rather than compute the smallest centered hexagonal number, calculate the spaces that would be added before each input character for all possible sized hexagons. Find the first one that has as many entries as there are input characters and then just zip them together. This is a good example of the power of laziness, although mainstream languages could have accomplished the same feat with streams/enumerators.

### Translation

```
+                        concat
 !                       zip with
  /                      foldr
   |                     filter
    . ,~                 map [1..] (call it n)
      + . ,              concat map 1 to (call it i)
           ; + -$~ $     n-1+n (saved, call it k)
          :              append
           :"\n"         newline prepended with
            `< != $ _    splitAt abs n-i (returns take part)
               ^ -@~ " " replicate " " k-1 times
           `' $          transpose of the drop part from splitAt
                         below is the fn for filter
    ~ -                  not of difference (aka <=)
        , ; +%_~         length of input with spaces removed via concat words of input (saved)
        , @              length of space table
   $                     fold's element variable (essentially / ... $ is a way to take head of a list)
  :@^~"."                our space removed input with infinite "." added
  :                      append (arg to zip with), combines space table with input

```

One trick is that newline was prepended to the first space table element on each line, so that the final zip also adds newlines correctly.

Another trick is the realization that each line has 2n-2 spaces. So a take/drop (splitAt) is used to take the number needed before the first of the line and the remainder is all the things needed before each character (transpose is used to convert that to a list of strings instead of just a string).

It seems a little silly to precompute the fact that we need to add a single space to most characters, but doing so is what ultimately enables us to count the size of the hexagon and combine that hexagon with the input trivially.
> 1 votes

# Answer
# Knight, ~~158~~ 152 bytes

```
;=n~1;=pP;=s'';Wp;=s+sI?32Ap''A Ap=pGp 1Lp;W<+1+**3=n+nTn*3nLsN;=i+1*2nW+1=i-iT;O+*' '=xI>=x-n iFx~x'\';=j~2;W<=j+1j-*2n xIs;O+A As' \'=sGs 1LsO'. \'O''

```

idek anymore lol

Try It Online!

Test Suite
> 0 votes

---
Tags: code-golf, string, kolmogorov-complexity, hexagonal-grid, whitespace
---