# Challenge

Create a function or program that, when given an integer size, does the following:

If size is equal to 1, output

H H
HHH
H H


If size is greater than 1, output

X X
XXX
X X


where X is the output of the program/function for size - 1

(If you prefer, you may have the base case correspond to 0, so long as you specify in your answer)

Any of the following output formats are acceptable, whichever is more convenient for you:

• A string of the required structure with any two distinct characters corresponding to H and space

• A two-dimensional array with the required structure, with any two distinct values corresponding to H and space

• An array/list of strings, with one line of the output in each string, with any two distinct values corresponding to H and space

Leading spaces are allowed, as long as there is a constant amount of leading spaces on each line. The two distinct output characters can be dependent on anything you choose, as long as they are different.

Specify what output format your code is returning.

# Test Cases

1

H H
HHH
H H


2

H H   H H
HHH   HHH
H H   H H
H HH HH H
HHHHHHHHH
H HH HH H
H H   H H
HHH   HHH
H H   H H


3

H H   H H         H H   H H
HHH   HHH         HHH   HHH
H H   H H         H H   H H
H HH HH H         H HH HH H
HHHHHHHHH         HHHHHHHHH
H HH HH H         H HH HH H
H H   H H         H H   H H
HHH   HHH         HHH   HHH
H H   H H         H H   H H
H H   H HH H   H HH H   H H
HHH   HHHHHH   HHHHHH   HHH
H H   H HH H   H HH H   H H
H HH HH HH HH HH HH HH HH H
HHHHHHHHHHHHHHHHHHHHHHHHHHH
H HH HH HH HH HH HH HH HH H
H H   H HH H   H HH H   H H
HHH   HHHHHH   HHHHHH   HHH
H H   H HH H   H HH H   H H
H H   H H         H H   H H
HHH   HHH         HHH   HHH
H H   H H         H H   H H
H HH HH H         H HH HH H
HHHHHHHHH         HHHHHHHHH
H HH HH H         H HH HH H
H H   H H         H H   H H
HHH   HHH         HHH   HHH
H H   H H         H H   H H


This is , so the lowest byte count for each language wins!

• Perfect for Charcoal probably... lol. Also welcome to PPCG! :D Mar 9 '18 at 1:54
• Welcome to PPCG. Nice first challenge!
Mar 9 '18 at 2:06
• May we use 0 based sizes?
Mar 9 '18 at 2:07
• related
– ngn
Mar 9 '18 at 2:26
• I'd call this a "Sierpinski H" Mar 12 '18 at 21:37

# Wolfram Language (Mathematica), 46 bytes

Nest[ArrayFlatten@{r={#,0,#},{#,#,#},r}&,1,#]&


Returns a 2d array of 0s and 1s.

Try it online!

• what the heck of course Mathematica has a built-in for recursive nested arrays lol. +1 Mar 9 '18 at 3:01
• @HyperNeutrino well obviously Mar 9 '18 at 9:29
• @HyperNeutrino How is this considered a built-in? Just Nest (repeatedly) the function multiple times. Like any other submissions (Jelly?) The ArrayFlatten is... well, built-in, but it behaves somewhat just like a Flatten[#,{{1,3},{2,4}}] in this case. (didn't test) Mar 9 '18 at 10:34
• There is a built-in for this, but longer. Mathematica has long function names. Mar 9 '18 at 10:49
• How could it not, given its triumph at the upgoat challenge?
– ojdo
Mar 14 '18 at 15:15

## Canvas, 14 12 bytes

H；［⌐⌐∔＊×∔；３＊＋


Try it here!

Explanation:
Code    |Instruction                                                         |Stack
--------+--------------------------------------------------------------------+-------------------------
|Push input to stack (implicit)                                      |I
H       |Push "H" to stack                                                   |I,"H"
；      |Swap the top two stack items                                        |"H",I
［      |The following ToS (input) times:                                    |X
⌐⌐  |Duplicate ToS (result from last loop ("H" if first loop)) four times|X,X,X,X,X
∔   |Join vertically                                                     |X,X,X,X\nX
×   |Prepend                                                             |X,X,XX\nX
∔   |Join vertically                                                     |X,X\nXX\nX
；  |Swap top two stack items                                            |X\nXX\nX,X
３＊|Repeat three times vertically                                       |X\nXX\nX,X\nX\nX
＋  |Join horizontally                                                   |X<space>X\nXXX\nX<space>X
|End loop (implicit)                                                 |X
|Print ToS (implicit)                                                |


Where I is the input, X is the pattern generated by the previous loop ("H" for the first loop), and <space> is the empty space on the first and third row of the pattern, added implicitly by ＋.

-2 bytes thanks to dzaima!

• Amazingly short answer :O Mar 9 '18 at 3:40

# MATL, 12 11 bytes

t:"[ACA]BX*


Given input n, this outputs a matrix containing 0 and n.

Try it online!

To convert this into a character matrix of Hand space add g72*c in the header. Try it online too!

Or add ]1YC to see the matrix displayed graphically. Try it at MATL Online!

### Explanation

t          % Input (implicit): n. Duplicate
:          % Range. Gives the array [ 1 2 ... n]
"          % For each (that is, do n times)
[ACA]    %   Push the array [5 7 5]
B        %   Convert to binary. Gives the 3×3 matrix [1 0 1; 1 1 1; 1 0 1]
X*       %   Kronecker product
% End (implicit). Display (implicit)


# Stax, 16 15 bytes

╛c_mê║6{│◙ÖmπV"


Run and debug it

This is the ascii representation of the program with comments. This program builds up the H sideways, and then transposes once at the end.

'H]                 ["H"]
{         },*    repeat block specified number of times
c               copy the matrix
{3*m           triplicate each row
|S         surround; prepend and append like b + a + b
|C       horizontally center rows with spaces
M   transpose back to original orientation
m  output each row


Bonus 14 byte program - uses its input as the output character. Theoretically, this would not produce the right shape at 10, since it has 2 digits, but attempting to run that crashes my browser.

# Ruby, 72 bytes

Output is a list of strings, one string per line.

f=->n{n<1?[?H]:[*a=(x=f[n-1]).map{|i|i+' '*i.size+i},*x.map{|i|i*3},*a]}


Try it online!

• Well done! The output looks wrong on tio at first, but it's fine when zoomed out. Mar 9 '18 at 19:07

# APL (Dyalog Classic), 14 bytes

×/¨∘.≥⍨2|,⍳⎕⍴3


Try it online!

⎕ evaluated input n

,⍳⎕⍴3 all n-tuples with elements from 0 1 2

2| mod 2

×/¨∘.≥⍨ form a matrix by comparing every pair of tuples a and b - if all elements of a are ≥ the corresponding elements of b, it's a 1, otherwise 0

f 0=[[1]]
f n=[x++map(*c)x++x|c<-[0,1,0],x<-f$n-1]  Try it online! Makes a grid of 0's and 1's. One character longer for spaces and H's. # Haskell, 51 bytes f 0=["H"] f n=[x++map(min c)x++x|c<-" H ",x<-f$n-1]


Try it online!

# Jelly, 1716 15 bytes

381B«€s3Z€ẎF€µ¡


This is a full program that prints a 2D array of 1's and 0's.

# SOGL V0.12, 13 bytes

┌.{³2∙⁴┼+;3∙┼


Try it Here!

# R, 64 bytes

function(n)Reduce(%x%,rep(list(matrix(c(1,1,1,0,1,0),3,3)),n))


Try it online!

Reduces by Kronecker product, as a shameless port of Luis Mendo's answer.

The footer prints the result nicely, but this is an anonymous function which returns a matrix of 1 for H and 0 for space.

# Java (JDK), 126 bytes

n->{int s=1,H[][]=new int[n+=Math.pow(3,n)-n][n],x;for(;s<n;s*=3)for(x=n*n;x-->0;)H[x/n][x%n]|=~(x/n/s%3)&x%n/s%3&1;return H;}


Try it online!

Returns an int[][] with 0 for H and 1 for space. This actually "carves" a wall of H's instead of "piling" H's.

## Explanations

n->{                        // An int to int[][] lambda function
int s=1,                  //  size of the carvings.
H[][]=new int[n+=Math.pow(3,n)-n][n],
//  change n to 3^n, through +=...-n to avoid an explicit cast
//  and create the 2D array to return, filled with 0s
x;                    //  counter for the 2D array
for(;s<n;s*=3)            //  for each size
for(x=n*n;x-->0;)       //   for each cell
H[x/n][x%n] |=        //     assign 1 to a cell of the array if...
~(x/n/s%3)          //      it is located in the "holes" of the H
&x%n/s%3            //
&1;                 //
return H;                 //  return the array
}                           // end the lambda


## Credits

• save 5 bytes by adding a static import for Math.pow Mar 12 '18 at 9:16
• @Selim the static import is required in the byte count. So I would lose... 19 bytes. Mar 12 '18 at 9:20

# V, 22 bytes

éHÀñäLgvr PGï3PkyHGpH


Try it online!

Hexdump:

00000000: e948 c0f1 e416 4c67 7672 2050 47ef 3350  .H....Lgvr PG.3P
00000010: 6b79 4847 7048                           kyHGpH


This is basically the exact same approach as the Sierpinski carpet and The Fractal Plus on Anarchy Golf.

• Is that French? May 26 '18 at 21:43

# Python 2, 70 bytes

f=lambda r:-r*'H'or[x+[x,' '*3**r][b]+x for b in 1,0,1for x in f(r-1)]


Try it online!

Function outputs a list of strings.

# Python 2, 84 bytes

r=input()
for i in range(3**r):x,s=' H';exec"s+=[x,s][i%3%2]+s;x*=3;i/=3;"*r;print s


Try it online!

Uses the same template as other 3*3 fractal patterns:

# J, 25 22 bytes

,./^:2@(*/#:@5 7 5)^:]


Try it online!

        */               multiply by
#:@5 7 5       the binary matrix shaped like H
,./^:2                   assemble the 4-dimensional result into a matrix
^:]   do it input times


g#f=g<>f<>g
w=map.(id#)
(iterate(w(>>" ")#w id)["H"]!!)


This works only with the latest version of Prelude, because it exports <> from Data.Semigroup. To run it on TIO, add an import as done here: Try it online!

g#f=              -- function # takes two functions g and f and a list s
-- and returns
g <> f <> g    -- g(s), followed by f(s) and another g(s)

w=                -- w takes a function and a list of lists
-- (both as unnamed parameters, because of pointfree style,
-- so let's call them f and l)
map.(id#)       -- return map(id#f)l, i.e. apply (id#f) to every element of l

w(>>" ")#w id   -- this partial application of # is a function that
-- takes the missing list (here a list of lists)
-- remember: (>>" ") is the function that replaces every element
-- of a list with a single space

iterate(   )["H"] -- starting with a singleton list of the string "H"
-- which itself is a singleton list of the char 'H'
-- repeatedly apply the above function
!!  -- and pick the nth iteration

Example for ["H H", "HHH", "H H"], i.e.

H H
HHH
H H

call the iterated function:
( w(>>" ")         # w id       ) ["H H","HHH","H H"]

expand w:           ( map(id#(>>" "))  # map(id#id) ) ["H H","HHH","H H"]

expand outermost #: map(id#(>>" "))["H H","HHH","H H"] ++
map(id#id)     ["H H","HHH","H H"] ++
map(id#(>>" "))["H H","HHH","H H"]

expand map:         [(id#(>>" "))"H H",   (id#(>>" "))"HHH",   (id#(>>" "))"H H"] ++
[(id#id)     "H H",   (id#id)     "HHH",   (id#id)     "H H"] ++
[(id#(>>" "))"H H",   (id#(>>" "))"HHH",   (id#(>>" "))"H H"]

expand other #:     ["H H"++"   "++"H H", "HHH"++"   "++"HHH", "H H"++"   "++"H H"] ++
["H H"++"H H"++"H H", "HHH"++"HHH"++"HHH", "H H"++"H H"++"H H"] ++
["H H"++"   "++"H H", "HHH"++"   "++"HHH", "H H"++"   "++"H H"]

collaps ++:         ["H H   H H", "HHH   HHH", "H H   H H",
"H HH HH H", "HHHHHHHHH", "H HH HH H",
"H H   H H", "HHH   HHH", "H H   H H"]

which is printed line by line:

H H   H H
HHH   HHH
H H   H H
H HH HH H
HHHHHHHHH
H HH HH H
H H   H H
HHH   HHH
H H   H H


Edit: -9 bytes thanks to @Potato44.

• You should be able to golf (#) down to g#f=g<>f<>g if you use GHC 8.4. This is because Semigroup is now in the prelude. Mar 11 '18 at 20:52
• @Potato44: I'm pretty sure this will help in a lot of challenges. Thanks!
– nimi
Mar 12 '18 at 17:47

# Perl 5, 46444341 40 bytes

1 based counting. Uses 0 and 1 for H and space, has a leading 1 (space)

say//,map/$'/^1,@;for@;=glob"{A,.,A}"x<>  Based on a classic idea by mtve. Try it online! • Output for n ≥ 3 isn't quite right. Mar 9 '18 at 14:12 • @primo The program was correct but TIO uses the UTF-8 version of the special characters. I fixed the link to use escapes instead, but the program still works if you use the actual literal characters Mar 9 '18 at 14:40 • I have no idea why \321 is necessary, any character seems to work. // and $' can also replace //g and $, but I'm not sure it leads to an improvement. Mar 9 '18 at 15:20 • @primo Thanks! I was still working from code derived from the old mtve solution where \321 was the bit complement of . (used to generate another fractal pattern). But I dropped the bit-complement so of course I don't need that anymore. I used //g and$ so I can easily test the code from the commandline (// and $' don't lead to a gain I can see, the gained byte is wasted with a space or ! again) Mar 9 '18 at 15:30 # Vim - 6656 54 bytes A @ c H esc " r d ^ q c { ctrl-v } " a y g v r space g v d " a P P " a P V G " b y P g v ctrl-v$ d " a P . . G " b p q @ r

The input is taken as a number in the buffer.

• What do I have to type, starting from a bash prompt, assuming I have vim installed, to see the result? Mar 13 '18 at 13:03
• Type vim, press enter, type the input number (e.g. 3) in the buffer then, from normal mode, press the sequence of keys from the post. Mar 13 '18 at 13:09
• Make sure to use vanilla vim Mar 13 '18 at 13:14
• There was a typo in the code. Just fixed it. Mar 13 '18 at 13:17
• Works! <kbd>I</kbd> is a capital i, not ell. :set nowrap to see the result, for 4 and more. Mar 14 '18 at 12:50

# APL (Dyalog Unicode), 38 34 bytesSBCS

({(⍵,(0×⍵),⍵){⍺⍪⍵⍪⍺}⍵,⍵,⍵}⍣⎕)1 1⍴1


Output is a 2-dimensional array with 1 representing H and 0 representing space.

Try it online!

• Welcome to PPCG! You can omit f← and count chars as 1 byte each: codegolf.meta.stackexchange.com/questions/9428/… It's also considered legal to take input from ⎕, i.e. replace ⍣⍵ with ⍣⎕ and drop the outer dfn's braces.
– ngn
Mar 9 '18 at 2:43
• Thanks! I've never actually formally golfed APL before so these should help. Mar 9 '18 at 3:19
• 1 1⍴1 can be written as ⍪1 and then the parens around the operator become unnecessary. If you're familiar with trains - they can help a lot here.
– ngn
Mar 9 '18 at 14:08
• Also, ⍨ is your friend: (⍵,(0×⍵),⍵) => (⍵,⍵,⍨0×⍵) Mar 9 '18 at 17:23

# Charcoal, 30 29 bytes

HＦＥＮＸ³ι«Ｊ⁰¦⁰Ｃ⁰ιＣιιＴ⊗ι⊗ι‖ＯＯ→↓ι


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

H


Print the original H.

ＦＥＮＸ³ι«


Loop over the first size powers of 3.

Ｊ⁰¦⁰


Move the cursor back to the origin. Trim needs this, as both the original printing of the H and the reflection below move the cursor.

Ｃ⁰ι


Copy the previous iteration downwards, creating a domino.

Ｃιι


Copy the result down and right, creating a tetromino.

Ｔ⊗ι⊗ι


Trim the canvas down to an L shape triomino.

‖ＯＯ→↓ι


Reflect the canvas horizontally and vertically with overlap, completing the iteration.

Charcoal is better at some fractals than others. Here's a similar idea, but in almost half the size:

HＦＮ«⟲Ｃ²⁶‖ＯＯLＸ³ι


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

# Python 2, 143 bytes

def g(a,x,y,s):
if s:s/=3;[g(a,x+k/3*s,y+k%3*s,s)for k in 0,2,3,4,5,6,8]
else:a[x][y]=1
def f(s):s=3**s;a=eval("s*[0],"*s);g(a,0,0,s);print a


Try it online!

-30 bytes thanks to recursive

wrapper code is for nice formatting. it works fine if you remove it

• A few golfs Mar 9 '18 at 7:15

# PHP 7, 125 109 bytes

a different approach: Instead of nesting and flattening the result recursively, this just loops through the rows and columns and uses a 3rd loop to find out if to print H or _.

Edit: Saved a lot by combining the row/column loops to one, though it took a bit to get the decrease for the inner loop correct. Requires PHP 7 for the power operator.

for($z=3**$argn;$z*$z>$q=$p;print$c." "[++$p%$z])for($c=H;$q;$q-=$q/$z%3*$z,$q/=3)if($q%3==1&&$q/$z%3-1)$c=_;


prints the result. Run as pipe with -nR.

# CJam - 1039787 76 bytes

{H{ae_,S*}%}:Il~a:A];{A_W={)(a9*+:A;[[HIH][HHH][HIH]]{z~}%}{);:A;"H"}?}:H~N*


This program does a quite verbose "handcoded" recursion. No smart matrix multiplications. Throughout the recursion, on top of the stack there is an array gathering the output gained from the parent calls. Right after each set of recursive calls the output of the recursive calls needs to be zipped together, to make sure the output is correct when the stack is printed linearly at the end of the program. The stack of arguments being passed down the recursion is kept in the variable A.

Try online

# K (ngn/k), 18 bytes

{~|/a<\:'a:1=!x#3}


Try it online!

# Japt, 23 bytes

_·£[X³XX³]Ãy c ·û}gQq)y


Try it online!

### Unpacked & How it works

Z{ZqR mXYZ{[Xp3 XXp3]} y c qR û}gQq)y

Z{    Declare a function that accepts a string...
ZqR   Split by newline...
mXYZ{   and map each row into...
[Xp3 XXp3]  an array of [X.repeat(3), X, X.repeat(3)]
}
y   Transpose the resulting 2D array
c   Flatten
qR  Join with newline
û   Center-pad each row to the longest
}
gQq)  Apply the above function to '"' recursively
y     Transpose the resulting 2D string


Using the transposed pattern

III
I
III


is far easier to handle than the original H pattern, at least in Japt where the I can be done with string repeat and center-padding.

# C++11 - 138 bytes

Not sure if this answer has a valid syntax here however.

#define A a?1:0
template<int N>struct H{H<N-1>h[9];H(int a):h{A,0,A,A,A,A,A,0,A}{}};template<>struct H<0>{char h;H(int a):h{a?'H':' '}{}};


Ungolfed with working code

#include <iostream>

#define A a?1:0

template<int N>
struct H
{
H<N-1> h[9];

H(int a) : h{A,0,A,A,A,A,A,0,A}
{}
};

template<>
struct H<0>
{
char h;

H(int a) : h{a?'H':' '}
{}
};

int pow(int a, int b)
{
int res=1;

for (int i=1; i<=b; ++i)
res *= a;

return res;
}

template<int N>
char getHvalue(int i, int j, H<N> &hn)
{
int n3=pow(3, N-1);

//std::cout << N << " " << i << " " << j << std::endl;

return getHvalue(i%n3, j%n3, hn.h[i/n3*3+j/n3]);
}

template<>
char getHvalue<0>(int, int, H<0> &hn)
{
return hn.h;
}

int main()
{
H<0> h0(1);

std::cout << getHvalue(0, 0, h0) << std::endl;

std::cout << "\n====================\n" << std::endl;

H<1> h1(1);

for (int i=0; i<3; ++i) {
for (int j=0; j<3; ++j)
std::cout << getHvalue(i, j, h1);
std::cout << std::endl;
}

std::cout << "\n====================\n" << std::endl;

H<2> h2(1);

for (int i=0; i<9; ++i) {
for (int j=0; j<9; ++j)
std::cout << getHvalue(i, j, h2);
std::cout << std::endl;
}

std::cout << "\n====================\n" << std::endl;

H<3> h3(1);

for (int i=0; i<27; ++i) {
for (int j=0; j<27; ++j)
std::cout << getHvalue(i, j, h3);
std::cout << std::endl;
}

return 0;
}