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
HandspaceA two-dimensional array with the required structure, with any two distinct values corresponding to
HandspaceAn array/list of strings, with one line of the output in each string, with any two distinct values corresponding to
Handspace
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 code-golf, so the lowest byte count for each language wins!
-
5\$\begingroup\$ Perfect for Charcoal probably... lol. Also welcome to PPCG! :D \$\endgroup\$hyperneutrino– hyperneutrino ♦2018年03月09日 01:54:46 +00:00Commented Mar 9, 2018 at 1:54
-
11\$\begingroup\$ Welcome to PPCG. Nice first challenge! \$\endgroup\$Adám– Adám2018年03月09日 02:06:59 +00:00Commented Mar 9, 2018 at 2:06
-
\$\begingroup\$ May we use 0 based sizes? \$\endgroup\$Adám– Adám2018年03月09日 02:07:19 +00:00Commented Mar 9, 2018 at 2:07
-
3\$\begingroup\$ related \$\endgroup\$ngn– ngn2018年03月09日 02:26:35 +00:00Commented Mar 9, 2018 at 2:26
-
2\$\begingroup\$ I'd call this a "Sierpinski H" \$\endgroup\$mbomb007– mbomb0072018年03月12日 21:37:27 +00:00Commented Mar 12, 2018 at 21:37
30 Answers 30
Wolfram Language (Mathematica), 46 bytes
Nest[ArrayFlatten@{r={#,0,#},{#,#,#},r}&,1,#]&
Returns a 2d array of 0s and 1s.
Nest[ArrayFlatten@{r={#,0,#},{#,#,#},r}&,1,#]&[3]//MatrixForm
-
18\$\begingroup\$ what the heck of course Mathematica has a built-in for recursive nested arrays lol. +1 \$\endgroup\$2018年03月09日 03:01:17 +00:00Commented Mar 9, 2018 at 3:01
-
1\$\begingroup\$ @HyperNeutrino well obviously \$\endgroup\$ASCII-only– ASCII-only2018年03月09日 09:29:51 +00:00Commented Mar 9, 2018 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?) TheArrayFlattenis... well, built-in, but it behaves somewhat just like aFlatten[#,{{1,3},{2,4}}]in this case. (didn't test) \$\endgroup\$user202729– user2027292018年03月09日 10:34:24 +00:00Commented Mar 9, 2018 at 10:34 -
6\$\begingroup\$ There is a built-in for this, but longer. Mathematica has long function names. \$\endgroup\$alephalpha– alephalpha2018年03月09日 10:49:11 +00:00Commented Mar 9, 2018 at 10:49
-
1\$\begingroup\$ How could it not, given its triumph at the upgoat challenge? \$\endgroup\$ojdo– ojdo2018年03月14日 15:15:46 +00:00Commented Mar 14, 2018 at 15:15
Canvas, (削除) 14 (削除ここまで) 12 bytes
×ばつ∔;3*+
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!
-
\$\begingroup\$ Amazingly short answer :O \$\endgroup\$NL628– NL6282018年03月09日 03:40:38 +00:00Commented Mar 9, 2018 at 3:40
MATL, (削除) 12 (削除ここまで) 11 bytes
t:"[ACA]BX*
Given input n, this outputs a matrix containing 0 and n.
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 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"
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]}
-
\$\begingroup\$ Well done! The output looks wrong on tio at first, but it's fine when zoomed out. \$\endgroup\$Eric Duminil– Eric Duminil2018年03月09日 19:07:13 +00:00Commented Mar 9, 2018 at 19:07
APL (Dyalog Classic), 14 bytes
×ばつ/ ̈∘.≥⍨2|,⍳⎕⍴3
⎕ 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
Haskell, 50 bytes
f 0=[[1]]
f n=[x++map(*c)x++x|c<-[0,1,0],x<-f$n-1]
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]
R, 64 bytes
function(n)Reduce(`%x%`,rep(list(matrix(c(1,1,1,0,1,0),3,3)),n))
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;}
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
- -9 bytes thanks to ceilingcat.
-
\$\begingroup\$ save 5 bytes by adding a static import for Math.pow \$\endgroup\$Selim– Selim2018年03月12日 09:16:06 +00:00Commented Mar 12, 2018 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– Olivier Grégoire2018年03月12日 09:20:42 +00:00Commented Mar 12, 2018 at 9:20
V, 22 bytes
éHÀñäLgvr PGï3PkyHGpH
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.
-
\$\begingroup\$ Is that French? \$\endgroup\$Stan Strum– Stan Strum2018年05月26日 21:43:43 +00:00Commented May 26, 2018 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)]
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
Uses the same template as other 3*3 fractal patterns:
J, (削除) 25 (削除ここまで) 22 bytes
,./^:2@(*/#:@5 7 5)^:]
*/ multiply by
#:@5 7 5 the binary matrix shaped like H
,./^:2 assemble the 4-dimensional result into a matrix
^:] do it input times
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.
-
3\$\begingroup\$ You should be able to golf
(#)down tog#f=g<>f<>gif you use GHC 8.4. This is becauseSemigroupis now in the prelude. \$\endgroup\$Potato44– Potato442018年03月11日 20:52:31 +00:00Commented Mar 11, 2018 at 20:52 -
\$\begingroup\$ @Potato44: I'm pretty sure this will help in a lot of challenges. Thanks! \$\endgroup\$nimi– nimi2018年03月12日 17:47:14 +00:00Commented Mar 12, 2018 at 17:47
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.
-
\$\begingroup\$ What do I have to type, starting from a bash prompt, assuming I have vim installed, to see the result? \$\endgroup\$Fabien– Fabien2018年03月13日 13:03:41 +00:00Commented Mar 13, 2018 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\$chtenb– chtenb2018年03月13日 13:09:24 +00:00Commented Mar 13, 2018 at 13:09
-
\$\begingroup\$ Make sure to use vanilla vim \$\endgroup\$chtenb– chtenb2018年03月13日 13:14:07 +00:00Commented Mar 13, 2018 at 13:14
-
\$\begingroup\$ There was a typo in the code. Just fixed it. \$\endgroup\$chtenb– chtenb2018年03月13日 13:17:22 +00:00Commented Mar 13, 2018 at 13:17
-
1\$\begingroup\$ Works! <kbd>I</kbd> is a capital i, not ell.
:set nowrapto see the result, for 4 and more. \$\endgroup\$Fabien– Fabien2018年03月14日 12:50:57 +00:00Commented Mar 14, 2018 at 12:50
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.
-
1\$\begingroup\$ Output for n ≥ 3 isn't quite right. \$\endgroup\$primo– primo2018年03月09日 14:12:35 +00:00Commented Mar 9, 2018 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– Ton Hospel2018年03月09日 14:40:01 +00:00Commented Mar 9, 2018 at 14:40
-
\$\begingroup\$ I have no idea why
321円is necessary, any character seems to work.//and$'can also replace//gand$`, but I'm not sure it leads to an improvement. \$\endgroup\$primo– primo2018年03月09日 15:20:47 +00:00Commented Mar 9, 2018 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//gand $` 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– Ton Hospel2018年03月09日 15:30:14 +00:00Commented Mar 9, 2018 at 15:30
APL (Dyalog Unicode), (削除) 38 (削除ここまで) 34 bytesSBCS
({(⍵,(×ばつ⍵),⍵){⍺⍪⍵⍪⍺}⍵,⍵,⍵}⍣⎕)1 1⍴1
Output is a 2-dimensional array with 1 representing H and 0 representing space.
-
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– ngn2018年03月09日 02:43:46 +00:00Commented Mar 9, 2018 at 2:43 -
\$\begingroup\$ Thanks! I've never actually formally golfed APL before so these should help. \$\endgroup\$MJacquet– MJacquet2018年03月09日 03:19:26 +00:00Commented Mar 9, 2018 at 3:19
-
-
\$\begingroup\$ Also,
⍨is your friend:(⍵,(0×⍵),⍵)=>(⍵,⍵,⍨0×⍵)\$\endgroup\$Adalynn– Adalynn2018年03月09日 17:23:51 +00:00Commented Mar 9, 2018 at 17:23
Charcoal, (削除) 30 (削除ここまで) 29 bytes
HFENX3ι«J0¦0C0ιCιιT⊗ι⊗ι‖OO→↓ι
Try it online! Link is to verbose version of code. Explanation:
H
Print the original H.
FENX3ι«
Loop over the first size powers of 3.
J0¦0
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.
C0ι
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«⟲C26‖OOLX3ι
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
-30 bytes thanks to recursive
wrapper code is for nice formatting. it works fine if you remove it
-
\$\begingroup\$ A few golfs \$\endgroup\$recursive– recursive2018年03月09日 07:15:15 +00:00Commented Mar 9, 2018 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.
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).
-
1\$\begingroup\$
%3==1can be replaced with%3&1. \$\endgroup\$primo– primo2018年03月13日 15:34:03 +00:00Commented Mar 13, 2018 at 15:34
Jelly, 25 bytes
×ばつ"3S_4A1e
3*çþ`ị) HY
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):
×ばつ"3S_4A1e
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
-
\$\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– Razvan Socol2018年03月11日 12:46:55 +00:00Commented Mar 11, 2018 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\$2018年03月11日 12:50:02 +00:00Commented Mar 11, 2018 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– Razvan Socol2018年03月11日 12:50:11 +00:00Commented Mar 11, 2018 at 12:50
-
1\$\begingroup\$ You should be able to get this down to 259 by removing some unnecessary whitespace and linefeeds \$\endgroup\$MickyT– MickyT2018年03月11日 18:37:07 +00:00Commented Mar 11, 2018 at 18:37
-
\$\begingroup\$ I only got to 261. What am I missing? \$\endgroup\$Razvan Socol– Razvan Socol2018年03月11日 19:23:55 +00:00Commented Mar 11, 2018 at 19:23
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.
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.
-
\$\begingroup\$ Counting on this site has changed, you don't need to count
-panymore (I think it is too lenient for perl, but that's how it is now) \$\endgroup\$Ton Hospel– Ton Hospel2018年03月09日 13:29:38 +00:00Commented Mar 9, 2018 at 13:29
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
-
1\$\begingroup\$ You can save one byte:
$s.$s.$sinstead of$s.=$s.$s. And you don´t need<?with-Rinstead of-F. \$\endgroup\$Titus– Titus2018年03月10日 12:23:54 +00:00Commented Mar 10, 2018 at 12:23 -
\$\begingroup\$ Thanks for the byte. Regarding
-R, can you show me the complete usage? \$\endgroup\$primo– primo2018年03月10日 14:26:01 +00:00Commented Mar 10, 2018 at 14:26 -
\$\begingroup\$ Just like
-nF:echo <input> | php -nR '<code>'.-ris almost the same:php -nr '<code>' <arguments>. \$\endgroup\$Titus– Titus2018年03月10日 14:43:16 +00:00Commented Mar 10, 2018 at 14:43 -
\$\begingroup\$ Maybe I'm just too stupid to get it working :/ i.sstatic.net/jqpmk.png \$\endgroup\$primo– primo2018年03月11日 04:24:33 +00:00Commented Mar 11, 2018 at 4:24
-
1\$\begingroup\$
preg_filteris to iterate each line while preserving newlines, roughly equivalent tojoin("\n",array_map(function(){...},split("\n",$s.$s.$s))), but significantly less verbose. I initially hadstr_padbut changed tosprintfbecause it's one byte shorter:'"0円".str_pad($$i++/$i&1?"0円":"",$i)."0円"'\$\endgroup\$primo– primo2018年03月13日 05:11:25 +00:00Commented Mar 13, 2018 at 5:11
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.
Japt, 23 bytes
_·£[X3XX3]Ãy c ·û}gQq)y
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;
}