Sierpinski carpet: Difference between revisions
Added Fōrmulæ entry
(Added Fōrmulæ entry) |
|||
(48 intermediate revisions by 25 users not shown) | |||
Line 48:
{{trans|Python}}
<
V carpet = [String(‘#’)]
L 1..n
Line 56:
R carpet.join("\n")
print(sierpinski_carpet(3))</
=={{header|Action!}}==
<syntaxhighlight lang="action!">BYTE FUNC InCarpet(BYTE x,y)
DO
IF x MOD 3=1 AND y MOD 3=1 THEN
RETURN (0)
FI
x==/3 y==/3
UNTIL x=0 AND y=0
OD
RETURN (1)
PROC DrawCarpet(INT x0 BYTE y0,depth)
BYTE i,x,y,size
size=1
FOR i=1 TO depth
DO size==*3 OD
FOR y=0 TO size-1
DO
FOR x=0 TO size-1
DO
IF InCarpet(x,y) THEN
Plot(x0+2*x,y0+2*y)
Plot(x0+2*x+1,y0+2*y)
Plot(x0+2*x+1,y0+2*y+1)
Plot(x0+2*x,y0+2*y+1)
FI
OD
OD
RETURN
PROC Main()
BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6
Graphics(8+16)
Color=1
COLOR1=$0C
COLOR2=$02
DrawCarpet(79,15,4)
DO UNTIL CH#$FF OD
CH=$FF
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sierpinski_carpet.png Screenshot from Atari 8-bit computer]
=={{header|Ada}}==
<
procedure Sierpinski_Carpet is
Line 134 ⟶ 182:
Divide_Square(Pattern, 3);
Print(Pattern);
end Sierpinski_Carpet;</
=={{header|ALGOL 68}}==
Line 141 ⟶ 189:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<
INT x := in x, y := in y;
BOOL out;
Line 169 ⟶ 217:
OD;
carpet(3)</
=={{header|ALGOL W}}==
{{Trans|C}}
As with the first C sample, uses pairs of characters for each point to give a squarer appreaence.
<
for depth := 3 do begin
integer dim;
Line 193 ⟶ 241:
end for_depth
end.
</syntaxhighlight>
{{out}}
<pre>
Line 225 ⟶ 273:
</pre>
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">carpet←{{⊃⍪/,⌿3 3⍴4 0 4\⊂⍵}⍣⍵⊢⍪'#'}</syntaxhighlight>
{{out}}
<pre>
carpet 0
#
carpet 1
###
# #
###
carpet 2
#########
# ## ## #
#########
### ###
# # # #
### ###
#########
# ## ## #
#########
carpet 3
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################</pre>
=={{header|AppleScript}}==
===Functional===
{{Trans|JavaScript}}
(ES5 Functional version)
<
-- sierpinskiCarpet :: Int -> [[Bool]]
Line 244 ⟶ 341:
-- inCarpet :: Int -> Int -> Bool
on inCarpet(x, y)
if (
true
else
not ((1 = x mod 3
(1 = y mod 3
inCarpet(x div 3, y div 3)
end if
Line 266 ⟶ 363:
on run
-- Carpets of orders 1, 2, 3
Line 279 ⟶ 376:
end run
-- showCarpet :: Int -> String
on showCarpet(n)
-- showRow :: [Bool] -> String
script showRow
Line 306 ⟶ 403:
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m
set
repeat with i from m to n
set end of xs to i
end repeat
xs
else
end if
end enumFromTo
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- map :: (a -> b) -> [a] -> [b]
Line 334 ⟶ 440:
end map
-- Lift 2nd class handler function into 1st class script wrapper
Line 352 ⟶ 451:
end script
end if
end mReturn</
{{Out}}
<pre>███
Line 399 ⟶ 498:
Or, defining the Sierpinski carpet weave more simply in terms of generic abstractions like '''zipWith''' and '''concatMap''':
<
on weave(xs)
script thread
Line 586 ⟶ 685:
end |λ|
end script
end zipWith</
{{Out}}
<pre>█████████
Line 597 ⟶ 696:
█ ██ ██ █
█████████</pre>
----
===Simple===
<syntaxhighlight lang="applescript">on SierpinskiCarpet(n, char)
if (n < 0) then return {}
script o
property lst1 : {char}
property lst2 : missing value
end script
set gap to space
repeat with k from 0 to (n - 1)
copy o's lst1 to o's lst2
repeat with i from 1 to (3 ^ k)
set str to o's lst1's item i
set o's lst1's item i to str & str & str
set o's lst2's item i to str & gap & str
end repeat
set o's lst1 to o's lst1 & o's lst2 & o's lst1
set gap to gap & gap & gap
end repeat
return join(o's lst1, linefeed)
end SierpinskiCarpet
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set txt to lst as text
set AppleScript's text item delimiters to astid
return txt
end join
return SierpinskiCarpet(3, "#")</syntaxhighlight>
{{output}}
<pre>###########################
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################</pre>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">inCarpet?: function [x,y][
X: x
Y: y
while [true][
if or? zero? X
zero? Y -> return true
if and? 1 = X % 3
1 = Y % 3 -> return false
X: X / 3
Y: Y / 3
]
]
carpet: function [n][
loop 0..dec 3^n 'i [
loop 0..dec 3^n 'j [
prints (inCarpet? i j)? -> "# "
-> " "
]
print ""
]
]
carpet 3</syntaxhighlight>
{{out}}
<pre># # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # #
# # # # # # # #
# # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # #</pre>
=={{header|Asymptote}}==
<
return
point(p, node + 1/3) + point(p, node - 1/3) - point(p, node);
Line 664 ⟶ 867:
size(9 inches, 6 inches);
carpet(q, 5);</
=={{header|AutoHotkey}}==
{{trans|Python}}
ahk [http://www.autohotkey.com/forum/topic44657-150.html discussion]
<
MsgBox % Carpet(A_Index)
Line 688 ⟶ 891:
Else x //= 3, y //= 3
Return "."
}</
=={{header|AWK}}==
<
#
# syntax: GAWK -f WSC.AWK [-v o={a|A}{b|B}] [-v X=anychar] iterations
Line 754 ⟶ 957:
}
exit(0)
}</
{{out|Sample}}
<pre>
Line 782 ⟶ 985:
</pre>
=={{header|
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="applesoftbasic"> 100 HGR
110 POKE 49234,0
120 DEF FN M(X) = X - INT (D * 3) * INT (X / INT (D * 3))
130 DE = 4
140 DI = 3 ^ DE * 3
150 FOR I = 0 TO DI - 1
160 FOR J = 0 TO DI - 1
170 FOR D = DI / 3 TO 0 STEP 0
180 IF INT ( FN M(I) / D) = 1 AND INT ( FN M(J) / D) = 1 THEN 200BREAK
190 D = INT (D / 3): NEXT D
200 HCOLOR= 3 * (D = 0)
210 HPLOT J,I
220 NEXT J
230 NEXT I</syntaxhighlight>
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">
function in_carpet(x, y)
while x <> 0 and y <> 0
if(x mod 3) = 1 and (y mod 3) = 1 then return False
y = int(y / 3): x = int(x / 3)
end while
return True
end function
Subroutine carpet(n)
k = (3^n)-1
for i = 0 to k
for j = 0 to k
if in_carpet(i, j) then print("#"); else print(" ");
next j
print
next i
end subroutine
for k = 0 to 3
print "N = "; k
call carpet(k)
print
next k
end
</syntaxhighlight>
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<
side% = 3^Order%
VDU 23,22,8*side%;8*side%;64,64,16,128
Line 801 ⟶ 1,050:
Y% DIV= 3
UNTIL X%=0 AND Y%=0
= TRUE</
[[File:sierpinski_carpet_bbc.gif]]
==={{header|Commodore BASIC}}===
<syntaxhighlight lang="basic">100 PRINT CHR$(147); CHR$(18); "**** SIERPINSKI CARPET ****"
110 PRINT
120 INPUT "ORDER"; O$
130 O = VAL(O$)
140 IF O < 1 THEN 120
150 PRINT
160 SZ = 3 ↑ O
170 FOR Y = 0 TO SZ - 1
180 :FOR X = 0 TO SZ - 1
190 : CH$ = "#"
200 : X1 = X
210 : Y1 = Y
220 : IF (X1 = 0) OR (Y1 = 0) THEN 290
230 : X3 = X1 - 3 * INT(X1 / 3)
240 : Y3 = Y1 - 3 * INT(Y1 / 3)
250 : IF (X3 = 1) AND (Y3 = 1) THEN CH$ = " ": GOTO 290
260 : X1 = INT(X1 / 3)
270 : Y1 = INT(Y1 / 3)
280 : GOTO 220
290 : PRINT CH$;
300 :NEXT X
310 PRINT
320 NEXT Y
</syntaxhighlight>
{{Out}}
All of the Commodore 8-bits have a 25-line display, so orders 3 and up scroll the top of the carpet off the screen. Orders 4+ additionally require at least 81 columns, and even a PET or C128 maxes out at 80. So we'll settle for an order-2 demonstration:
<pre>**** SIERPINSKI CARPET ****
ORDER? 2
#########
# ## ## #
#########
### ###
# # # #
### ###
#########
# ## ## #
#########
READY.</pre>
You can get a more graphical display by replacing the <tt>"#"</tt> with <tt>CHR$(18)+CHR$(186)+CHR$(146)</tt>; for maximum portability it should also output a <tt>CHR$(142)</tt> at some earlier point, maybe by adding it to the otherwise-empty <tt>PRINT</tt> statement on line 110. Then the filled-in squares become mostly-solid blocks with narrow gaps along their right and bottom edges so you can still count them when adjacent.
==={{header|FreeBASIC}}===
{{trans|QB64}}
====ASCII version====
<syntaxhighlight lang="freebasic">
Function in_carpet(x As Uinteger, y As Uinteger) As Boolean
While x <> 0 And y <> 0
If(x Mod 3) = 1 And (y Mod 3) = 1 Then Return False
y = y \ 3: x = x \ 3
Wend
Return True
End Function
Sub carpet(n As Uinteger)
Dim As Uinteger i, j, k = (3^n)-1
For i = 0 To k
For j = 0 To k
If in_carpet(i, j) Then Print("#"); Else Print(" ");
Next j
Print
Next i
End Sub
For k As Byte = 0 To 4
Print !"\nN ="; k
carpet(k)
Next k
Sleep
</syntaxhighlight>
{{trans|QB64}}
====Graphic version====
<syntaxhighlight lang="freebasic">
Screenres 500, 545, 8
Windowtitle "Sierpinski Carpet"
Cls
Color 1, 15
Sub carpet (x As Integer, y As Integer, size As Integer, order As Integer)
Dim As Integer ix, iy, isize, iorder, side, newX, newY
ix = x: iy = y: isize = size: iorder = order
Line (ix, iy)-(ix + isize - 1, iy + isize - 1), 1, BF
side = Int(isize / 3)
newX = ix + side
newY = iy + side
Line (newX, newY)-(newX + side - 1, newY + side - 1), 15, BF
iorder -= 1
If iorder >= 0 Then
carpet(newX - side, newY - side + 1, side, iorder)
carpet(newX, newY - side + 1, side, iorder)
carpet(newX + side, newY - side + 1, side, iorder)
carpet(newX + side, newY, side, iorder)
carpet(newX + side, newY + side, side, iorder)
carpet(newX, newY + side, side, iorder)
carpet(newX - side, newY + side, side, iorder)
carpet(newX - side, newY, side, iorder)
End If
End Sub
carpet(5, 20, 243, 0)
carpet(253, 20, 243, 1)
carpet(5, 293, 243, 2)
carpet(253, 293, 243, 3)
Sleep
</syntaxhighlight>
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 PROGRAM "Sierpins.bas"
110 LET O=3
120 LET SZ=3^O
130 FOR Y=0 TO SZ-1
140 FOR X=0 TO SZ-1
150 LET CH$=CHR$(159)
160 LET X1=X:LET Y1=Y
170 DO UNTIL X1=0
180 IF MOD(X1,3)=1 AND MOD(Y1,3)=1 THEN LET CH$=" ":EXIT DO
190 LET X1=INT(X1/3):LET Y1=INT(Y1/3)
200 LOOP
210 PRINT CH$;
220 NEXT
230 PRINT
240 NEXT </syntaxhighlight>
==={{header|Liberty BASIC}}===
{{works with|Just BASIC}}
<syntaxhighlight lang="lb">NoMainWin
WindowWidth = 508
WindowHeight = 575
Open "Sierpinski Carpets" For Graphics_nsb_nf As #g
#g "Down; TrapClose [halt]"
'labels
#g "Place 90 15;\Order 0"
#g "Place 340 15;\Order 1"
#g "Place 90 286;\Order 2"
#g "Place 340 286;\Order 3"
'carpets
Call carpet 5, 20, 243, 0
Call carpet 253, 20, 243, 1
Call carpet 5, 293, 243, 2
Call carpet 253, 293, 243, 3
#g "Flush"
Wait
[halt]
Close #g
End
Sub carpet x, y, size, order
#g "Color 0 0 128; BackColor 0 0 128"
#g "Place ";x;" ";y
#g "BoxFilled ";x+size-1;" ";y+size-1
#g "Color white; BackColor white"
side = Int(size/3)
newX = x+side
newY = y+side
#g "Place ";newX;" ";newY
#g "BoxFilled ";newX+side-1;" ";newY+side-1
order = order - 1
If order > -1 Then
Call carpet newX-side, newY-side+1, side, order
Call carpet newX, newY-side+1, side, order
Call carpet newX+side, newY-side+1, side, order
Call carpet newX+side, newY, side, order
Call carpet newX+side, newY+side, side, order
Call carpet newX, newY+side, side, order
Call carpet newX-side, newY+side, side, order
Call carpet newX-side, newY, side, order
End If
End Sub</syntaxhighlight>
==={{header|Minimal BASIC}}===
{{trans|BBC BASIC}}
Adapted to text mode. In some systems the screen scrolls for an order greater than 2.
{{works with|BASICA}}
{{works with|Commodore BASIC|3.5}}
{{works with|IS-BASIC}}
{{works with|Nascom ROM BASIC|4.7}}
<syntaxhighlight lang="basic" >
10 REM Sierpinski carpet
20 REM R - order; S - size.
30 LET R = 3
40 LET S = 3^R
50 FOR I = 0 TO S-1
60 FOR J = 0 TO S-1
70 LET X = J
80 LET Y = I
90 GOSUB 500
100 IF C = 1 THEN 130
110 PRINT " ";
120 GOTO 140
130 PRINT "*";
140 NEXT J
150 PRINT
160 NEXT I
170 END
490 REM Is (X,Y) in the carpet? Returns C = 0 (no) or C = 1 (yes).
500 LET C = 0
510 X3 = INT(X/3)
520 Y3 = INT(Y/3)
530 REM If (X mod 3 = 1) and (Y mod 3 = 1) then return
540 IF (X-X3*3)*(Y-Y3*3) = 1 THEN 600
550 LET X = X3
560 LET Y = Y3
570 IF X > 0 THEN 510
580 IF Y > 0 THEN 510
590 LET C = 1
600 RETURN
</syntaxhighlight>
==={{header|Nascom BASIC}}===
{{trans|BBC BASIC}}
{{works with|Nascom ROM BASIC|4.7}}
<syntaxhighlight lang="basic">
10 REM Sierpinski carpet
20 CLS
30 LET RDR=3
40 LET S=3^RDR
50 FOR I=0 TO S-1
60 FOR J=0 TO S-1
70 LET X=J
80 LET Y=I
90 GOSUB 300
100 IF C THEN SET(J,I)
110 NEXT J
120 NEXT I
130 REM ** Set up machine code INKEY$ command
140 IF PEEK(1)<>0 THEN RESTORE 410
150 DOKE 4100,3328:FOR A=3328 TO 3342 STEP 2
160 READ B:DOKE A,B:NEXT A
170 SCREEN 1,15
180 PRINT "Hit any key to exit.";
190 A=USR(0):IF A<0 THEN 190
200 CLS
210 END
290 REM ** Is (X,Y) in the carpet?
295 REM Returns C=0 (no) or C=1 (yes).
300 LET C=0
310 XD3=INT(X/3):YD3=INT(Y/3)
320 IF X-XD3*3=1 AND Y-YD3*3=1 THEN RETURN
330 LET X=XD3
340 LET Y=YD3
350 IF X>0 OR Y>0 THEN GOTO 310
360 LET C=1
370 RETURN
395 REM ** Data for machine code INKEY$
400 DATA 25055,1080,-53,536,-20665,3370,-5664,0
410 DATA 27085,14336,-13564,6399,18178,10927
420 DATA -8179,233
</syntaxhighlight>
==={{header|PureBasic}}===
{{trans|Python}}
<syntaxhighlight lang="purebasic">Procedure in_carpet(x,y)
While x>0 And y>0
If x%3=1 And y%3=1
ProcedureReturn #False
EndIf
y/3: x/3
Wend
ProcedureReturn #True
EndProcedure
Procedure carpet(n)
Define i, j, l=Pow(3,n)-1
For i=0 To l
For j=0 To l
If in_carpet(i,j)
Print("#")
Else
Print(" ")
EndIf
Next
PrintN("")
Next
EndProcedure</syntaxhighlight>
==={{header|QB64}}===
<syntaxhighlight lang="qb64">_Title "Sierpinski Carpet"
Screen _NewImage(500, 545, 8)
Cls , 15: Color 1, 15
'labels
_PrintString (96, 8), "Order 0"
_PrintString (345, 8), "Order 1"
_PrintString (96, 280), "Order 3"
_PrintString (345, 280), "Order 4"
'carpets
Call carpet(5, 20, 243, 0)
Call carpet(253, 20, 243, 1)
Call carpet(5, 293, 243, 2)
Call carpet(253, 293, 243, 3)
Sleep
System
Sub carpet (x As Integer, y As Integer, size As Integer, order As Integer)
Dim As Integer ix, iy, isize, iorder, side, newX, newY
ix = x: iy = y: isize = size: iorder = order
Line (ix, iy)-(ix + isize - 1, iy + isize - 1), 1, BF
side = Int(isize / 3)
newX = ix + side
newY = iy + side
Line (newX, newY)-(newX + side - 1, newY + side - 1), 15, BF
iorder = iorder - 1
If iorder >= 0 Then
Call carpet(newX - side, newY - side + 1, side, iorder)
Call carpet(newX, newY - side + 1, side, iorder)
Call carpet(newX + side, newY - side + 1, side, iorder)
Call carpet(newX + side, newY, side, iorder)
Call carpet(newX + side, newY + side, side, iorder)
Call carpet(newX, newY + side, side, iorder)
Call carpet(newX - side, newY + side, side, iorder)
Call carpet(newX - side, newY, side, iorder)
End If
End Sub</syntaxhighlight>
==={{header|Quite BASIC}}===
{{trans|BBC BASIC}}
In Quite BASIC, the point on the lower left on the canvas is 0, 0.
<syntaxhighlight lang="basic" >
10 REM Sierpinski carpet
20 CLS
30 LET R = 3
40 LET S = 1
50 FOR P = 1 TO R
60 LET S = 3 * S
70 NEXT P
80 REM Now S (size) is 3 to the power of R (order)
90 FOR I = 0 TO S - 1
100 FOR J = 0 TO S - 1
110 LET X = J
120 LET Y = I
130 GOSUB 300
140 IF C = 1 THEN PLOT J, I, "white"
150 NEXT J
160 NEXT I
170 END
300 REM Subroutine -- Is (X,Y) in the carpet?
310 REM Returns C = 0 (no) or C = 1 (yes).
320 LET C = 0
330 IF X % 3 = 1 AND Y % 3 = 1 THEN RETURN
340 LET X = FLOOR(X / 3)
350 LET Y = FLOOR(Y / 3)
360 IF X > 0 OR Y > 0 THEN GOTO 330
370 LET C = 1
380 RETURN
</syntaxhighlight>
==={{header|Sinclair ZX81 BASIC}}===
{{trans|BBC BASIC}}
Works with the unexpanded (1k RAM) ZX81. A screenshot of the output is [http://www.edmundgriffiths.com/zx81sierpcarpet.jpg here].
<syntaxhighlight lang="basic"> 10 LET O=3
20 LET S=3**O
30 FOR I=0 TO S-1
40 FOR J=0 TO S-1
50 LET X=J
60 LET Y=I
70 GOSUB 120
80 IF C THEN PLOT J,I
90 NEXT J
100 NEXT I
110 GOTO 190
120 LET C=0
130 IF X-INT (X/3)*3=1 AND Y-INT (Y/3)*3=1 THEN RETURN
140 LET X=INT (X/3)
150 LET Y=INT (Y/3)
160 IF X>0 OR Y>0 THEN GOTO 130
170 LET C=1
180 RETURN</syntaxhighlight>
==={{header|Tiny BASIC}}===
{{trans|Minimal BASIC}}
In some systems the screen scrolls for an order greater than 2.
{{works with|TinyBasic}}
<syntaxhighlight lang="basic">
10 REM SIERPINSKI CARPET
20 REM R - ORDER; S - SIZE.
30 LET R=3
40 LET S=1
50 LET P=1
60 IF P>R THEN GOTO 100
70 LET S=3*S
80 LET P=P+1
90 GOTO 60
100 REM NOW S IS 3 TO THE POWER OF R
110 LET I=0
120 LET J=0
130 LET X=J
140 LET Y=I
150 GOSUB 500
160 IF C=1 THEN GOTO 190
170 PRINT " ";
180 GOTO 200
190 PRINT "*";
200 LET J=J+1
210 IF J=S THEN GOTO 230
220 GOTO 130
230 PRINT
240 LET I=I+1
250 IF I=S THEN GOTO 270
260 GOTO 120
270 END
490 REM IS (X,Y) IN THE CARPET? RETURNS C = 0 (NO) OR C = 1 (YES).
500 LET C=0
510 W=X/3
520 Z=Y/3
530 IF X-W*3=1 IF Y-Z*3=1 THEN RETURN
540 LET X=W
550 LET Y=Z
560 IF X>0 THEN GOTO 510
570 IF Y>0 THEN GOTO 510
580 LET C=1
590 RETURN
</syntaxhighlight>
{{out}}
<pre>
***************************
* ** ** ** ** ** ** ** ** *
***************************
*** ****** ****** ***
* * * ** * * ** * * *
*** ****** ****** ***
***************************
* ** ** ** ** ** ** ** ** *
***************************
********* *********
* ** ** * * ** ** *
********* *********
*** *** *** ***
* * * * * * * *
*** *** *** ***
********* *********
* ** ** * * ** ** *
********* *********
***************************
* ** ** ** ** ** ** ** ** *
***************************
*** ****** ****** ***
* * * ** * * ** * * *
*** ****** ****** ***
***************************
* ** ** ** ** ** ** ** ** *
***************************
</pre>
==={{header|uBasic/4tH}}===
<syntaxhighlight lang="text">Input "Carpet order: ";n
l = (3^n) - 1
For i = 0 To l
For j = 0 To l
Push i,j
Gosub 100
If Pop() Then
Print "#";
Else
Print " ";
EndIf
Next
Print
Next
End
100 y = Pop(): x = Pop() : Push 1
Do While (x > 0) * (y > 0)
If (x % 3 = 1) * (y % 3 = 1) Then
Push (Pop() - 1)
Break
EndIf
y = y / 3
x = x / 3
Loop
Return</syntaxhighlight>
==={{header|VBA}}===
{{trans|Phix}}<syntaxhighlight lang="vb">Const Order = 4
Function InCarpet(ByVal x As Integer, ByVal y As Integer)
Do While x <> 0 And y <> 0
If x Mod 3 = 1 And y Mod 3 = 1 Then
InCarpet = " "
Exit Function
End If
x = x \ 3
y = y \ 3
Loop
InCarpet = "#"
End Function
Public Sub sierpinski_carpet()
Dim i As Integer, j As Integer
For i = 0 To 3 ^ Order - 1
For j = 0 To 3 ^ Order - 1
Debug.Print InCarpet(i, j);
Next j
Debug.Print
Next i
End Sub</syntaxhighlight>{{out}}
<pre>#################################################################################
# ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## #
#################################################################################
### ###### ###### ###### ###### ###### ###### ###### ###### ###
# # # ## # # ## # # ## # # ## # # ## # # ## # # ## # # ## # # #
### ###### ###### ###### ###### ###### ###### ###### ###### ###
#################################################################################
# ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## #
#################################################################################
######### ################## ################## #########
# ## ## # # ## ## ## ## ## # # ## ## ## ## ## # # ## ## #
######### ################## ################## #########
### ### ### ###### ### ### ###### ### ### ###
# # # # # # # ## # # # # # # ## # # # # # # #
### ### ### ###### ### ### ###### ### ### ###
######### ################## ################## #########
# ## ## # # ## ## ## ## ## # # ## ## ## ## ## # # ## ## #
######### ################## ################## #########
#################################################################################
# ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## #
#################################################################################
### ###### ###### ###### ###### ###### ###### ###### ###### ###
# # # ## # # ## # # ## # # ## # # ## # # ## # # ## # # ## # # #
### ###### ###### ###### ###### ###### ###### ###### ###### ###
#################################################################################
# ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## #
#################################################################################
########################### ###########################
# ## ## ## ## ## ## ## ## # # ## ## ## ## ## ## ## ## #
########################### ###########################
### ###### ###### ### ### ###### ###### ###
# # # ## # # ## # # # # # # ## # # ## # # #
### ###### ###### ### ### ###### ###### ###
########################### ###########################
# ## ## ## ## ## ## ## ## # # ## ## ## ## ## ## ## ## #
########################### ###########################
######### ######### ######### #########
# ## ## # # ## ## # # ## ## # # ## ## #
######### ######### ######### #########
### ### ### ### ### ### ### ###
# # # # # # # # # # # # # # # #
### ### ### ### ### ### ### ###
######### ######### ######### #########
# ## ## # # ## ## # # ## ## # # ## ## #
######### ######### ######### #########
########################### ###########################
# ## ## ## ## ## ## ## ## # # ## ## ## ## ## ## ## ## #
########################### ###########################
### ###### ###### ### ### ###### ###### ###
# # # ## # # ## # # # # # # ## # # ## # # #
### ###### ###### ### ### ###### ###### ###
########################### ###########################
# ## ## ## ## ## ## ## ## # # ## ## ## ## ## ## ## ## #
########################### ###########################
#################################################################################
# ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## #
#################################################################################
### ###### ###### ###### ###### ###### ###### ###### ###### ###
# # # ## # # ## # # ## # # ## # # ## # # ## # # ## # # ## # # #
### ###### ###### ###### ###### ###### ###### ###### ###### ###
#################################################################################
# ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## #
#################################################################################
######### ################## ################## #########
# ## ## # # ## ## ## ## ## # # ## ## ## ## ## # # ## ## #
######### ################## ################## #########
### ### ### ###### ### ### ###### ### ### ###
# # # # # # # ## # # # # # # ## # # # # # # #
### ### ### ###### ### ### ###### ### ### ###
######### ################## ################## #########
# ## ## # # ## ## ## ## ## # # ## ## ## ## ## # # ## ## #
######### ################## ################## #########
#################################################################################
# ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## #
#################################################################################
### ###### ###### ###### ###### ###### ###### ###### ###### ###
# # # ## # # ## # # ## # # ## # # ## # # ## # # ## # # ## # # #
### ###### ###### ###### ###### ###### ###### ###### ###### ###
#################################################################################
# ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## #
#################################################################################</pre>
==={{header|VBScript}}===
<syntaxhighlight lang="vbscript">Function InCarpet(i,j)
If i > 0 And j > 0 Then
Do While i > 0 And j > 0
If i Mod 3 = 1 And j Mod 3 = 1 Then
InCarpet = " "
Exit Do
Else
InCarpet = "#"
End If
i = Int(i / 3)
j = Int(j / 3)
Loop
Else
InCarpet = "#"
End If
End Function
Function Carpet(n)
k = 3^n - 1
x2 = 0
y2 = 0
For y = 0 To k
For x = 0 To k
x2 = x
y2 = y
WScript.StdOut.Write InCarpet(x2,y2)
Next
WScript.StdOut.WriteBlankLines(1)
Next
End Function
Carpet(WScript.Arguments(0))</syntaxhighlight>
{{out}}
<pre>F:\VBScript>cscript /nologo RosettaCode-Sierpinski_Carpet.vbs 3
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################</pre>
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">sub sp$(n)
local i, s$
for i = 1 to n
s$ = s$ + " "
next i
return s$
end sub
sub replace$(s$, cf$, cr$)
local i, p
do
i = instr(s$, cf$, p)
if not i break
mid$(s$, i, 1) = cr$
p = i
loop
return s$
end sub
sub foreach$(carpet$, p$, m)
local n, i, t$(1)
n = token(carpet$, t$(), ",")
for i = 1 to n
switch(m)
case 0: p$ = p$ + "," + t$(i) + t$(i) + t$(i) : break
case 1: p$ = p$ + "," + t$(i) + sp$(len(t$(i))) + t$(i) : break
default: error "Method not found!" : break
end switch
next i
return p$
end sub
sub sierpinskiCarpet$(n)
local carpet$, next$, i
carpet$ = "@"
for i = 1 to n
next$ = foreach$(carpet$, "")
next$ = foreach$(carpet$, next$, 1)
carpet$ = foreach$(carpet$, next$)
next i
return carpet$
end sub
print replace$(sierpinskiCarpet$(3), ",", "\n")</syntaxhighlight>
=={{header|Befunge}}==
Line 809 ⟶ 1,772:
The order, N, is specified by the first number on the stack. The upper limit is implementation dependent and is determined by the interpreter's cell size.
<
>p>40p"#"30g40g*!#v_$48*30g3%1-v^ >$55+,1v>
0 ^p03/3g03/3g04$_v#!*!-1%3g04!<^_^#- g00 <
^3g01p02:0p01_@#-g>#0,#02#:0#+g#11#g+#0:#<^</
=={{header|BQN}}==
<code>_decode</code> is a base conversion idiom from [https://mlochbaum.github.io/bqncrate/ BQNcrate].
<code>Carpet1</code> works based on the following condition:
<blockquote>Consider a coordinate grid in base 3. The holes in the carpet occur where
1) a trit in the x-coordinate is 1, and
2) the trit in the same position in the y-coordinate is also 1.</blockquote>
<syntaxhighlight lang="bqn">_decode ← {⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}
Carpet ← { # 2D Array method using ∾.
{∾(3‿3⥊4≠↕9)⊏⟨(≢𝕩)⥊0,𝕩⟩}⍟(𝕩-1) 1‿1⥊1
}
Carpet1 ← { # base conversion method, works in a single step.
¬{∨´𝕨∧○((-𝕨⌈○≠𝕩)⊸↑)𝕩}⌜˜2|3 _decode¨↕3⋆𝕩-1
}
•Show " #"⊏˜Carpet 4
•Show (Carpet ≡ Carpet1) 4</syntaxhighlight><syntaxhighlight lang="text">┌─
╵"###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################"
┘
1</syntaxhighlight>
[https://mlochbaum.github.io/BQN/try.html#code=X2RlY29kZSDihpAge+KMvfCdlZd84oyK4oiYw7fin5zwnZWX4o2fKOKGlTErwrfijIrwnZWX4ouG4oG8MeKMiOKKoil9CkNhcnBldCDihpAgeyAgIyAyRCBBcnJheSBtZXRob2QgdXNpbmcg4oi+LgogIHviiL4oM+KAvzPipYo04omg4oaVOSniio/in6go4omi8J2VqSnipYowLPCdlanin6l94o2fKPCdlaktMSkgMeKAvzHipYoxCn0KQ2FycGV0MSDihpAgeyAjIGJhc2UgY29udmVyc2lvbiBtZXRob2QsIHdvcmtzIGluIGEgc2luZ2xlIHN0ZXAuCiAgwqx74oiowrTwnZWo4oin4peLKCgt8J2VqOKMiOKXi+KJoPCdlakp4oq44oaRKfCdlal94oycy5wyfDMgX2RlY29kZcKo4oaVM+KLhvCdlaktMQp9CgrigKJTaG93ICIgIyLiio/LnENhcnBldCA0CuKAolNob3cgKENhcnBldCDiiaEgQ2FycGV0MSkgNAoK Try It!]
=={{header|Brainf***}}==
Double the first two prints for squarer output.
<syntaxhighlight lang="brainf***">input order and print the associated Sierpinski carpet
orders over 5 require larger cell sizes
+++>>+[[-]>[-],[+[-----------[>[-]++++++[<------>-]<--<<[->>++++++++++<<]>>[-<<+
>>]<+>]]]<]<<[>>+<<-]+>[>>[-]>[-]<<<<[>>>>+<<<<-]>>>>[<<[<<+>>>+<-]>[<+>-]>-]<<<
-]>[-]<<[>+>+<<-]>>[<<+>>-]<[<[>>+>+<<<-]>>>[<<<+>>>-]<[<[>>+>>>+<<<<<-]>>[<<+>>
-]<[>>+>>>+<<<<<-]>>[<<+>>-]>>->-<<<<+[[>+>+<<-]>[<+>-]>[>[>>+>+<<<-]>>>[<<<+>>>
-]+++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[-]<->+<[>-]>[<<<+>>>->]<<[-]<<<[>>+>+
<<<-]>>>[<<<+>>>-]+++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[-]<->+<[>-]>[<<<+>>>-
>]<<[-]<<<[>[>+<-]<-]>[-]>[<<+>>-]<<[>>++++[<++++++++>-]<.[-]<<[-]<[-]<<<->>>>>-
]<<<-]<<[>+>+<<-]>[<+>-]>[>[>>+<<-]>>>+++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>[-]
>[<<<<<+>>>>>-]<<<+++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>[-]>[<<<+>>>-]<<<<[>>+>
+<<<-]>>>[<<<+>>>-]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[>[>+<-]<-]>[-]+>[[-]<->]<[->+<]>
[<<+>>-]<<[>>+++++[<+++++++>-]<.[-]<<[-]<[-]<<<->>>>>-]<<<-]<<]<-]++++++++++.[-]
<-]</syntaxhighlight>
{{out}}
<pre>###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################</pre>
=={{header|C}}==
If you write coordinates of any point on the carpet in base 3, the pixel
<
int main()
Line 836 ⟶ 1,898:
return 0;
}</
<
#include <stdlib.h>
#include <string.h>
Line 929 ⟶ 1,991:
// fclose(f);
return 0;
}</
Recursive version:
<
#include <stdlib.h>
Line 1,011 ⟶ 2,073:
return 0;
}</
=={{header|C sharp|C#}}==
{{trans|Ruby}}
{{works with|C sharp|C#|3.0+}}
<
using System.Collections.Generic;
using System.Linq;
Line 1,039 ⟶ 2,101:
Console.WriteLine(s);
}
}</
=={{header|C++}}==
Performance focused variant (about 7x faster than the div/mod solutions at AMD Ryzen 7 4800H)
<syntaxhighlight lang="cpp">// contributed to rosettacode.org by Peter Helcmanovsky
// BCT = Binary-Coded Ternary: pairs of bits form one digit [0,1,2] (0b11 is invalid digit)
#include <cstdint>
#include <cstdlib>
#include <cstdio>
static constexpr int32_t bct_low_bits = 0x55555555;
static int32_t bct_decrement(int32_t v) {
--v; // either valid BCT (v-1), or block of bottom 0b00 digits becomes invalid 0b11
return v ^ (v & (v>>1) & bct_low_bits); // fix all 0b11 to 0b10 (digit "2")
}
int main (int argc, char *argv[])
{
// parse N from first argument, if no argument, use 3 as default value
const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;
// check for valid N (0..9) - 16 requires 33 bits for BCT form 1<<(n*2) => hard limit
if (n < 0 || 9 < n) { // but N=9 already produces 370MB output
std::printf("N out of range (use 0..9): %ld\n", long(n));
return 1;
}
const int32_t size_bct = 1<<(n*2); // 3**n in BCT form (initial value for loops)
// draw the carpet, two nested loops counting down in BCT form of values
int32_t y = size_bct;
do { // all lines loop
y = bct_decrement(y); // --Y (in BCT)
int32_t x = size_bct;
do { // line loop
x = bct_decrement(x); // --X (in BCT)
// check if x has ternary digit "1" at same position(s) as y -> output space (hole)
std::putchar((x & y & bct_low_bits) ? ' ' : '#');
} while (0 < x);
std::putchar('\n');
} while (0 < y);
return 0;
}</syntaxhighlight>
[[File:sierpinski_cpp.png|300px]]
<
#include <windows.h>
#include <math.h>
Line 1,166 ⟶ 2,270:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
=={{header|Clojure}}==
{{trans|Scheme}}
<
(:require [clojure.contrib.math :as math]))
Line 1,189 ⟶ 2,293:
(if (in-carpet? x y) "*" " ")))))))
(println (carpet 3))</
=={{header|Common Lisp}}==
This solution works by printing a square of # except where both of the coordinates of a cell contain a 1 in the same digit position in base 3. For example, the central empty square has a 1 in the highest base-3 digit of all its cells, and the smallest empty squares have 1s in the lowest base-3 digit.
<
(let ((size (expt 3 order)))
(flet ((trinary (x) (format nil "~3,vR" order x))
Line 1,202 ⟶ 2,306:
(princ (if (some #'ones (trinary i) (trinary j))
" "
"#")))))))</
=={{header|Crystal}}==
{{trans|Ruby}}
<
carpet = ["#"]
n.times do
Line 1,216 ⟶ 2,320:
end
5.times{ |i| puts "\nN=#{i}"; sierpinski_carpet(i).each { |row| puts row } }</
{{out}}
Line 1,354 ⟶ 2,458:
=={{header|D}}==
{{trans|Python}}
<
auto sierpinskiCarpet(in int n) pure nothrow @safe {
Line 1,367 ⟶ 2,471:
void main() {
3.sierpinskiCarpet.writeln;
}</
More functional style:
<
auto nextCarpet(in string[] c) pure nothrow {
Line 1,382 ⟶ 2,486:
.front
.binaryReverseArgs!writefln("%-(%s\n%)");
}</
A more direct and efficient version:
<
char[][] sierpinskiCarpet(in size_t n) pure nothrow @safe {
Line 1,411 ⟶ 2,515:
writefln("%-(%s\n%)", 3.sierpinskiCarpet);
7.sierpinskiCarpet.length.writeln;
}</
=={{header|Delphi}}==
Line 1,418 ⟶ 2,522:
=={{header|DWScript}}==
{{Trans|Java}}
<
begin
while (x<>0) and (y<>0) do begin
Line 1,445 ⟶ 2,549:
end;
Carpet(3);</
Line 1,451 ⟶ 2,555:
=={{header|E}}==
{{trans|Python}}
<
while (x > 0 && y > 0) {
if (x %% 3 <=> 1 && y %% 3 <=> 1) {
Line 1,469 ⟶ 2,573:
println()
}
}</
=={{header|EasyLang}}==
[https://easylang.dev/ide/#cod=dY+xDsIwDER3f8XtEcEQlQ3+JZhCEYVUKSDo1xOHIDGklgffnf2iDDEIxMcBL7wxTrCwBOAanm2yFmotsU7Zb9Q0tnJXOU6qzkedd2DbqEzVYfvddsUoL2RGQXXVqO6ayoGZZ5kqy8yz6pj/XUuW9l4upxgetwOYmaRvfSQJfYjYOEf5qmHtFXP+/Ac= Run it]
<syntaxhighlight lang="easylang">
proc carp x y sz . .
move x - sz / 2 y - sz / 2
rect sz sz
if sz > 0.5
h = sz / 3
carp x - sz y - sz h
carp x - sz y h
carp x - sz y + sz h
carp x + sz y - sz h
carp x + sz y h
carp x + sz y + sz h
carp x y - sz h
carp x y + sz h
.
.
background 000
clear
color 633
carp 50 50 100 / 3
</syntaxhighlight>
=={{header|Elixir}}==
{{trans|Ruby}}
<
def sierpinski_carpet(n), do: sierpinski_carpet(n, ["#"])
Line 1,488 ⟶ 2,618:
IO.puts "\nN=#{n}"
Enum.each(RC.sierpinski_carpet(n), fn line -> IO.puts line end)
end)</
{{out}}
Line 1,542 ⟶ 2,672:
=={{header|Erlang}}==
<
-module(carpet).
-export([main/0]).
Line 1,561 ⟶ 2,691:
carpet(X div 3, Y div 3)
end.
</syntaxhighlight>
{{out}}
<pre>***************************
Line 1,594 ⟶ 2,724:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM SIERP_CARPET
Line 1,626 ⟶ 2,756:
CLOSE(1)
END PROGRAM
</syntaxhighlight>
Output is redirected to file OUT.PRN: you can change this to SCRN: to screen or "LPTx:" for a parallel printer.
Output taken from OUT.PRN file:
Line 1,661 ⟶ 2,791:
=={{header|Euphoria}}==
<
include std/math.e
Line 1,688 ⟶ 2,818:
puts(1,'\n')
end for
</syntaxhighlight>
=={{header|Excel}}==
===LAMBDA===
Binding the names SIERPCARPET, SIERPWEAVE, and SHOWBLOCKS to the following lambda expressions in the Name Manager of the Excel WorkBook:
(See [https://www.microsoft.com/en-us/research/blog/lambda-the-ultimatae-excel-worksheet-function/ LAMBDA: The ultimate Excel worksheet function])
{{Works with|Office 365 betas 2021}}
<syntaxhighlight lang="lisp">SHOWBLOCKS
=LAMBDA(xs,
IF(0 <> xs, "█", " ")
)
SIERPCARPET
=LAMBDA(n,
APPLYN(n)(
SIERPWEAVE
)(1)
)
SIERPWEAVE
=LAMBDA(xs,
LET(
triple, REPLICATECOLS(3)(xs),
gap, LAMBDA(x, IF(x, 0, 0))(xs),
middle, APPENDCOLS(
APPENDCOLS(xs)(gap)
)(xs),
APPENDROWS(
APPENDROWS(triple)(middle)
)(triple)
)
)</syntaxhighlight>
and also assuming the following generic bindings in the Name Manager for the WorkBook:
<syntaxhighlight lang="lisp">APPENDCOLS
=LAMBDA(xs,
LAMBDA(ys,
LET(
nx, COLUMNS(xs),
ny, COLUMNS(ys),
colIndexes, SEQUENCE(1, nx + ny),
rowIndexes, SEQUENCE(MAX(ROWS(xs), ROWS(ys))),
IFERROR(
IF(nx < colIndexes,
INDEX(ys, rowIndexes, colIndexes - nx),
INDEX(xs, rowIndexes, colIndexes)
),
NA()
)
)
)
)
APPENDROWS
=LAMBDA(xs,
LAMBDA(ys,
LET(
nx, ROWS(xs),
rowIndexes, SEQUENCE(nx + ROWS(ys)),
colIndexes, SEQUENCE(
1,
MAX(COLUMNS(xs), COLUMNS(ys))
),
IFERROR(
IF(rowIndexes <= nx,
INDEX(xs, rowIndexes, colIndexes),
INDEX(ys, rowIndexes - nx, colIndexes)
),
NA()
)
)
)
)
APPLYN
=LAMBDA(n,
LAMBDA(f,
LAMBDA(x,
IF(0 < n,
APPLYN(n - 1)(f)(
f(x)
),
x
)
)
)
)
REPLICATECOLS
=LAMBDA(n,
LAMBDA(xs,
LET(
nCols, COLUMNS(xs),
h, n * nCols,
ixs, SEQUENCE(ROWS(xs), h, 0, 1),
INDEX(
xs,
1 + QUOTIENT(ixs, h),
1 + MOD(ixs, nCols)
)
)
)
)</syntaxhighlight>
{{Out}}
{| class="wikitable"
|-
|||style="text-align:right; font-family:serif; font-style:italic; font-size:120%;"|fx
! colspan="11" style="text-align:left; vertical-align: bottom; font-family:Arial, Helvetica, sans-serif !important;"|=SHOWBLOCKS(SIERPCARPET(A2))
|- style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff;"
|
| A
| B
| C
| D
| E
| F
| G
| H
| I
| J
| K
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 1
| style="text-align:left" | Level
| colspan="9" style="text-align:left" | Sierpinski carpet
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 2
| style="text-align:left" | 0
| style="text-align:left; background-color:#cbcefb" | █
|
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 3
|
|
|
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 4
| style="text-align:left" | 1
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 5
|
| style="text-align:left" | █
| style="text-align:left" |
| style="text-align:left" | █
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 6
|
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 7
|
|
|
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 8
| style="text-align:left" | 2
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 9
|
| style="text-align:left" | █
| style="text-align:left" |
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" |
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" |
| style="text-align:left" | █
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 10
|
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 11
|
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" |
| style="text-align:left" |
| style="text-align:left" |
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 12
|
| style="text-align:left" | █
| style="text-align:left" |
| style="text-align:left" | █
| style="text-align:left" |
| style="text-align:left" |
| style="text-align:left" |
| style="text-align:left" | █
| style="text-align:left" |
| style="text-align:left" | █
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 13
|
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" |
| style="text-align:left" |
| style="text-align:left" |
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 14
|
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 15
|
| style="text-align:left" | █
| style="text-align:left" |
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" |
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" |
| style="text-align:left" | █
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 16
|
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
| style="text-align:left" | █
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 17
|
|
|
|
|
|
|
|
|
|
|
|}
=={{header|F_Sharp|F#}}==
{{trans|OCaml}}{{trans|Ruby}}
<
let blank x = new String(' ', String.length x)
Line 1,707 ⟶ 3,185:
aux n ["#"]
List.iter (printfn "%s") (sierpinskiCarpet 3)</
=={{header|Factor}}==
The order n sierpinski carpet is the [[Kronecker product| Kronecker product]] of order n-1 and order 1.
<
: sierpinski ( n -- )
Line 1,717 ⟶ 3,195:
curry times [ 1 = "#" " " ? ] matrix-map simple-table. ;
3 sierpinski</
=={{header|Fan}}==
<syntaxhighlight lang="fan">**
** Generates a square Sierpinski gasket
**
Line 1,759 ⟶ 3,237:
carpet(4)
}
}</
=={{header|Fennel}}==
<syntaxhighlight lang="fennel">(fn in-carpet? [x y]
(if
(or (= 0 x) (= 0 y)) true
(and (= 1 (% x 3)) (= 1 (% y 3))) false
(in-carpet? (// x 3) (// y 3))))
(fn make-carpet [size]
(for [y 0 (- (^ 3 size) 1)]
(for [x 0 (- (^ 3 size) 1)]
(if (in-carpet? x y)
(io.write "#")
(io.write " ")))
(io.write "\n")))
(for [i 0 3]
(make-carpet i)
(print))</syntaxhighlight>
=={{header|Forth}}==
{{trans|Fan}}
<
: 1? over 3 mod 1 = ; ( n1 n2 -- n1 n2 f)
: 3/ 3 / swap ; ( n1 n2 -- n2/3 n1)
Line 1,778 ⟶ 3,275:
;
cr 4 carpet</
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{trans|Python}}
<
implicit none
Line 1,824 ⟶ 3,321:
end do
end subroutine Carpet
end program Sierpinski_carpet</
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/L-system}}
'''Solution'''
It can be done using an [[wp:L-system|L-system]]. There are generic functions written in Fōrmulæ to compute an L-system in the page [[L-system#Fōrmulæ | L-system]].
The program that creates a Sierpiński carpet is:
[[File:Fōrmulæ - L-system - Sierpiński carpet 01.png]]
[[File:Fōrmulæ - L-system - Sierpiński carpet 02.png]]
=={{header|Gnuplot}}==
Line 1,834 ⟶ 3,345:
[[File:SC5gp1.png|right|thumb|Output SC5gp1.png]]
<
## SCff.gp 1/14/17 aev
## Plotting Sierpinski carpet fractal.
Line 1,846 ⟶ 3,357:
ttl = "Sierpinski carpet fractal, v.#1"
load "plotff.gp"
</
{{Output}}
<pre>
Line 1,862 ⟶ 3,373:
;plotscf.gp:
<
## plotscf.gp 12/7/16 aev
## Plotting a Sierpinski carpet fractal to the png-file.
Line 1,883 ⟶ 3,394:
plot -100
set output
</syntaxhighlight>
;plotscf1.gp:
<
## plotscf1.gp 12/7/16 aev
## Plotting a Sierpinski carpet fractal to the png-file.
Line 1,914 ⟶ 3,425:
splot sc(x,y)
set output
</syntaxhighlight>
;Plotting v.#2 and v.#3:
<
## pSCF.gp 12/7/16 aev
## Plotting Sierpinski carpet fractals.
Line 1,938 ⟶ 3,449:
filename = "SCF31gp"; ttl = "Sierpinski carpet fractal #31, ord ".ord;
load "plotscf1.gp"
</syntaxhighlight>
{{Output}}
<pre>
Line 1,947 ⟶ 3,458:
=={{header|Go}}==
Variable "grain" shown set to "#" here, but it's fun to experiment with other values. "|", ". ", "[]", "___", "██", "░░"...
<
import (
Line 1,974 ⟶ 3,485:
fmt.Println(r)
}
}</
=={{header|Groovy}}==
Solution, uses list-indexing of base 3 string representation:
<
def sierpinskiCarpet = { int order ->
Line 1,996 ⟶ 3,507:
}
sb.toString()
}</
Test Program:
<
{{out}}
<pre style="height:30ex;overflow:scroll;">
Line 2,128 ⟶ 3,639:
=={{header|Haskell}}==
<
inCarpet 0 _ = True
inCarpet _ 0 = True
Line 2,143 ⟶ 3,654:
printCarpet :: Int -> IO ()
printCarpet = mapM_ putStrLn . carpet</
{{trans|Ruby}}
<
nextCarpet carpet = border ++ map f carpet ++ border
where border = map (concat . replicate 3) carpet
Line 2,155 ⟶ 3,666:
main :: IO ()
main = mapM_ putStrLn $ sierpinskiCarpet 3</
Seems not very different from version above,
<
main = putStr . unlines . (!!3) $ iterate next ["#"]
Line 2,170 ⟶ 3,681:
where
(!) = zipWith (++)
center = map (map $ const ' ') block</
which we could also read as:
<
carpet = unlines . (iterate weave ["██"] !!)
weave :: [String] -> [String]
weave xs =
let f = zipWith (
g = flip f
in concatMap
(g xs . f xs)
[ xs,
fmap (const ' ') <$> xs,
xs
]
main :: IO ()
main = mapM_ (putStrLn . carpet) [0 .. 2]</
Or more applicatively, representing different phases of the weaving shuttle as <*> and <>:
<syntaxhighlight lang="haskell">carpet :: Int -> String
carpet = unlines . (iterate weave ["██"] !!)
weave :: [String] -> [String]
weave =
let thread = zipWith (<
in ( (>>=)
<*> ( ((:) . fmap (fmap (const ' ')))
<*> return
)
)
)
<*> ((.) <$> flip thread <*> thread)
main :: IO ()
main = mapM_ (putStrLn . carpet) [0 .. 2]</
{{Out}}
<pre>██
Line 2,221 ⟶ 3,741:
{{works with|GHC}}
{{libheader|diagrams}}
<
import Control.Monad.Trans (lift)
import Data.Colour (Colour)
Line 2,284 ⟶ 3,804:
cell :: Colour Float -> Diagram Cairo R2
cell color = square 1 # lineWidth 0 # fillColor color
</syntaxhighlight>
=={{header|Icon}} and {{header|Unicon}}==
The IsFilled procedure is a translation of Java and Python.
<
procedure main(A)
Line 2,311 ⟶ 3,831:
}
return
end</
{{out}}
<pre>Carpet order= 2
Line 2,327 ⟶ 3,847:
=={{header|Io}}==
Based on Python translation of Ruby.
<
carpet := list("@")
n repeat(
Line 2,339 ⟶ 3,859:
)
sierpinskiCarpet(3) println</
{{out}}
<pre>@@@@@@@@@@@@@@@@@@@@@@@@@@@
Line 2,368 ⟶ 3,888:
@ @@ @@ @@ @@ @@ @@ @@ @@ @
@@@@@@@@@@@@@@@@@@@@@@@@@@@</pre>
=={{header|J}}==
Like the sierpinski triangle, the carpet is straightforward to produce in J. One approach is based on repeatedly putting a function's argument in a box, forming 9 copies of it into a 3 by 3 array, and then replacing the contents of the middle box with blanks:
<
(a:(<1;1)}3 3$<)^:N' '</
But N=:3 is big, so let's use N=:2
<
(a:(<1;1)}3 3$<)^:N' '
┌─────────────┬─────────────┬─────────────┐
Line 2,428 ⟶ 3,922:
││ │ │ │││ │ │ │││ │ │ ││
│└───┴───┴───┘│└───┴───┴───┘│└───┴───┴───┘│
└─────────────┴─────────────┴─────────────┘</
or another way of getting the same image starts with the boolean array
<
1 1 1
1 0 1
1 1 1</
<
((#:7 5 7){_2{.<)^:N' '
┌─────────────┬─────────────┬─────────────┐
Line 2,462 ⟶ 3,956:
││ │ │ │││ │ │ │││ │ │ ││
│└───┴───┴───┘│└───┴───┴───┘│└───┴───┴───┘│
└─────────────┴─────────────┴─────────────┘</
That said, using spaces and '#' characters takes a bit more work. One approach would be:
<syntaxhighlight lang
scarp=:{{' #'{~(#:7 5 7) ,/@(1 3 ,/"2@|: */)^:
scarp 2
#########
# ## ## #
Line 2,476 ⟶ 3,971:
# ## ## #
#########
scarp 3
###########################
# ## ## ## ## ## ## ## ## #
Line 2,504 ⟶ 3,999:
###########################
# ## ## ## ## ## ## ## ## #
###########################</
Here, what we are doing is forming a tensor product of our #:7 5 7 boolean array with our argument and then collapsing two of the dimensions so they line up right. Our starting argument is the 1 by 1 array with the value 1. Once we have repeated this process enough times, we select spaces for our zeros and pound signs for our 1s.
Line 2,510 ⟶ 4,005:
=={{header|Java}}==
{{trans|Python}}
<
while (x!=0 && y!=0) {
if (x % 3 == 1 && y % 3 == 1)
Line 2,528 ⟶ 4,023:
System.out.println();
}
}</
===Animated version===
[[File:sierpinski_carpet_java.png|300px|thumb|right]]
{{works with|java|8}}
<
import java.awt.event.ActionEvent;
import javax.swing.*;
Line 2,591 ⟶ 4,086:
});
}
}</
=={{header|JavaScript}}==
Line 2,601 ⟶ 4,096:
{{works with|Firefox|1.5+}}
This version also produces a "graphic" via HTML and CSS.
<
<html>
<head>
Line 2,672 ⟶ 4,167:
</body>
</html></
{{out}}
[[File:Sierpinski carpet js.png]]
Line 2,681 ⟶ 4,176:
Creates an N by N array of boolean values, which are mapped to lines of characters for output.
<
// as lines of text.
Line 2,736 ⟶ 4,231:
}).join('\n');
}).join('\n\n');</
Output (orders 1, 2 and 3):
Line 2,783 ⟶ 4,278:
===ES6===
<
'use strict';
Line 2,825 ⟶ 4,320:
return [1, 2, 3]
.map(sierpinskiCarpet);
})();</
{{Out}}
Line 2,873 ⟶ 4,368:
Or, defining the Sierpinksi carpet weave declaratively, in terms of '''zipWith''' and '''concatMap''':
<
'use strict';
Line 2,964 ⟶ 4,459:
// MAIN -----------------------------------------------
return main();
})();</
{{Out}}
<pre>█████████
Line 2,983 ⟶ 4,478:
This is like a "for" loop within a "for" loop in C-like languages, because range(0;n) generates a stream of n integers beginning at 0. The -1 is used to signal that a newline character is required.
<syntaxhighlight lang="jq">
def inCarpet(x; y):
x as $x | y as $y |
Line 3,001 ⟶ 4,496:
carpet(3)</
<
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
x = fill(token, 1, 1)
for _ in 1:n
Line 3,022 ⟶ 4,517:
end
sierpinski(2, "#") |> printsierpinski</
=={{header|Kotlin}}==
Line 3,028 ⟶ 4,523:
===ASCII Art Version===
{{trans|Python}}
<
fun inCarpet(x: Int, y: Int): Boolean {
Line 3,049 ⟶ 4,544:
}
fun main(args: Array<String>) = carpet(3)</
{{out}}
Line 3,084 ⟶ 4,579:
===Graphical Animated Version===
{{trans|Java}}
<
import java.awt.*
Line 3,140 ⟶ 4,635:
f.isVisible = true
}
}</
=={{header|Lambdatalk}}==
<syntaxhighlight lang="Scheme">
{def sierpinsky
{def sierpinsky.r
{lambda {:n :w}
{if {= :n 0}
then :w
else {sierpinsky.r
{- :n 1}
{S.map {lambda {:x} :x:x:x} :w}
{S.map {lambda {:x} :x{S.replace ■ by o in :x}:x} :w}
{S.map {lambda {:x} :x:x:x} :w} }}}}
{lambda {:n}
{h2 n=:n}{S.replace o by space in
{S.replace \s by {div} in
{sierpinsky.r :n ■}}}}}
-> sierpinsky
{S.map sierpinsky 0 1 2 3}
->
S0
■
S1
■■■
■ ■
■■■
S2
■■■■■■■■■
■ ■■ ■■ ■
■■■■■■■■■
■■■ ■■■
■ ■ ■ ■
■■■ ■■■
■■■■■■■■■
■ ■■ ■■ ■
■■■■■■■■■
S3
■■■■■■■■■■■■■■■■■■■■■■■■■■■
■ ■■ ■■ ■■ ■■ ■■ ■■ ■■ ■■ ■
■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■■ ■■■■■■ ■■■■■■ ■■■
■ ■ ■ ■■ ■ ■ ■■ ■ ■ ■
■■■ ■■■■■■ ■■■■■■ ■■■
■■■■■■■■■■■■■■■■■■■■■■■■■■■
■ ■■ ■■ ■■ ■■ ■■ ■■ ■■ ■■ ■
■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■■■■■■■■ ■■■■■■■■■
■ ■■ ■■ ■ ■ ■■ ■■ ■
■■■■■■■■■ ■■■■■■■■■
■■■ ■■■ ■■■ ■■■
■ ■ ■ ■ ■ ■ ■ ■
■■■ ■■■ ■■■ ■■■
■■■■■■■■■ ■■■■■■■■■
■ ■■ ■■ ■ ■ ■■ ■■ ■
■■■■■■■■■ ■■■■■■■■■
■■■■■■■■■■■■■■■■■■■■■■■■■■■
■ ■■ ■■ ■■ ■■ ■■ ■■ ■■ ■■ ■
■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■■ ■■■■■■ ■■■■■■ ■■■
■ ■ ■ ■■ ■ ■ ■■ ■ ■ ■
■■■ ■■■■■■ ■■■■■■ ■■■
■■■■■■■■■■■■■■■■■■■■■■■■■■■
■ ■■ ■■ ■■ ■■ ■■ ■■ ■■ ■■ ■
■■■■■■■■■■■■■■■■■■■■■■■■■■■
</syntaxhighlight>
=={{header|Lua}}==
An excellent opportunity to show off tail calls, so, recursively..
<
print("n = " .. n)
local function S(x, y)
Line 3,162 ⟶ 4,728:
for n = 0, 4 do
carpet(n, function(b) return b and "■ " or " " end)
end</
{{out}}
<pre style="font-size:50%">n = 0
Line 3,295 ⟶ 4,861:
■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■</pre>
=={{header|
Replace a empty spot with a 3x3 empty matrix, and replace a full spot with an empty spot surrounded by 8 full spots:
<
empty={{0,0,0},{0,0,0},{0,0,0}}
n=3;
Grid[Nest[ArrayFlatten[#/.{0->empty,1->full}]&,{{1}},n]//.{0->" ",1->"#"}]</
=={{header|MATLAB}}==
<
c = string('#');
for k = 1 : n
c = [c + c + c, c + c.replace('#', ' ') + c, c + c + c];
end
disp(c.join(char(10)))</
{{out}}
<pre>###########################
Line 3,386 ⟶ 4,905:
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols nobinary
Line 3,432 ⟶ 4,951:
end edge
return isFilled
</syntaxhighlight>
{{out}}
Sample shown with order "2".
Line 3,449 ⟶ 4,968:
=={{header|Nim}}==
{{trans|Python}}
<
proc inCarpet(x, y: int): bool =
Line 3,468 ⟶ 4,987:
echo()
carpet(3)</
{{out}}
<pre>* * * * * * * * * * * * * * * * * * * * * * * * * * *
Line 3,500 ⟶ 5,019:
=={{header|Objeck}}==
{{trans|Python}}
<
function : Main(args : String[]) ~ Nil {
Carpet(3);
Line 3,528 ⟶ 5,047:
};
}
}</
=={{header|OCaml}}==
<
if x = 0 || y = 0 then true
else if x mod 3 = 1 && y mod 3 = 1 then false
Line 3,548 ⟶ 5,067:
done;
print_newline ()
done</
{{trans|Ruby}}
<
List.map (fun x -> x ^ x ^ x) carpet @
List.map (fun x -> x ^ String.make (String.length x) ' ' ^ x) carpet @
Line 3,563 ⟶ 5,082:
let () =
List.iter print_endline (sierpinskiCarpet 3)</
=={{header|Oforth}}==
<
| dim i j k |
3 n pow ->dim
Line 3,581 ⟶ 5,100:
]
printcr
] ;</
=={{header|Order}}==
Since the C Preprocessor cannot print newlines, this Order program produces a string for a simple C program to print:
<
#define ORDER_PP_DEF_8in_carpet ORDER_PP_FN( \
Line 3,623 ⟶ 5,142:
printf(ORDER_PP( 8carpet_to_string(8carpet(3)) ));
return 0;
}</
(This example may take a long time to compile: change the <code>8carpet</code> parameter to 2 for a much quicker compile time and a smaller graphic.)
Line 3,632 ⟶ 5,151:
=={{header|Oz}}==
<
%% A carpet is a list of lines.
fun {NextCarpet Carpet}
Line 3,653 ⟶ 5,172:
in
%% print all lines of the Sierpinski carpet of order 3
{ForAll {Nth SierpinskiCarpets 4} System.showInfo}</
=={{header|PARI/GP}}==
Line 3,663 ⟶ 5,182:
===Plotting helper functions===
Note: wrtmat() can be found here on RC [[Brownian_tree#PARI.2FGP| Brownian tree page]].
<
\\ Improved simple plotting using matrix mat (color and scaling added).
\\ Matrix should be filled with 0/1. 7/6/16 aev
Line 3,695 ⟶ 5,214:
x\=3; y\=3;);\\wend
}
</syntaxhighlight>
===Sierpinski carpet fractal.===
<
\\ Sierpinski carpet fractal (n - order, clr - color, dfn - data file name)
\\ 6/10/16, upgraded 11/29/16 aev
Line 3,718 ⟶ 5,237:
{pSierpinskiC(5,,"c:\\pariData\\SC5.dat");
iPlotV2("c:\\pariData\\SC5.dat",10);} \\ SierpC5a.png, color - dark-green
</
{{Output}}
Line 3,760 ⟶ 5,279:
=={{header|Pascal}}==
<
uses
Line 3,812 ⟶ 5,331:
Carpet(3);
{$IFNDEF UNIX} readln; {$ENDIF}
end.</
{{out}}
<pre>:> ./SierpinskiCarpet
Line 3,845 ⟶ 5,364:
=={{header|Perl}}==
<
@c = (map($_ x 3, @c), map($_.(' ' x length).$_, @c), map($_ x 3, @c))
for 1 .. 3;
print join("\n", @c), "\n";</
=={{header|Phix}}==
{{Trans|Euphoria}}
<!--<
<span style="color: #008080;">constant</span> <span style="color: #000000;">order</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">4</span>
Line 3,872 ⟶ 5,391:
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'\n'</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre style="font-size: 2px">
Line 3,960 ⟶ 5,479:
=={{header|PHP}}==
<
function isSierpinskiCarpetPixelFilled($x, $y) {
Line 3,987 ⟶ 5,506:
sierpinskiCarpet($order);
echo PHP_EOL;
}</
{{out}}
Line 4,037 ⟶ 5,556:
# ## ## ## ## ## ## ## ## #
###########################
</pre>
=={{header|Picat}}==
{{works with|Picat}}
<syntaxhighlight lang="picat">
in_carpet(X, Y) =>
while (X != 0, Y != 0)
if (X mod 3 == 1, Y mod 3 == 1) then
false
end,
X := X div 3,
Y := Y div 3
end.
in_carpet(_, _) =>
true.
main(Args) =>
N = to_int(Args[1]),
Power1 = 3 ** N - 1,
foreach (I in 0..Power1)
foreach (J in 0..Power1)
printf("%w", cond(in_carpet(I, J), "*", " "))
end,
nl
end.
</syntaxhighlight>
{{out}}
<pre>
***************************
* ** ** ** ** ** ** ** ** *
***************************
*** ****** ****** ***
* * * ** * * ** * * *
*** ****** ****** ***
***************************
* ** ** ** ** ** ** ** ** *
***************************
********* *********
* ** ** * * ** ** *
********* *********
*** *** *** ***
* * * * * * * *
*** *** *** ***
********* *********
* ** ** * * ** ** *
********* *********
***************************
* ** ** ** ** ** ** ** ** *
***************************
*** ****** ****** ***
* * * ** * * ** * * *
*** ****** ****** ***
***************************
* ** ** ** ** ** ** ** ** *
***************************
</pre>
=={{header|PicoLisp}}==
{{trans|Ruby}}
<
(let Carpet '("#")
(do N
Line 4,052 ⟶ 5,627:
(mapcar '((S) (pack S S S)) Carpet) ) ) ) ) )
(mapc prinl (carpet 3))</
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
/* Sierpinski carpet */
Line 4,093 ⟶ 5,668:
end Carpet;
end Sierpinski_carpet;
</syntaxhighlight>
The above is a translation of the Fortran version.
Output for n=3:
Line 4,127 ⟶ 5,702:
=={{header|PostScript}}==
<
%%BoundingBox 0 0 300 300
Line 4,146 ⟶ 5,721:
pop showpage
%%EOF</
=={{header|PowerShell}}==
<h3>Text based solution</h3>
{{works with|PowerShell|2}}
<
{
$Carpet = @( '#' ) * [math]::Pow( 3, $N )
Line 4,167 ⟶ 5,742:
}
Draw-SierpinskiCarpet 3</
{{out}}
<pre>###########################
Line 4,198 ⟶ 5,773:
<h3>Graphics based solution</h3>
{{works with|PowerShell|3}}
<
{
# Define form
Line 4,251 ⟶ 5,826:
}
Draw-SierpinskiCarpet 4</
{{out}}
{{incomplete|powershell|Upload of files currently blocked. Needs output screenshot once file uploading is again allowed.}}
=={{header|Processing}}==
<
void setup() {
Line 4,282 ⟶ 5,857:
}
}
}</
Line 4,288 ⟶ 5,863:
==={{header|Processing Python mode}}===
{{trans|Processing}}
<
def setup():
size(729, 729)
Line 4,307 ⟶ 5,882:
rect(xx + delta, yy + delta, delta, delta)
rectangles(xx + s / 3, yy + s / 3, s / 3)
</syntaxhighlight>
=={{header|Prolog}}==
{{works with|SWI Prolog}}
This program produces an image file in SVG format.
<
write_sierpinski_carpet('sierpinski_carpet.svg', 486, 4).
Line 4,351 ⟶ 5,926:
format(Stream,
"<rect fill='black' x='~g' y='~g' width='~g' height='~g'/>\n",
[X, Y, Side, Side]).</
{{out}}
[[Media:Sierpinski_carpet_prolog.svg]]
=={{header|Python}}==
This inserts a space after every character; but this makes the spacing look better anyway.
<
while True:
if x == 0 or y == 0:
Line 4,401 ⟶ 5,950:
else:
print ' ',
print</
This version is elegant:
{{trans|Ruby}}
<
carpet = ["#"]
for i in xrange(n):
Line 4,412 ⟶ 5,961:
return "\n".join(carpet)
print sierpinski_carpet(3)</
Line 4,418 ⟶ 5,967:
{{Trans|Haskell}}
{{Works with|Python|3.7}}
<
from itertools import chain, islice
Line 4,561 ⟶ 6,110:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>Iterations of the Sierpinski carpet:
Line 4,609 ⟶ 6,158:
▓▓ ▓▓▓▓ ▓▓▓▓ ▓▓▓▓ ▓▓▓▓ ▓▓▓▓ ▓▓▓▓ ▓▓▓▓ ▓▓▓▓ ▓▓
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓</pre>
=={{header|Quackery}}==
Line 4,615 ⟶ 6,163:
{{trans|Forth}}
<
[ 3 / swap ] is 3/ ( n1 n2 --> n2/3 n1 )
Line 4,636 ⟶ 6,184:
drop ] is carpet ( n --> )
4 carpet</
{{out}}Shown at half size.
Line 4,728 ⟶ 6,276:
{{Works with|R|3.3.3 and above}}
[[File:SierpCRo5.png|200px|right|thumb|Output SierpCRo5.png]]
<syntaxhighlight lang="r">
## Are x,y inside Sierpinski carpet (and where)? (1-yes, 0-no)
inSC <- function(x, y) {
Line 4,754 ⟶ 6,302:
## Executing:
pSierpinskiC(5);
</syntaxhighlight>
{{Output}}
<pre>
Line 4,767 ⟶ 6,315:
{{Works with|R|3.3.3 and above}}
[[File:SierpCR2o5.png|200px|right|thumb|Output SierpCR2o5.png]]
<syntaxhighlight lang="r">
## Plotting Sierpinski carpet fractal v.2. aev 4/2/17
## ord - order, fn - file name, ttl - plot title, clr - color
Line 4,785 ⟶ 6,333:
## Executing:
pSierpinskiC2(5);
</syntaxhighlight>
{{Output}}
<pre>
Line 4,796 ⟶ 6,344:
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(define (carpet n)
Line 4,807 ⟶ 6,355:
(map (λ(x) (~a x x x)) prev)))))
(for-each displayln (carpet 3))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{trans|Tcl}}
<syntaxhighlight lang="raku"
{
(['#'], -> @c {
Line 4,838 ⟶ 6,386:
say @carpet[3];
# Output of both versions matches task example.</
=={{header|Relation}}==
Used _ instead of spaces beause wikitext compacts subsequents spaces
<syntaxhighlight lang="relation">
function incarpet(x,y)
set a = x
Line 4,878 ⟶ 6,426:
run carpet(3)
</syntaxhighlight>
<pre>
Line 4,911 ⟶ 6,459:
=={{header|REXX}}==
<
parse arg N char . /*get the order of the carpet. */
if N=='' | N=="," then N= 3 /*if none specified, then assume 3. */
Line 4,936 ⟶ 6,484:
if length(z)<width then say z /*display the line if it fits on screen*/
call lineout 'Sierpinski.'N, z /*also, write the line to a (disk) file*/
end /*j*/ /*stick a fork in it, we're all done. */</
This REXX program makes use of '''linesize''' REXX program (or BIF) which is used to determine the screen width (or linesize) of the terminal (console).
Line 4,985 ⟶ 6,533:
=={{header|Ring}}==
<
load "guilib.ring"
Line 5,042 ⟶ 6,590:
end
return true}
</syntaxhighlight>
Output:
[[File:CalmoSoftCarpet.jpg]]
Line 5,048 ⟶ 6,596:
=={{header|Ruby}}==
{{trans|Tcl}}
<
carpet = ["#"]
n.times do
Line 5,058 ⟶ 6,606:
end
4.times{|i| puts "\nN=#{i}", sierpinski_carpet(i)}</
{{out}}
Line 5,113 ⟶ 6,661:
{{libheader|RubyGems}}
{{libheader|JRubyArt}}
<
attr_reader :limit
Line 5,144 ⟶ 6,692:
size(729, 729)
end
</syntaxhighlight>
=={{header|Rust}}==
{{trans|Ruby}}
<
for i in 0..4 {
println!("\nN={}", i);
Line 5,172 ⟶ 6,720:
}
</syntaxhighlight>
=={{header|Scala}}==
{{trans|Ruby}}
<
carpet.map(x => x + x + x) :::
carpet.map(x => x + x.replace('#', ' ') + x) :::
carpet.map(x => x + x + x))
def sierpinskiCarpets(n: Int) = (Iterator.iterate(List("#"))(nextCarpet) drop n next) foreach println</
=={{header|Scheme}}==
<
(define (in-carpet? x y)
(cond ((or (zero? x) (zero? y))
Line 5,198 ⟶ 6,746:
#\*
#\space)))
(newline)))</
=={{header|Seed7}}==
<
const func boolean: inCarpet (in var integer: x, in var integer: y) is func
Line 5,237 ⟶ 6,785:
begin
carpet(3);
end func;</
=={{header|Sidef}}==
<
3.times {
c = (c.map{|x| x * 3 } +
Line 5,246 ⟶ 6,794:
c.map{|x| x * 3 })
}
say c.join("\n")</
=={{header|Swift}}==
{{trans|Ruby}}
<
func sierpinski_carpet(n:Int) -> String {
func middle(str:String) -> String {
Line 5,288 ⟶ 6,814:
}
println(sierpinski_carpet(3))</
=={{header|Tcl}}==
<
proc map {lambda list} {
Line 5,312 ⟶ 6,838:
}
puts [sierpinski_carpet 3]</
=={{header|UNIX Shell}}==
===Bash + paste(1)===
{{works with|Bash}}
Doesn't pretend to be efficient.
Note that this code inserts a space between characters; some versions of [http://en.wikipedia.org/wiki/Paste_(Unix) paste(1)] (notably the one that ships with OS X) won't allow an empty delimiter. If yours does, you can replace the <tt>-d ' '</tt> in the function body with <tt>-d </tt>' '<tt> </tt>for more compact output.
<
sierpinski_carpet() {
Line 5,360 ⟶ 6,856:
done
echo "$carpet"
}</
Sample run:
Line 5,393 ⟶ 6,889:
# # # # # # # # # # # # # # # # # # # # # # # # # # #
</pre>
===Bash/Ksh/Zsh + dc(1)===
Alternate version using the 'corresponding 1s in base 3' rule, with help from dc(1):
{{works with|Bourne-Again SHell}}
{{works with|Korn Shell}}
{{works with|Zsh}}
<syntaxhighlight lang="sh">sierpinski_carpet() {
typeset -i n=${1:-3}
if (( n < 1 )); then
return 1
fi
typeset -i size x y
typeset x1 y1
(( size = 3 ** n ))
for (( y=0; y<size; ++y )); do
y1=$(dc <<<"$y 3op")
for (( x=0; x<size; ++x )); do
x1=$(dc <<<"$x 3op")
if (( 2#${x1//2/0} & 2#${y1//2/0} )); then
printf ' '
else
printf '#'
fi
done
printf '\n'
done
}
sierpinski_carpet 3</syntaxhighlight>
{{Out}}
<pre>###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
### ### ### ###
# # # # # # # #
### ### ### ###
######### #########
# ## ## # # ## ## #
######### #########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################</pre>
=={{header|Ursala}}==
The carpet function works for any natural number n and is tested on 0,1,2, and 3.
The carpet is stored as a list of lists of booleans but converted to characters for display.
<
#import nat
Line 5,404 ⟶ 6,957:
#show+
test = mat0 ~&?(`#!,` !)*** carpet* <0,1,2,3></
{{out}}
<pre style="height:30ex;overflow:scroll;">
Line 5,452 ⟶ 7,005:
</pre>
=={{header|
{{trans|
<syntaxhighlight lang="Zig">
import math
fn main() {
carpet(3)
}
fn carpet(n int) {
power := int(math.pow(3.0, n))
if in_carpet(i, j) == true {print("*")} else{print(" ")}
}
println('')
}
}
fn in_carpet(x int, y int) bool {
mut xx := x
mut yy := y
for xx != 0 && yy != 0 {
if xx % 3 == 1 && yy % 3 == 1 {return false}
xx /= 3
yy /= 3
}
return true
}
</syntaxhighlight>
{{out}}
<pre>
***************************
* ** ** ** ** ** ** ** ** *
***************************
*** ****** ****** ***
***************************
* ** ** ** ** ** ** ** ** *
***************************
********* *********
***************************
* ** ** ** ** ** ** ** ** *
***************************
*** ****** ****** ***
***************************
* ** ** ** ** ** ** ** ** *
***************************
</pre>
=={{header|Wren}}==
{{trans|Python}}
<
while (true) {
if (x == 0 || y == 0) return true
Line 5,643 ⟶ 7,088:
}
carpet.call(3)</
{{out}}
Line 5,679 ⟶ 7,124:
Uses magic number division to avoid repeatedly using the div instruction in a loop.
<
;Tested in windows 7 Enterprise Service Pack 1 64 bit
;With the AMD FX(tm)-6300 processor
Line 5,838 ⟶ 7,283:
mov rcx,1
call exit</
{{out|Sample}}
Line 5,898 ⟶ 7,343:
=={{header|XPL0}}==
[[File:CarpetXPL0.gif|right]]
<
proc DrawPat(X0, Y0, S); \Draw 3x3 pattern with hole in middle
Line 5,916 ⟶ 7,361:
if ChIn(1) then []; \wait for keystroke
SetVid($3); \restore normal text mode
]</
=={{header|
8-bit BCT (Binary-Coded Ternary) values are used so maximum N is 4, sjasmplus syntax, CP/M executable:
<syntaxhighlight lang="z80">; Sierpinski carpet in Z80 assembly (for CP/M OS - you can use `tnylpo` or `z88dk-ticks` on PC)
OPT --syntax=abf : OUTPUT "sierpinc.com" ; asm syntax for z00m's variant of sjasmplus
; start for n=0, total size is 1x1 (just '#'), show five carpets for n=0,1,2,3,4
ld h,%00000001 ; 3**0 = 1 in BCT form (0t0001)
carpets_loop: ; n == 4 is maximum for 8bit BCT math (3**4 = 81 = 0x100 as BCT value)
call show_carpet
ld a,h ; do ++n -> H = 3**n in BCT form, ie. `H <<= 2;` in binary way
add a,a
jp z,0 ; return to CP/M if the biggest carpet for n=4 (H==0) was already displayed
add a,a
ld h,a ; zero for n=4, which will correctly wrap to 0t2222 in base3_dec_a
jr carpets_loop
show_carpet:
ld l,h ; L = 3**n (row counter and Y coordinate)
.rows:
ld a,l
call base3_dec_a
ld l,a ; --L for this row
ld b,h ; B = 3**n (char counter and X coordinate)
.chars:
ld a,b
call base3_dec_a
ld b,a ; --B
and l ; check if X and Y coordinate have digit "1" at same position(s) in ternary
and %01010101 ; non-zero if both coordinates have digit "1" at same position(s)
ld e,'#'
jr z,.fill_char
ld e,' '
.fill_char:
call print_char
inc b
djnz .chars ; loop chars until B==0 was displayed
call print_crlf
ld a,l
or a
jr nz,.rows ; loop rows until L==0 was displayed
; fallthrough into print_crlf for extra empty line after each carpet is finished
print_crlf:
ld e,10
call print_char
ld e,13
print_char:
push bc
push hl
ld c,2
call 5
pop hl
pop bc
ret
; in: A = BCT value (Binary-coded Ternary = pair of bits for ternary digit 0,1,2 (3 not allowed))
; out: A-1 in BCT encoding, modifies C and F (ZF signals zero result, 0t0000-1 = 0t2222 (0xAA))
base3_dec_a:
dec a ; --A (%00 digits may become %11 when involved in decrement)
ld c,a
and c
and %01010101 ; %11 bit-pairs to %01, anything else to %00
xor c ; fix %11 -> %10 in result to have only 0,1,2 digits
ret
/* ;;; bonus routine ;;;
; in: A = BCT value (Binary-coded Ternary = pair of bits for ternary digit 0,1,2 (3 not allowed))
; out: A+1 in BCT encoding, modifies C and F (ZF signals zero result, ie. 0t2222+1 = 0t0000)
base3_inc_a:
add a,%01'01'01'10 ; +1 to every digit (0,1,2 -> 1,2,3), and +1 overall to increment
ld c,a
rra
or c
and %01'01'01'01 ; 00,01,10,11 -> 00,01,01,01
add a,c ; revert digits 3,2,1 back to 2,1,0 (0 -> 0)
ret
*/</syntaxhighlight>
{{out}}
<pre>
#
###
# #
###
#########
# ## ## #
#########
### ###
# # # #
### ###
#########
# ## ## #
#########
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ###### ###
###########################
# ## ## ## ## ## ## ## ## #
###########################
######### #########
# ## ## # # ## ## #
######### #########
...
</pre>
=={{header|zkl}}==
Line 5,973 ⟶ 7,478:
{{trans|XPL0}}
Uses the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl
<
foreach y,x in (3,3){
if(x.isEven or y.isEven){ // don't draw middle pattern
Line 5,980 ⟶ 7,485:
}
}
}</
<
drawPat(0,0,(3).pow(5),img);
img.write(File("foo.ppm","wb"));</
[[Category:Geometry]]
|