Create an "H" from smaller "H"s

76

7

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!

Bazinga_9000

Posted 2018-03-09T01:37:43.977

Reputation: 807

4Perfect for Charcoal probably... lol. Also welcome to PPCG! :D – HyperNeutrino – 2018-03-09T01:54:46.453

10Welcome to PPCG. Nice first challenge! – Adám – 2018-03-09T02:06:59.993

May we use 0 based sizes? – Adám – 2018-03-09T02:07:19.467

@Adám that is acceptable – Bazinga_9000 – 2018-03-09T02:10:45.167

Forgot to check your acceptable outputs before I submitted, but would an array of strings be acceptable instead of a two-dimensional array? This is for languages where a string is not formally an array of characters, but its own data structure. – Value Ink – 2018-03-09T02:22:42.907

@ValueInk That's fine – Bazinga_9000 – 2018-03-09T02:24:38.067

3related – ngn – 2018-03-09T02:26:35.347

Can I print the desired output instead of returning it? Can I give a program that instead of a function? – Titus – 2018-03-09T10:53:29.403

Are leading spaces (or whatever the chosen background character is) allowed ? – Ton Hospel – 2018-03-09T15:46:58.263

Possible duplicate of ABAA/ABBB: Generate this recursive 2D pattern

– Erik the Outgolfer – 2018-03-09T17:23:50.177

@LuisMendo apologies, there are no restrictions on the two output characters so long as they are different. You can have them depend on whatever you want. – Bazinga_9000 – 2018-03-10T02:11:09.757

@Titus that's fine – Bazinga_9000 – 2018-03-10T02:11:43.430

@TonHospel Leading/trailing spaces are allowed so long as they are consistent across all lines (so the structure of the H remains) – Bazinga_9000 – 2018-03-10T02:12:55.013

1I'd call this a "Sierpinski H" – mbomb007 – 2018-03-12T21:37:27.573

I made a dot plot, but I don't think that qualifies: https://repl.it/repls/ShockedAgitatedKeygenerator

– mbomb007 – 2018-03-13T18:19:03.150

I just found a piece of paper from 2008 where I did exactly this! I was 8 at that time and very interested in fractals (meaning: even more than now). It's the fourth iteration. Photo: https://drive.google.com/open?id=1Ww7_i2phDWGwUNUZCte0Nr4YrKz_Mlxg

– Fabian Röling – 2018-04-07T18:20:59.017

Apparently a I can't do Math. I was 12 in 2008, not 8. +2, not -2. – Fabian Röling – 2018-04-07T20:59:22.227

Answers

29

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

alephalpha

Posted 2018-03-09T01:37:43.977

Reputation: 23 988

18what the heck of course Mathematica has a built-in for recursive nested arrays lol. +1 – HyperNeutrino – 2018-03-09T03:01:17.113

1@HyperNeutrino well obviously – ASCII-only – 2018-03-09T09:29:51.423

7@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) – user202729 – 2018-03-09T10:34:24.297

6There is a built-in for this, but longer. Mathematica has long function names. – alephalpha – 2018-03-09T10:49:11.193

1

How could it not, given its triumph at the upgoat challenge?

– ojdo – 2018-03-14T15:15:46.897

21

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!

hakr14

Posted 2018-03-09T01:37:43.977

Reputation: 1 295

Amazingly short answer :O – NL628 – 2018-03-09T03:40:38.133

19

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)

Luis Mendo

Posted 2018-03-09T01:37:43.977

Reputation: 87 464

16

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.

recursive

Posted 2018-03-09T01:37:43.977

Reputation: 8 616

11

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!

Value Ink

Posted 2018-03-09T01:37:43.977

Reputation: 10 608

Well done! The output looks wrong on tio at first, but it's fine when zoomed out. – Eric Duminil – 2018-03-09T19:07:13.940

10

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!

xnor

Posted 2018-03-09T01:37:43.977

Reputation: 115 687

9

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.

Dennis

Posted 2018-03-09T01:37:43.977

Reputation: 196 637

9

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

ngn

Posted 2018-03-09T01:37:43.977

Reputation: 11 449

8

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

Olivier Grégoire

Posted 2018-03-09T01:37:43.977

Reputation: 10 647

save 5 bytes by adding a static import for Math.pow – Selim – 2018-03-12T09:16:06.890

4@Selim the static import is required in the byte count. So I would lose... 19 bytes. – Olivier Grégoire – 2018-03-12T09:20:42.337

8

SOGL V0.12, 13 bytes

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

Try it Here!

dzaima

Posted 2018-03-09T01:37:43.977

Reputation: 19 048

8

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.

Giuseppe

Posted 2018-03-09T01:37:43.977

Reputation: 21 077

7

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.

James

Posted 2018-03-09T01:37:43.977

Reputation: 54 537

Is that French? – Stan Strum – 2018-05-26T21:43:43.237

7

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:

xnor

Posted 2018-03-09T01:37:43.977

Reputation: 115 687

6

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

FrownyFrog

Posted 2018-03-09T01:37:43.977

Reputation: 3 112

6

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.

nimi

Posted 2018-03-09T01:37:43.977

Reputation: 34 639

3You 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. – Potato44 – 2018-03-11T20:52:31.773

@Potato44: I'm pretty sure this will help in a lot of challenges. Thanks! – nimi – 2018-03-12T17:47:14.760

5

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!

Ton Hospel

Posted 2018-03-09T01:37:43.977

Reputation: 14 114

1Output for n ≥ 3 isn't quite right. – primo – 2018-03-09T14:12:35.860

@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 – Ton Hospel – 2018-03-09T14:40:01.627

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. – primo – 2018-03-09T15:20:47.900

1@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) – Ton Hospel – 2018-03-09T15:30:14.860

5

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.

Chiel ten Brinke

Posted 2018-03-09T01:37:43.977

Reputation: 201

What do I have to type, starting from a bash prompt, assuming I have vim installed, to see the result? – Fabien – 2018-03-13T13:03:41.200

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. – Chiel ten Brinke – 2018-03-13T13:09:24.210

Make sure to use vanilla vim – Chiel ten Brinke – 2018-03-13T13:14:07.647

There was a typo in the code. Just fixed it. – Chiel ten Brinke – 2018-03-13T13:17:22.090

1Works! <kbd>I</kbd> is a capital i, not ell. :set nowrap to see the result, for 4 and more. – Fabien – 2018-03-14T12:50:57.477

@Fabien an i works as well, so I changed it to be more clear – Chiel ten Brinke – 2018-03-14T12:52:22.527

4

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

HyperNeutrino

Posted 2018-03-09T01:37:43.977

Reputation: 26 575

A few golfs – recursive – 2018-03-09T07:15:15.277

4

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!

MJacquet

Posted 2018-03-09T01:37:43.977

Reputation: 41

2

Welcome to PPCG! You can omit f← and count chars as 1 byte each: https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each It's also considered legal to take input from , i.e. replace ⍣⍵ with ⍣⎕ and drop the outer dfn's braces.

– ngn – 2018-03-09T02:43:46.203

Thanks! I've never actually formally golfed APL before so these should help. – MJacquet – 2018-03-09T03:19:26.743

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 – 2018-03-09T14:08:24.733

Also, is your friend: (⍵,(0×⍵),⍵) => (⍵,⍵,⍨0×⍵) – Zacharý – 2018-03-09T17:23:51.653

4

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.

Neil

Posted 2018-03-09T01:37:43.977

Reputation: 95 035

4

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

Titus

Posted 2018-03-09T01:37:43.977

Reputation: 13 814

1%3==1 can be replaced with %3&1. – primo – 2018-03-13T15:34:03.470

3

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*çþ`

user202729

Posted 2018-03-09T01:37:43.977

Reputation: 14 620

3

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

Razvan Socol

Posted 2018-03-09T01:37:43.977

Reputation: 341

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. – Razvan Socol – 2018-03-11T12:46:55.853

1

Welcome to PPCG and nice first post! For tips about golfing in T-SQL, make sure to check out this post!

– caird coinheringaahing – 2018-03-11T12:50:02.190

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: http://sqlfiddle.com/#%2118/eb14e/2. However, the output is not formatted correctly by sqlfiddle, but it works fine in SSMS.

– Razvan Socol – 2018-03-11T12:50:11.797

1You should be able to get this down to 259 by removing some unnecessary whitespace and linefeeds – MickyT – 2018-03-11T18:37:07.053

I only got to 261. What am I missing? – Razvan Socol – 2018-03-11T19:23:55.173

2

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.

Titus

Posted 2018-03-09T01:37:43.977

Reputation: 13 814

2

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!

primo

Posted 2018-03-09T01:37:43.977

Reputation: 30 891

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) – Ton Hospel – 2018-03-09T13:29:38.313

2

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!

primo

Posted 2018-03-09T01:37:43.977

Reputation: 30 891

1You can save one byte: $s.$s.$s instead of $s.=$s.$s. And you don´t need <? with -R instead of -F. – Titus – 2018-03-10T12:23:54.930

Thanks for the byte. Regarding -R, can you show me the complete usage? – primo – 2018-03-10T14:26:01.537

Just like -nF: echo <input> | php -nR '<code>'. -r is almost the same: php -nr '<code>' <arguments>. – Titus – 2018-03-10T14:43:16.980

Maybe I'm just too stupid to get it working :/ https://i.stack.imgur.com/jqpmk.png

– primo – 2018-03-11T04:24:33.987

Errm no, sorry. The mix of quotation marks ruins it. You probably could work around that with a ~ for the preg-replacement; but that would render your code pretty unreadable - for gaining a single byte. – Titus – 2018-03-11T14:10:52.417

But: why preg_filter and not simply $s=($s=$s.$s).sprintf("%$i.s$s",$$i++/$i&1?$s:"");? And have you tried $s.str_pad($$i++/$i&1?$s:"",$i).$s instead of the sprintf? (I have not) – Titus – 2018-03-11T14:54:54.037

1preg_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"' – primo – 2018-03-13T05:11:25.910

1

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

Chiel ten Brinke

Posted 2018-03-09T01:37:43.977

Reputation: 201

1

K (ngn/k), 18 bytes

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

Try it online!

ngn

Posted 2018-03-09T01:37:43.977

Reputation: 11 449

1

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.

Bubbler

Posted 2018-03-09T01:37:43.977

Reputation: 16 616

0

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;
}

Tsathoggua

Posted 2018-03-09T01:37:43.977

Reputation: 131