# 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!

• Why do we even have a hexagonal-grid tag? – Pavel Dec 26 '16 at 7:25
• Also, someone needs to write a hexagony solution. – Pavel Dec 26 '16 at 7:40
• If anyone wants to go for the bounty, you can probably reuse the output loop of my Hexagony answer over here. – Martin Ender Jan 19 '17 at 9:01
• "Could you make me a hexagon please?" - sure, here you go: i.imgur.com/1emYIia.png – aditsu Jan 28 '17 at 18:45
• @Pavel because a lot of operations on a hexagonal grid are distinct from on the more standard square grid, and portable between solutions to different problems. Such operations as coordinate manipulation, rotation, output layout, etc. – Sparr Jun 28 '18 at 5:25

# 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)]]} # 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. • This could be shortened by changing to Python2. – Yytsi Jan 24 '17 at 6:14 • @TuukkaX unfortunately I don't know Python2 well enough to change it. You are welcome to suggest a solution – george Jan 26 '17 at 13:26 ## 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"; } ## 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 definitelyprobably be golfed further.

# PostgreSQL, 86

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

\prompt n

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

# 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)
• I would be interested to see an explanation of how this works. – Sriotchilism O'Zaic Jan 29 '17 at 6:27
• will do @WheatWizard! – Nick the coder Jan 29 '17 at 6:30

# Groovy, 64636258 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:

* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *

# 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 as. 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 as. .*$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 as 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 as have been inserted. m^(a+)¶\1$1

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

a
*

Finally, replace all instances of a with * ​.

# R, 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!

# 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.

# Kotlin, 113 89 bytes

24 bytes saved thanks to mazzy

{n:Int->for(o in 1-n..n-1){val c=Math.abs(o)

Try it online!

• 87 bytes: n:Int->for(m in 1-n..n-1){val c=Math.abs(m);println("".padEnd(c)+"* ".repeat(2*n-c-1))} – mazzy Jun 28 '18 at 21:40

# 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

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

# K (oK), 4438 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:

Try it online!

# 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

# 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.

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

Try it online!

Now beats V!

# 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.

# Charcoal, 3331 17 bytes

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

-14 bytes thanks to @Neil.

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);
‖Ｂ↓
• FYI I'm down to 22 bytes using a different algorithm (ported from my answer to another hexagon-drawing question). – Neil Jan 27 at 12:34
• I got to 20 bytes using a polygon but 17 bytes based on your algorithm. – Neil Jan 27 at 13:05