73
\$\begingroup\$

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!

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

30 Answers 30

28
\$\begingroup\$

Wolfram Language (Mathematica), 46 bytes

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

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

Try it online!

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

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

\$\endgroup\$
  • 17
    \$\begingroup\$ what the heck of course Mathematica has a built-in for recursive nested arrays lol. +1 \$\endgroup\$ – HyperNeutrino Mar 9 '18 at 3:01
  • 1
    \$\begingroup\$ @HyperNeutrino well obviously \$\endgroup\$ – ASCII-only Mar 9 '18 at 9:29
  • 7
    \$\begingroup\$ @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) \$\endgroup\$ – user202729 Mar 9 '18 at 10:34
  • 6
    \$\begingroup\$ There is a built-in for this, but longer. Mathematica has long function names. \$\endgroup\$ – alephalpha Mar 9 '18 at 10:49
  • 1
    \$\begingroup\$ How could it not, given its triumph at the upgoat challenge? \$\endgroup\$ – ojdo Mar 14 '18 at 15:15
21
\$\begingroup\$

Canvas, 14 12 bytes

H;[⌐⌐∔*×∔;3*+

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
    3*|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!

\$\endgroup\$
  • \$\begingroup\$ Amazingly short answer :O \$\endgroup\$ – NL628 Mar 9 '18 at 3:40
19
\$\begingroup\$

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)
\$\endgroup\$
16
\$\begingroup\$

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.

\$\endgroup\$
11
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ Well done! The output looks wrong on tio at first, but it's fine when zoomed out. \$\endgroup\$ – Eric Duminil Mar 9 '18 at 19:07
10
\$\begingroup\$

Haskell, 50 bytes

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!

\$\endgroup\$
9
\$\begingroup\$

Jelly, 17 16 15 bytes

381B«€s3Z€ẎF€µ¡

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

Try it online! or see the output with H's and spaces.

\$\endgroup\$
9
\$\begingroup\$

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

\$\endgroup\$
8
\$\begingroup\$

SOGL V0.12, 13 bytes

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

Try it Here!

\$\endgroup\$
8
\$\begingroup\$

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.

\$\endgroup\$
8
\$\begingroup\$

Java (OpenJDK 9), 135 bytes

n->{n+=Math.pow(3,n)-n;int s=1,H[][]=new int[n][n],x,y;for(;s<n;s*=3)for(x=n;x-->0;)for(y=n;y-->0;)H[x][y]|=~(x/s%3)&y/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
  n+=Math.pow(3,n)-n;       //  change n to 3^n, through +=...-n to avoid an explicit cast
  int s=1,                  //  size of the carvings.
      H[][]=new int[n][n],  //  the 2D array to return, filled with 0s
      x,                    //  counter for the 2D array
      y;                    //  counter for the 2D array
  for(;s<n;s*=3)            //  for each size
    for(x=n;x-->0;)         //   for each row
      for(y=n;y-->0;)       //    for each column
        H[x][y] |=          //     assign 1 to a cell of the array if...
           ~(x/s%3)         //      it is located in the "holes" of the H
          &y/s%3            //
          &1;               //      
  return H;                 //  return the array
}                           // end the lambda
\$\endgroup\$
  • \$\begingroup\$ save 5 bytes by adding a static import for Math.pow \$\endgroup\$ – Selim Mar 12 '18 at 9:16
  • 4
    \$\begingroup\$ @Selim the static import is required in the byte count. So I would lose... 19 bytes. \$\endgroup\$ – Olivier Grégoire Mar 12 '18 at 9:20
7
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Is that French? \$\endgroup\$ – Stan Strum May 26 '18 at 21:43
7
\$\begingroup\$

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:

\$\endgroup\$
6
\$\begingroup\$

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
\$\endgroup\$
6
\$\begingroup\$

Haskell, 73 67 64 55 bytes

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.

\$\endgroup\$
  • 3
    \$\begingroup\$ 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. \$\endgroup\$ – Potato44 Mar 11 '18 at 20:52
  • \$\begingroup\$ @Potato44: I'm pretty sure this will help in a lot of challenges. Thanks! \$\endgroup\$ – nimi Mar 12 '18 at 17:47
5
\$\begingroup\$

Perl 5, 46 44 43 41 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!

\$\endgroup\$
  • 1
    \$\begingroup\$ Output for n ≥ 3 isn't quite right. \$\endgroup\$ – primo Mar 9 '18 at 14:12
  • \$\begingroup\$ @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 \$\endgroup\$ – Ton Hospel Mar 9 '18 at 14:40
  • \$\begingroup\$ 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. \$\endgroup\$ – primo Mar 9 '18 at 15:20
  • 1
    \$\begingroup\$ @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) \$\endgroup\$ – Ton Hospel Mar 9 '18 at 15:30
5
\$\begingroup\$

Vim - 66 56 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.

\$\endgroup\$
  • \$\begingroup\$ What do I have to type, starting from a bash prompt, assuming I have vim installed, to see the result? \$\endgroup\$ – Fabien Mar 13 '18 at 13:03
  • \$\begingroup\$ 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. \$\endgroup\$ – Chiel ten Brinke Mar 13 '18 at 13:09
  • \$\begingroup\$ Make sure to use vanilla vim \$\endgroup\$ – Chiel ten Brinke Mar 13 '18 at 13:14
  • \$\begingroup\$ There was a typo in the code. Just fixed it. \$\endgroup\$ – Chiel ten Brinke Mar 13 '18 at 13:17
  • 1
    \$\begingroup\$ Works! <kbd>I</kbd> is a capital i, not ell. :set nowrap to see the result, for 4 and more. \$\endgroup\$ – Fabien Mar 14 '18 at 12:50
4
\$\begingroup\$

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!

\$\endgroup\$
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – ngn Mar 9 '18 at 2:43
  • \$\begingroup\$ Thanks! I've never actually formally golfed APL before so these should help. \$\endgroup\$ – MJacquet Mar 9 '18 at 3:19
  • \$\begingroup\$ 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. \$\endgroup\$ – ngn Mar 9 '18 at 14:08
  • \$\begingroup\$ Also, is your friend: (⍵,(0×⍵),⍵) => (⍵,⍵,⍨0×⍵) \$\endgroup\$ – Zacharý Mar 9 '18 at 17:23
4
\$\begingroup\$

Charcoal, 30 29 bytes

HFENX³ι«J⁰¦⁰C⁰ιCιιT⊗ι⊗ι‖OO→↓ι

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

H

Print the original H.

FENX³ι«

Loop over the first size powers of 3.

J⁰¦⁰

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.

C⁰ι

Copy the previous iteration downwards, creating a domino.

Cιι

Copy the result down and right, creating a tetromino.

T⊗ι⊗ι

Trim the canvas down to an L shape triomino.

‖OO→↓ι

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:

HFN«⟲C²⁶‖OOLX³ι

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

\$\endgroup\$
4
\$\begingroup\$

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

\$\endgroup\$
4
\$\begingroup\$

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.

Try them online!


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.

qualified function, 147 130 bytes

function r($n){for($z=3**$n;$z*$z>$q=$p;$r.=$c."
"[++$p%$z])for($c=H;$q;$q-=$q/$z%3*$z,$q/=3)if($q%3==1&&$q/$z%3-1)$c=_;return$r;}

returns a single string. Run with default config (no php.ini).

\$\endgroup\$
  • 1
    \$\begingroup\$ %3==1 can be replaced with %3&1. \$\endgroup\$ – primo Mar 13 '18 at 15:34
3
\$\begingroup\$

Jelly, 25 bytes

,’b3U×"3S_4A1e
3*çþ`ị⁾ HY

Try it online!


Although this is longer than the existing Jelly submission, it tries to generate each character independently just from the coordinate.

In particular, if the coordinate is (x,y) (1-indexing), the first link returns 0 and 1 corresponds to H and respectively.


,                Pair. Get (x,y)
 ’               Decrement. Get (x,y) (0-indexing)
  b3             Convert to base 3 digits.
    U            Upend. So next operations can pair the corresponding digits.
     ×"3         Multiply the first element (list) by 3.
        S        Sum (corresponding digit together). Let the sum be s.
         _4A1e   Check if any of abs(s-4) is 1. Equivalently, check
                 if there is any 3 or 5 in the list of s.

Also, the 5 bytes ị⁾ HY are used for formatting, so this program (20 bytes) is also valid (but the output doesn't look as nice):

,’b3U×"3S_4A1e
3*çþ`
\$\endgroup\$
3
\$\begingroup\$

T-SQL, 267 261 bytes

DECLARE @N INT=3DECLARE @ TABLE(I INT,H VARCHAR(MAX))INSERT @ VALUES(1,'H H'),(2,'HHH'),(3,'H H');WITH
T AS(SELECT 1 A,3 P,I J,H S FROM @ UNION ALL SELECT A+1,P*3,J*P+I,REPLACE(REPLACE(S,' ','   '),'H',H)FROM @,T
WHERE A<@N)SELECT S FROM T WHERE A=@N ORDER BY J
\$\endgroup\$
  • \$\begingroup\$ This is my first answer on Code Golf, so please help me if I made any mistakes. Also, my preferred language is Transact-SQL, which is not very suitable for short code. \$\endgroup\$ – Razvan Socol Mar 11 '18 at 12:46
  • 1
    \$\begingroup\$ Welcome to PPCG and nice first post! For tips about golfing in T-SQL, make sure to check out this post! \$\endgroup\$ – caird coinheringaahing Mar 11 '18 at 12:50
  • \$\begingroup\$ I tried adding a sqlfiddle, but it doesn't work well with table variables. If I use normal tables, it's even 1 byte shorter: sqlfiddle.com/#!18/eb14e/2. However, the output is not formatted correctly by sqlfiddle, but it works fine in SSMS. \$\endgroup\$ – Razvan Socol Mar 11 '18 at 12:50
  • 1
    \$\begingroup\$ You should be able to get this down to 259 by removing some unnecessary whitespace and linefeeds \$\endgroup\$ – MickyT Mar 11 '18 at 18:37
  • \$\begingroup\$ I only got to 261. What am I missing? \$\endgroup\$ – Razvan Socol Mar 11 '18 at 19:23
2
\$\begingroup\$

PHP 7, 153 bytes

    function p($n){$r=["H H",HHH,"H H"];if(--$n)foreach(p($n)as$s){$r[+$i]=$r[$i+6*$p=3**$n]=str_pad($s,2*$p).$s;$r[3*$p+$i++]=$s.$s.$s;}ksort($r);return$r;}

Run with default config (no php.ini) or try it online.

\$\endgroup\$
2
\$\begingroup\$

Perl, 64 bytes

//;$_ x=3,$.=s|.+|$&@{[$$_++/$.&1?$&:$"x$.]}$&|g for($_=H.$/)x$'

Requires -p, input is taken from stdin. Output is an H of Hs.

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Counting on this site has changed, you don't need to count -p anymore (I think it is too lenient for perl, but that's how it is now) \$\endgroup\$ – Ton Hospel Mar 9 '18 at 13:29
2
\$\begingroup\$

PHP (5.6+), 94 bytes

<?for(;$H>$e*=3or$e=($i+=$e&&print"$s
")<${$s=H}=3**$argn;)$s.=str_pad($i/$e%3&1?$s:'',$e).$s;

Used with -F command line option. Assumes interpreter defaults (-n). Will not work on versions previous to 5.6, due to the power operator.

Sample usage

$ echo 3|php -nF h-carpet.php
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

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ You can save one byte: $s.$s.$s instead of $s.=$s.$s. And you don´t need <? with -R instead of -F. \$\endgroup\$ – Titus Mar 10 '18 at 12:23
  • \$\begingroup\$ Thanks for the byte. Regarding -R, can you show me the complete usage? \$\endgroup\$ – primo Mar 10 '18 at 14:26
  • \$\begingroup\$ Just like -nF: echo <input> | php -nR '<code>'. -r is almost the same: php -nr '<code>' <arguments>. \$\endgroup\$ – Titus Mar 10 '18 at 14:43
  • \$\begingroup\$ Maybe I'm just too stupid to get it working :/ i.stack.imgur.com/jqpmk.png \$\endgroup\$ – primo Mar 11 '18 at 4:24
  • 1
    \$\begingroup\$ preg_filter is to iterate each line while preserving newlines, roughly equivalent to join("\n",array_map(function(){...},split("\n",$s.$s.$s))), but significantly less verbose. I initially had str_pad but changed to sprintf because it's one byte shorter: '"\0".str_pad($$i++/$i&1?"\0":"",$i)."\0"' \$\endgroup\$ – primo Mar 13 '18 at 5:11
1
\$\begingroup\$

CJam - 103 97 87 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

\$\endgroup\$
1
\$\begingroup\$

K (ngn/k), 18 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.