Sierpinski triangle/Graphical: Difference between revisions

m
(46 intermediate revisions by 23 users not shown)
Line 4:
An example of Sierpinski's triangle (order = 8) looks like this: <br/><br/>
[[File:Sierpinski_Triangle_Unicon.PNG]]
 
=={{header|8086 Assembly}}==
 
This program will draw a Sierpinski triangle of the given order on a CGA (or EGA/VGA/etc) screen.
It uses 320x200 mode, so the maximum order is 7.
 
<syntaxhighlight lang="asm"> ;;; Display a Sierpinski triangle on a CGA screen
;;; (order 7 is the maximum that fits in 200 lines)
mode: equ 0Fh ; INT 10H call to get current video mode
puts: equ 9h ; MS-DOS call to print string
cgaseg: equ 0B800h ; Location of CGA video memory
cpu 8086
bits 16
org 100h
section .text
cmp [80h],byte 2 ; Argument length should be 2 (space + digit)
jne eusage
mov al,[82h] ; Get digit
sub al,'0'+2 ; 2->0, 7->5
cmp al,5 ; Then it must be <=5
jbe argok
eusage: mov dx,usage ; Print usage string
estop: mov ah,puts
int 21h
ret ; And stop
argok: add al,2 ; Add 2, setting AL to the order
mov [order],al ; Store the order
mov ah,mode ; Get the current video mode
int 10h
cmp al,7 ; If MDA, we don't have graphics support
mov dx,errcga
je estop
mov [vmode],al ; Otherwise, store the old mode
mov ax,4 ; and switch to mode 4 (320x200 graphics)
int 10h
mov ch,1 ; Size = 2^order
mov cl,[order]
shl ch,cl
xor dh,dh ; Start at coords (0,0)
mov bp,cgaseg ; Point ES at the CGA memory
mkscr: mov es,bp
xor di,di ; Start at the beginning
mkline: xor dl,dl ; Start at coords (0,Y)
mkbyte: xor al,al ; A byte has 4 pixels in it
mov cl,4
mkpx: shl al,1 ; Make room for next pixel
shl al,1
test dl,dh ; X & Y == 0?
jnz nextpx
or al,3 ; X & Y == 0, set pixel on
nextpx: inc dl ; Increment X coordinate
dec cl ; More pixels in this byte?
jnz mkpx ; If so, add them in
stosb ; Otherwise, write it out to CGA memory
cmp dl,ch ; And if the line is not done yet,
jb mkbyte ; do the next byte on this line.
shr dl,1 ; Move ahead to start of next line
shr dl,1
mov ax,80 ; 80 bytes per line
sub al,dl
add di,ax
add dh,2 ; Memory is interlaced so we're 2 lines further
cmp dh,ch ; If we're not done yet,
jb mkline ; Do the next line.
add bp,200h ; Move ahead 8k to the area for the odd lines
cmp bp,0BA00h ; Unless we were already there
mov dh,1 ; We'll have to start at line 1
jbe mkscr
xor ah,ah ; Wait for a keypress to get back to DOS
int 16h
xor ah,ah ; Then, restore the old video mode,
mov al,[vmode]
int 10h
ret ; And exit to DOS
section .data
usage: db 'SIERPCGA [2..7] - display Sierpinski triangle of order N$'
errcga: db 'Need at least CGA.$'
section .bss
order: resb 1 ; Order of Sierpinski triangle
vmode: resb 1 ; Store old video mode (to restore later)</syntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Draw(INT x0 BYTE y0,depth)
BYTE i,x,y,size
 
size=1 LSH depth
 
FOR y=0 TO size-1
DO
FOR x=0 TO size-1
DO
IF (x&y)=0 THEN
Plot(x0+x,y0+y)
FI
OD
OD
RETURN
 
PROC Main()
BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6
 
Graphics(8+16)
Color=1
COLOR1=$0C
COLOR2=$02
 
Draw(96,32,7)
 
DO UNTIL CH#$FF OD
CH=$FF
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sierpinski_triangle_graphical.png Screenshot from Atari 8-bit computer]
 
=={{header|ActionScript}}==
SierpinskiTriangle class:
<syntaxhighlight lang="actionscript3">
<lang ActionScript3>
package {
Line 87 ⟶ 200:
 
}
</syntaxhighlight>
</lang>
 
Document class:
<syntaxhighlight lang="actionscript3">
<lang ActionScript3>
package {
Line 113 ⟶ 226:
 
}
</syntaxhighlight>
</lang>
 
=={{header|ALGOL 68}}==
{{libheader|ALGOL 68-l-system}}
Generates an SVG file containing the curve using the L-System. Very similar to the Algol 68 Sierpinski square curve sample.
Note the Algol 68 L-System library source code is on a separate page on Rosetta Code - follow the above link and then to the Talk page.
<syntaxhighlight lang="algol68">
BEGIN # Sierpinski Triangle Curve in SVG #
# uses the RC Algol 68 L-System library for the L-System evaluation & #
# interpretation #
 
PR read "lsystem.incl.a68" PR # include L-System utilities #
 
PROC sierpinski triangle curve = ( STRING fname, INT size, length, order, init x, init y )VOID:
IF FILE svg file;
BOOL open error := IF open( svg file, fname, stand out channel ) = 0
THEN
# opened OK - file already exists and #
# will be overwritten #
FALSE
ELSE
# failed to open the file #
# - try creating a new file #
establish( svg file, fname, stand out channel ) /= 0
FI;
open error
THEN # failed to open the file #
print( ( "Unable to open ", fname, newline ) );
stop
ELSE # file opened OK #
 
REAL x := init x;
REAL y := init y;
INT angle := 0;
put( svg file, ( "<svg xmlns='http://www.w3.org/2000/svg' width='"
, whole( size, 0 ), "' height='", whole( size, 0 ), "'>"
, newline, "<rect width='100%' height='100%' fill='white'/>"
, newline, "<path stroke-width='1' stroke='black' fill='none' d='"
, newline, "M", whole( x, 0 ), ",", whole( y, 0 ), newline
)
);
 
LSYSTEM ssc = ( "F-G-G"
, ( "F" -> "F-G+F+G-F"
, "G" -> "GG"
)
);
STRING curve = ssc EVAL order;
curve INTERPRET ( ( CHAR c )VOID:
IF c = "F" OR c = "G" THEN
x +:= length * cos( angle * pi / 180 );
y +:= length * sin( angle * pi / 180 );
put( svg file, ( " L", whole( x, 0 ), ",", whole( y, 0 ), newline ) )
ELIF c = "+" THEN
angle +:= 120 MODAB 360
ELIF c = "-" THEN
angle -:= 120 MODAB 360
FI
);
put( svg file, ( "'/>", newline, "</svg>", newline ) );
close( svg file )
FI # sierpinski square # ;
 
sierpinski triangle curve( "sierpinski_triangle.svg", 1200, 12, 5, 200, 400 )
 
END
</syntaxhighlight>
 
=={{header|Asymptote}}==
This simple-minded recursive apporach doesn't scale well to large orders, but neither would your PostScript viewer, so there's nothing to gain from a more efficient algorithm. Thus are the perils of vector graphics.
 
<langsyntaxhighlight lang="asymptote">path subtriangle(path p, real node) {
return
point(p, node) --
Line 136 ⟶ 316:
}
sierpinski((0, 0) -- (5 inch, 1 inch) -- (2 inch, 6 inch) -- cycle, 10);</langsyntaxhighlight>
 
Una versión mas corta:
<syntaxhighlight lang="asymptote">pair A = (0, 0), B = (1, 0), C = (.5, 1);
 
void sierpinski(pair p, int d) {
if (++d < 7) {
p *= 2;
sierpinski(p + A * 2, d);
sierpinski(p + B * 2, d);
sierpinski(p + C * 2, d);
} else {
fill(shift(p / 2) * (A -- B -- C -- cycle));
}
}
 
sierpinski((0, 0), 0);</syntaxhighlight>
 
=={{header|ATS}}==
{{libheader|SDL}}
<langsyntaxhighlight ATSlang="ats">// patscc -O2 -flto -D_GNU_SOURCE -DATS_MEMALLOC_LIBC sierpinski.dats -o sierpinski -latslib -lSDL2
#include "share/atspre_staload.hats"
 
Line 242 ⟶ 438:
SDL_RenderDrawLine(sdlren, x1, y1, x2, y2);
}
%}</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
{{libheader|GDIP}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">#NoEnv
#SingleInstance, Force
SetBatchLines, -1
Line 344 ⟶ 540:
If (A_Gui = 1)
PostMessage, 0xA1, 2
}</langsyntaxhighlight>
 
 
=={{header|BBC BASIC}}==
=={{header|BASIC}}==
{{works with|QBasic}}
<!-- {{works with|QBasic}} codificado por: Kibbee, 12 junio 2012 -->
<syntaxhighlight lang="basic">
SCREEN 9
H=.5
P=300
FOR I=1 TO 9^6
N=RND
IF N > 2/3 THEN
X=H+X*H:Y=Y*H
ELSEIF N > 1/3 THEN
X=H^2+X*H:Y=H+Y*H
ELSE
X=X*H:Y=Y*H
END IF
PSET(P-X*P,P-Y*P)
NEXT
</syntaxhighlight>
[https://www.dropbox.com/s/c3g1ae1i771ox7g/Sierpinski_triangle_QBasic.png?dl=0 Sierpinski triangle QBasic image]
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> order% = 8
size% = 2^order%
VDU 23,22,size%;size%;8,8,16,128
Line 356 ⟶ 574:
NEXT
NEXT Y%
</syntaxhighlight>
</lang>
[[File:sierpinski_triangle_bbc.gif]]
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' version 06-07-2015
' compile with: fbc -s console or with: fbc -s gui
 
#Define black 0
#Define white RGB(255,255,255)
 
Dim As Integer x, y
Dim As Integer order = 9
Dim As Integer size = 2 ^ order
 
ScreenRes size, size, 32
Line (0,0) - (size -1, size -1), black, bf
 
For y = 0 To size -1
For x = 0 To size -1
If (x And y) = 0 Then PSet(x, y) ' ,white
Next
Next
 
' empty keyboard buffer
While Inkey <> "" : Wend
WindowTitle "Hit any key to end program"
Sleep
End</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 PROGRAM "Triangle.bas"
110 SET VIDEO MODE 1:SET VIDEO COLOR 0:SET VIDEO X 40:SET VIDEO Y 27
120 OPEN #101:"video:"
130 DISPLAY #101:AT 1 FROM 1 TO 27
140 CALL SIERP(896,180,50)
150 DEF SIERP(W,X,Y)
160 IF W>28 THEN
170 CALL SIERP(W/2,X,Y)
180 CALL SIERP(W/2,X+W/4,Y+W/2)
190 CALL SIERP(W/2,X+W/2,Y)
200 ELSE
210 PLOT X,Y;X+W/2,Y+W;X+W,Y;X,Y
220 END IF
230 END DEF</syntaxhighlight>
 
==={{header|Liberty BASIC}}===
The ability of LB to handle very large integers makes the Pascal triangle method very attractive. If you alter the rem'd line you can ask it to print the last, central term...
<syntaxhighlight lang="lb">
nomainwin
 
open "test" for graphics_nsb_fs as #gr
 
#gr "trapclose quit"
#gr "down; home"
#gr "posxy cx cy"
 
order =10
 
w =cx *2: h =cy *2
 
dim a( h, h) 'line, col
 
#gr "trapclose quit"
#gr "down; home"
 
a( 1, 1) =1
 
for i = 2 to 2^order -1
scan
a( i, 1) =1
a( i, i) =1
for j = 2 to i -1
'a(i,j)=a(i-1,j-1)+a(i-1,j) 'LB is quite capable for crunching BIG numbers
a( i, j) =(a( i -1, j -1) +a( i -1, j)) mod 2 'but for this task, last bit is enough (and it much faster)
next
for j = 1 to i
if a( i, j) mod 2 then #gr "set "; cx +j -i /2; " "; i
next
next
#gr "flush"
 
wait
 
sub quit handle$
close #handle$
end
end sub
</syntaxhighlight>
Up to order 10 displays on a 1080 vertical pixel screen.
 
==={{header|Run BASIC}}===
[[File : SierpinskiRunBasic.png|thumb|right]]
<syntaxhighlight lang="runbasic">graphic #g, 300,300
order = 8
width = 100
w = width * 11
dim canvas(w,w)
canvas(1,1) = 1
 
for x = 2 to 2^order -1
canvas(x,1) = 1
canvas(x,x) = 1
for y = 2 to x -1
canvas( x, y) = (canvas(x -1,y -1) + canvas(x -1, y)) mod 2
if canvas(x,y) mod 2 then #g "set "; width + (order*3) + y - x / 2;" "; x
next y
next x
render #g
#g "flush"
wait</syntaxhighlight>
 
==={{header|SmileBASIC}}===
{{Trans|Action!}}
<syntaxhighlight lang="basic">OPTION STRICT
OPTION DEFINT
DEF DRAW X0, Y0, DEPTH
VAR X, Y, SIZE
SIZE = 1 << DEPTH
FOR Y = 0 TO SIZE - 1
FOR X = 0 TO SIZE - 1
IF (X AND Y) == 0 THEN
GPSET X0 + X, Y0 + Y, RGB(X, 255 - Y, 255)
ENDIF
NEXT
NEXT
END
CALL "DRAW", 96, 32, 7
END</syntaxhighlight>
 
==={{header|TI-83 BASIC}}===
<syntaxhighlight lang="ti83b">:1→X:1→Y
:Zdecimal
:Horizontal 3.1
:Vertical -4.5
:While 1
:X+1→X
:DS<(Y,1
:While 0
:X→Y
:1→X
:End
:If pxl-Test(Y-1,X) xor (pxl-Test(Y,X-1
:PxlOn(Y,X
:End</syntaxhighlight>
This could be made faster, but I just wanted to use the DS<( command
 
==={{header|Yabasic}}===
[http://retrogamecoding.org/board/index.php?action=dlattach;topic=753.0;attach=1800;image Sierpinski Triangle 3D.png]
 
3D version.
<syntaxhighlight lang="yabasic">// Adpated from non recursive sierpinsky.bas for SmallBASIC 0.12.6 [B+=MGA] 2016-05-19 with demo mod 2016-05-29
 
//Sierpinski triangle gasket drawn with lines from any 3 given points
// WITHOUT RECURSIVE Calls
 
 
//first a sub, given 3 points of a triangle draw the traiangle within
//from the midpoints of each line forming the outer triangle
//this is the basic Sierpinski Unit that is repeated at greater depths
//3 points is 6 arguments to function plus a depth level
 
xmax=800:ymax=600
open window xmax,ymax
backcolor 0,0,0
color 255,0,0
clear window
 
sub SierLineTri(x1, y1, x2, y2, x3, y3, maxDepth)
local mx1, mx2, mx3, my1, my2, my3, ptcount, depth, i, X, Y
Y = 1
//load given set of 3 points into oa = outer triangles array, ia = inner triangles array
ptCount = 3
depth = 1
dim oa(ptCount - 1, 1) //the outer points array
oa(0, X) = x1
oa(0, Y) = y1
oa(1, X) = x2
oa(1, Y) = y2
oa(2, X) = x3
oa(2, Y) = y3
dim ia(3 * ptCount - 1, 1) //the inner points array
iaIndex = 0
while(depth <= maxDepth)
for i=0 to ptCount-1 step 3 //draw outer triangles at this level
if depth = 1 then
line oa(i,X), oa(i,Y), oa(i+1,X), oa(i+1,Y)
line oa(i+1,X), oa(i+1,Y), oa(i+2,X), oa(i+2,Y)
line oa(i,X), oa(i,Y), oa(i+2,X), oa(i+2,Y)
end if
if oa(i+1,X) < oa(i,X) then mx1 = (oa(i,X) - oa(i+1,X))/2 + oa(i+1,X) else mx1 = (oa(i+1,X) - oa(i,X))/2 + oa(i,X) endif
if oa(i+1,Y) < oa(i,Y) then my1 = (oa(i,Y) - oa(i+1,Y))/2 + oa(i+1,Y) else my1 = (oa(i+1,Y) - oa(i,Y))/2 + oa(i,Y) endif
if oa(i+2,X) < oa(i+1,X) then mx2 = (oa(i+1,X)-oa(i+2,X))/2 + oa(i+2,X) else mx2 = (oa(i+2,X)-oa(i+1,X))/2 + oa(i+1,X) endif
if oa(i+2,Y) < oa(i+1,Y) then my2 = (oa(i+1,Y)-oa(i+2,Y))/2 + oa(i+2,Y) else my2 = (oa(i+2,Y)-oa(i+1,Y))/2 + oa(i+1,Y) endif
if oa(i+2,X) < oa(i,X) then mx3 = (oa(i,X) - oa(i+2,X))/2 + oa(i+2,X) else mx3 = (oa(i+2,X) - oa(i,X))/2 + oa(i,X) endif
if oa(i+2,Y) < oa(i,Y) then my3 = (oa(i,Y) - oa(i+2,Y))/2 + oa(i+2,Y) else my3 = (oa(i+2,Y) - oa(i,Y))/2 + oa(i,Y) endif
//color 9 //testing
//draw all inner triangles
line mx1, my1, mx2, my2
line mx2, my2, mx3, my3
line mx1, my1, mx3, my3
//x1, y1 with mx1, my1 and mx3, my3
ia(iaIndex,X) = oa(i,X)
ia(iaIndex,Y) = oa(i,Y) : iaIndex = iaIndex + 1
ia(iaIndex,X) = mx1
ia(iaIndex,Y) = my1 : iaIndex = iaIndex + 1
ia(iaIndex,X) = mx3
ia(iaIndex,Y) = my3 : iaIndex = iaIndex + 1
//x2, y2 with mx1, my1 and mx2, my2
ia(iaIndex,X) = oa(i+1,X)
ia(iaIndex,Y) = oa(i+1,Y) : iaIndex = iaIndex + 1
ia(iaIndex,X) = mx1
ia(iaIndex,Y) = my1 : iaIndex = iaIndex + 1
ia(iaIndex,X) = mx2
ia(iaIndex,Y) = my2 : iaIndex = iaIndex + 1
//x3, y3 with mx3, my3 and mx2, my2
ia(iaIndex,X) = oa(i+2,X)
ia(iaIndex,Y) = oa(i+2,Y) : iaIndex = iaIndex + 1
ia(iaIndex,X) = mx2
ia(iaIndex,Y) = my2 : iaIndex = iaIndex + 1
ia(iaIndex,X) = mx3
ia(iaIndex,Y) = my3 : iaIndex = iaIndex + 1
next i
//update and prepare for next level
ptCount = ptCount * 3
depth = depth + 1
redim oa(ptCount - 1, 1 )
for i = 0 to ptCount - 1
oa(i, X) = ia(i, X)
oa(i, Y) = ia(i, Y)
next i
redim ia(3 * ptCount - 1, 1)
iaIndex = 0
wend
end sub
 
//Test Demo for the sub (NEW as 2016 - 05 - 29 !!!!!)
cx=xmax/2
cy=ymax/2
r=cy - 20
N=3
for i = 0 to 2
color 64+42*i,64+42*i,64+42*i
SierLineTri(cx, cy, cx+r*cos(2*pi/N*i), cy +r*sin(2*pi/N*i), cx + r*cos(2*pi/N*(i+1)), cy + r*sin(2*pi/N*(i+1)), 5)
next i
</syntaxhighlight>
 
Simple recursive version
<syntaxhighlight lang="yabasic">w = 800 : h = 600
open window w, h
window origin "lb"
 
sub SierpinskyTriangle(level, x, y, w, h)
local w2, w4, h2
w2 = w/2 : w4 = w/4 : h2 = h/2
if level=1 then
new curve
line to x, y
line to x+w2, y+h
line to x+w, y
line to x, y
else
SierpinskyTriangle(level-1, x, y, w2, h2)
SierpinskyTriangle(level-1, x+w4, y+h2, w2, h2)
SierpinskyTriangle(level-1, x+w2, y, w2, h2)
end if
end sub
 
SierpinskyTriangle(7, w*0.05, h*0.05, w*0.9, h*0.9)</syntaxhighlight>
 
=={{header|Bruijn}}==
 
Rendered using [https://lambda-screen.marvinborner.de/ lambda screen].
 
<syntaxhighlight lang="bruijn">y [[1 (0 0)] [1 (0 0)]]
 
# infinite depth
triangle [y [[0 1 [[0]] 1 1]]]
 
:import std/Number .
 
# limited depth
triangle-n [y [[[[1 0 [[0]] 0 0] (=?1 [[1]] (2 --1))]]] (+7)]
</syntaxhighlight>
 
=={{header|C}}==
[[file:sierp-tri-c.png|thumb|center|128px]]Code lifted from [[Dragon curve]]. Given a depth n, draws a triangle of size 2^n in a PNM file to the standard output. Usage: <code>gcc -lm stuff.c -o sierp; ./sierp 9 > triangle.pnm</code>. Sample image generated with depth 9. Generated image's size depends on the depth: it plots dots, but does not draw lines, so a large size with low depth is not possible.
 
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 474 ⟶ 985:
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
[[file:STriCpp.png|thumb|right|200px]]
<langsyntaxhighlight lang="cpp">
#include <windows.h>
#include <string>
Line 599 ⟶ 1,110:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|D}}==
The output image is the same as the Go version. This requires the module from the Grayscale image Task.
{{trans|Go}}
<langsyntaxhighlight lang="d">void main() {
import grayscale_image;
 
Line 619 ⟶ 1,130:
im[x + margin, y + margin] = Gray.black;
im.savePGM("sierpinski.pgm");
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
[[File:DelphiSierpinskiTriangle.png|frame|none]]
 
<syntaxhighlight lang="Delphi">
 
 
const DepthColors24: array [0..23] of TColor =(
0 or (0 shl 8) or (0 shl 16),
255 or (0 shl 8) or (0 shl 16),
255 or (63 shl 8) or (0 shl 16),
255 or (127 shl 8) or (0 shl 16),
255 or (191 shl 8) or (0 shl 16),
255 or (255 shl 8) or (0 shl 16),
191 or (255 shl 8) or (0 shl 16),
127 or (255 shl 8) or (0 shl 16),
63 or (255 shl 8) or (0 shl 16),
0 or (255 shl 8) or (0 shl 16),
0 or (255 shl 8) or (63 shl 16),
0 or (255 shl 8) or (127 shl 16),
0 or (255 shl 8) or (191 shl 16),
0 or (255 shl 8) or (255 shl 16),
0 or (191 shl 8) or (255 shl 16),
0 or (127 shl 8) or (255 shl 16),
0 or (63 shl 8) or (255 shl 16),
0 or (0 shl 8) or (255 shl 16),
63 or (0 shl 8) or (255 shl 16),
127 or (0 shl 8) or (255 shl 16),
191 or (0 shl 8) or (255 shl 16),
255 or (0 shl 8) or (255 shl 16),
255 or (0 shl 8) or (191 shl 16),
255 or (0 shl 8) or (127 shl 16));
 
procedure DrawSerpTriangle(Image: TImage; StartX,StartY, Depth: integer);
var I,X,Y,Size,Inx: integer;
var C: TColor;
begin
Size:=1 shl Depth;
for Y:=0 to Size-1 do
for X:=0 to Size-1 do
begin
{Calculate new color index}
Inx:=MulDiv(Length(DepthColors24),X+Y,Size+Size)+1;
if (X and Y)=0 then
begin
Image.Canvas.Pixels[StartX+X,StartY+Y]:=DepthColors24[Inx];
end;
end;
end;
 
procedure ShowSierpinskiTriangle(Image: TImage);
begin
ClearImage(Image,clBlack);
DrawSerpTriangle(Image,50,32,8);
Image.Invalidate;
end;
</syntaxhighlight>
{{out}}
<pre>
Elapsed Time: 28.293 ms.
</pre>
 
 
=={{header|EasyLang}}==
[https://easylang.dev/show/#cod=fY3BCoMwEETv+Yq5l65RCOghH1PCKoG0kShS+/UmuiAe7O7pzczOjik6zMm/PgMCL/hixeR/DAIpAL7fZQtdKM87LlxSgs4nFxiaalMUDhOLU86eFrXgXlpZNMKXn4/DPl7/CVRockjgLnu2kCIlVguTt9NqAw== Run it]
 
<syntaxhighlight lang="easylang">
proc triang lev x y size . .
if lev = 0
move x y
circle 0.15
else
lev -= 1
size /= 2
triang lev x + size y size
triang lev x + size / 2 y + size size
triang lev x y size
.
.
triang 8 5 5 90
</syntaxhighlight>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module(sierpinski).
-author("zduchac").
Line 652 ⟶ 1,246:
}]),
wxFrame:show(Frame).
</syntaxhighlight>
</lang>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM SIERPINSKY
 
Line 672 ⟶ 1,266:
GET(K$)
END PROGRAM
</syntaxhighlight>
</lang>
 
=={{header|Evaldraw}}==
 
This makes use of sleep(millis); and refresh(); in the middle of a function to do the slow animation of triangles.
 
[[File:Evaldraw sierpinski.gif|thumb|alt=refresh allows for drawing outside the main () function|With sleep() we wait 1 milli before redraw any pixels with refresh()]]
 
<syntaxhighlight lang="c">
static calls=0;
() {
setcol(255,255,255);
if (numframes==0) {
cls(0);
calls = 0;
sierpinski(xres/2,yres*0.1,xres*.8,xres*.8);
}
moveto(0,0); printf("%g recursions", calls);
}
sierpinski(x,y,w,h) {
calls++;
triangle(x,y,w,h);
if(w < 10 || h < 10) return;
sleep(1); refresh();
halfH = h/2;
halfW = w/2;
sierpinski(x,y,halfW,halfH); // left
sierpinski(x+halfW/2,y+halfH,halfW,halfH);
sierpinski(x-halfW/2,y+halfH,halfW,halfH);
}
triangle(x,y,w,h) {
moveto(x,y);
lineto(x+w/2, y+h);
lineto(x-w/2, y+h);
lineto(x,y);
}</syntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: accessors images images.loader kernel literals math
math.bits math.functions make sequences ;
IN: rosetta-code.sierpinski-triangle-graphical
Line 715 ⟶ 1,344:
"sierpinski-triangle.png" save-graphic-image ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
[https://i.imgur.com/wjwCrvL.png]
=={{header|Forth}}==
{{works with|4tH v3.62}}
<langsyntaxhighlight lang="forth">include lib/graphics.4th \ graphics support is needed
 
520 pic_width ! \ width of the image
Line 733 ⟶ 1,362:
: triangle 1 order lshift dup 0 do dup 0 do i j ?pixel loop loop drop ;
 
triangle s" triangle.ppm" save_image \ done, save the image</langsyntaxhighlight>
{{Out}}''Because Rosetta code doesn't allow file uploads, the output can't be shown.''
=={{header|FreeBASIC}}==
<lang FreeBASIC>' version 06-07-2015
' compile with: fbc -s console or with: fbc -s gui
 
#Define black 0
#Define white RGB(255,255,255)
 
=={{header|FutureBasic}}==
Dim As Integer x, y
<syntaxhighlight lang="futurebasic">
Dim As Integer order = 9
_window = 1
Dim As Integer size = 2 ^ order
_width = 600
_height = 500
 
local fn SierpinskyTriangle( level as NSUInteger, x as NSUInteger, y as NSUInteger, w as NSUInteger, h as NSUInteger )
ScreenRes size, size, 32
NSUInteger w2 = w/2, w4 = w/4, h2 = h/2
Line (0,0) - (size -1, size -1), black, bf
if ( level == 1 )
pen -1.0
line to x, y
pen 1.0, fn ColorYellow
line to x+w2, y+h
line to x+w, y
line to x, y
else
fn SierpinskyTriangle( level-1, x, y, w2, h2 )
fn SierpinskyTriangle( level-1, x+w4, y+h2, w2, h2 )
fn SierpinskyTriangle( level-1, x+w2, y, w2, h2 )
end if
end fn
 
window _window, @"Sierpinsky Triangle", ( 0, 0, _width, _height )
For y = 0 To size -1
WindowSetBackgroundColor( 1, fn ColorBlack )
For x = 0 To size -1
If (x And y) = 0 Then PSet(x, y) ' ,white
Next
Next
 
fn SierpinskyTriangle( 9, _width * 0.05, _height * 0.05, _width * 0.9, _height * 0.9 )
' empty keyboard buffer
 
While Inkey <> "" : Wend
HandleEvents
WindowTitle "Hit any key to end program"
</syntaxhighlight>
Sleep
{{output}}
End</lang>
[[File:Sierpinski_triangle_in_FutureBasic.png]]
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/L-system}}
 
'''Solution'''
 
=== By 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 script that creates a Sierpiński triangle is:
 
[[File:Fōrmulæ - L-system - Sierpiński triangle 01.png]]
 
[[File:Fōrmulæ - L-system - Sierpiński triangle 02.png]]
 
=== By chaos game ===
 
There is a function written in Fōrmulæ to create Sierpiński n-gons by the method known as chaos game in the page [[Chaos game#Fōrmulæ | chaos game]].
 
The script that creates a Sierpiński triangle is:
 
[[File:Fōrmulæ - Chaos game - Sierpiński triangle 01.png]]
 
[[File:Fōrmulæ - Chaos game - Sierpiński triangle 02.png]]
 
=== By Kronecker product ===
 
There is a function written in Fōrmulæ to create generic Kronecker product based fractal in the page [[Kronecker product based fractals#Fōrmulæ | Kronecker product based fractals]].
 
The script that creates a Sierpiński triangle is:
 
[[File:Fōrmulæ - Kronecker product based fractals 08.png]]
 
[[File:Fōrmulæ - Kronecker product based fractals 09.png]]
 
=== By elementary cellular automaton ===
 
There is a function written in Fōrmulæ to create images for the elementary cellular automaton in the page [[Elementary cellular automaton#Fōrmulæ | Elementary cellular automaton]].
 
All the rules 18, 22 , 23, 60, 82, 90, 102, 126, 129, 146, 153, 154, 161, 165, 167, 181, 182, 195, 210 and 218 produce Sierpiński triangles:
 
[[File:Fōrmulæ - Elementary cellular automaton - Sierpiński triangle 01.png]]
 
[[File:Fōrmulæ - Elementary cellular automaton - Sierpiński triangle 02.png]]
 
=={{header|gnuplot}}==
Generating X,Y coordinates by the ternary digits of parameter t.
 
<langsyntaxhighlight lang="gnuplot"># triangle_x(n) and triangle_y(n) return X,Y coordinates for the
# Sierpinski triangle point number n, for integer n.
triangle_x(n) = (n > 0 ? 2*triangle_x(int(n/3)) + digit_to_x(int(n)%3) : 0)
Line 780 ⟶ 1,464:
set parametric
set key off
plot triangle_x(t), triangle_y(t) with points</langsyntaxhighlight>
 
=={{header|Go}}==
[[file:GoSierpinski.png|right|thumb|Output png]]
{{trans|Icon and Unicon}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 824 ⟶ 1,508:
fmt.Println(err)
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 834 ⟶ 1,518:
 
[[File:Sierpinski-Haskell.svg|thumb|Sierpinski Triangle]]
<langsyntaxhighlight lang="haskell">import Diagrams.Prelude
import Diagrams.Backend.Cairo.CmdLine
 
Line 846 ⟶ 1,530:
 
main = defaultMain $ sierpinski !! 7
</syntaxhighlight>
</lang>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 852 ⟶ 1,536:
 
[[File:Sierpinski_Triangle_Unicon.PNG|thumb|Sample Output for order=8]]
<langsyntaxhighlight Iconlang="icon">link wopen
 
procedure main(A)
Line 867 ⟶ 1,551:
 
Event()
end</langsyntaxhighlight>
{{libheader|Icon Programming Library}}
[http://www.cs.arizona.edu/icon/library/src/gprogs/sier1.icn Original source IPL Graphics/sier1.]
 
=={{header|IS-BASIC}}==
<lang IS-BASIC>100 PROGRAM "Triangle.bas"
110 SET VIDEO MODE 1:SET VIDEO COLOR 0:SET VIDEO X 40:SET VIDEO Y 27
120 OPEN #101:"video:"
130 DISPLAY #101:AT 1 FROM 1 TO 27
140 CALL SIERP(896,180,50)
150 DEF SIERP(W,X,Y)
160 IF W>28 THEN
170 CALL SIERP(W/2,X,Y)
180 CALL SIERP(W/2,X+W/4,Y+W/2)
190 CALL SIERP(W/2,X+W/2,Y)
200 ELSE
210 PLOT X,Y;X+W/2,Y+W;X+W,Y;X,Y
220 END IF
230 END DEF</lang>
 
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j"> load 'viewmat'
'rgb'viewmat--. |. (~:_1&|.)^:(<@#) (2^8){.1</syntaxhighlight>
 
</lang>
This looks almost exactly (except for OS specific decorations) like the [[:File:Sierpinski_Triangle_Unicon.PNG|task example image]]
 
Other approaches are possible
 
<syntaxhighlight lang="j">load'viewmat'
viewmat(,~,.~)^:4,1</syntaxhighlight> generates a [[j:File:Sier1.jpg|"smaller" image]] and is white on black instead of black on white.
 
Similarly, <syntaxhighlight lang="j">viewmat #:(~:/&.#:@, +:)^:(<32) 1</syntaxhighlight> presents the [[j:File:Sierpinksi.png|image]] in a different orientation.
or
 
And, of course, other approaches are [[j:File:Triangle.png|viable]].
<lang j>
load'viewmat'
viewmat(,~,.~)^:8,1
</lang>
 
=={{header|Java}}==
'''Solution:'''
<langsyntaxhighlight lang="java">import javax.swing.*;
import java.awt.*;
 
Line 959 ⟶ 1,630:
drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);
}
}</langsyntaxhighlight>
 
===Animated version===
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.geom.Path2D;
Line 1,024 ⟶ 1,695:
});
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 1,035 ⟶ 1,706:
{{Works with|Chrome}}
[[File:SierpTRjs.png|200px|right|thumb|Output SierpTRjs.png]]
<langsyntaxhighlight lang="html">
<!-- SierpinskiTriangle.html -->
<html>
Line 1,093 ⟶ 1,764:
<!--canvas id="cvsId" width="1280" height="1280" style="border: 2px inset;"></canvas-->
</body></html>
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 1,099 ⟶ 1,770:
Right clicking on canvas with image allows you to save it as png-file, for example.
</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
This entry uses an L-system and turtle graphics to generate an SVG
file, which can be viewed using a web browser, at least if the file type is `.svg`.
 
See [[Category_talk:Jq-turtle]] for the turtle.jq module used here.
Please note that the `include` directive may need to be modified
depending on the location of the included file, and the command-line
options used.
<syntaxhighlight lang="jq">include "turtle" {search: "."};
 
# Compute the curve using a Lindenmayer system of rules
def rules:
# "H" signfies Horizontal motion
{X: "XX",
H: "H--X++H++X--H",
"": "H--X--X"};
def sierpinski($count):
rules as $rules
| def repeat($count):
if $count == 0 then .
else gsub("X"; $rules["X"]) | gsub("H"; $rules["H"])
| repeat($count-1)
end;
$rules[""] | repeat($count) ;
 
def interpret($x):
if $x == "+" then turtleRotate(-60)
elif $x == "-" then turtleRotate(60)
else turtleForward(20)
end;
 
def sierpinski_curve($n):
sierpinski($n)
| split("")
| reduce .[] as $action (
turtle([200,-200]) | turtleDown;
interpret($action) ) ;
 
# viewBox = <min-x> <min-y> <width> <height>
# Input: {svg, minx, miny, maxx, maxy}
def svg:
"<svg viewBox='\(.minx|floor) \(.miny - 4 |floor) \(.maxx - .minx|ceil) \(6 + .maxy - .miny|ceil)'",
" preserveAspectRatio='xMinYmin meet'",
" xmlns='http://www.w3.org/2000/svg' >",
path("none"; "red"; 1),
"</svg>";
 
sierpinski_curve(5)
| svg
</syntaxhighlight>
 
=={{header|Julia}}==
Produces a png graphic on a transparent background. The brushstroke used for fill might need to be modified for a white background.
<langsyntaxhighlight lang="julia">
using Luxor
 
Line 1,124 ⟶ 1,850:
finish()
preview()
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
'''From Java code:'''
<langsyntaxhighlight lang="scala">import java.awt.*
import javax.swing.JFrame
import javax.swing.JPanel
Line 1,180 ⟶ 1,906:
drawSierpinskyTriangle(level - 1, x, y + size / 2, size / 2)
}
}</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
The ability of LB to handle very large integers makes the Pascal triangle method very attractive. If you alter the rem'd line you can ask it to print the last, central term...
<lang lb>
nomainwin
 
open "test" for graphics_nsb_fs as #gr
 
#gr "trapclose quit"
#gr "down; home"
#gr "posxy cx cy"
 
order =10
 
w =cx *2: h =cy *2
 
dim a( h, h) 'line, col
 
#gr "trapclose quit"
#gr "down; home"
 
a( 1, 1) =1
 
for i = 2 to 2^order -1
scan
a( i, 1) =1
a( i, i) =1
for j = 2 to i -1
'a(i,j)=a(i-1,j-1)+a(i-1,j) 'LB is quite capable for crunching BIG numbers
a( i, j) =(a( i -1, j -1) +a( i -1, j)) mod 2 'but for this task, last bit is enough (and it much faster)
next
for j = 1 to i
if a( i, j) mod 2 then #gr "set "; cx +j -i /2; " "; i
next
next
#gr "flush"
 
wait
 
sub quit handle$
close #handle$
end
end sub
</lang>
Up to order 10 displays on a 1080 vertical pixel screen.
 
=={{header|Logo}}==
This will draw a graphical Sierpinski gasket using turtle graphics.
<langsyntaxhighlight lang="logo">to sierpinski :n :length
if :n = 0 [stop]
repeat 3 [sierpinski :n-1 :length/2 fd :length rt 120]
end
seth 30 sierpinski 5 200</langsyntaxhighlight>
 
=={{header|Lua}}==
{{libheader|LÖVE}}
<langsyntaxhighlight Lualang="lua">-- The argument 'tri' is a list of co-ords: {x1, y1, x2, y2, x3, y3}
function sierpinski (tri, order)
local new, p, t = {}
Line 1,257 ⟶ 1,938:
function love.draw ()
sierpinski({400, 100, 700, 500, 100, 500}, 7)
end</langsyntaxhighlight>
[[File:Love2D-Sierpinski.jpg]]
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Sierpinski[n_] :=
Nest[Join @@ Table[With[{a = #[[i, 1]], b = #[[i, 2]], c = #[[i, 3]]},
{{a, (a + b)/2, (c + a)/2}, {(a + b)/2, b, (b + c)/2}, {(c + a)/2, (b + c)/2, c}}],
{i, Length[#]}] &, {{{0, 0}, {1/2, 1}, {1, 0}}}, n]
Graphics[{Black, Polygon /@ Sierpinski[8]}]</syntaxhighlight>
 
Graphics[{Black, Polygon /@ Sierpinski[8]}]</lang>
Another faster version
<langsyntaxhighlight Mathematicalang="mathematica">cf = Compile[{{A, _Real, 2}},
With[{a = A[[1]], b = A[[2]], c = A[[3]]},
With[{ab = (a + b)/2, bc = (b + c)/2, ca = (a + c)/2},
Line 1,274 ⟶ 1,954:
RuntimeAttributes -> {Listable}
];
 
n = 3;
pts = Flatten[Nest[cf, N@{{{0, 0}, {1, 0}, {1/2, √3/2}}}, n], n];
Graphics[Polygon /@ pts]</langsyntaxhighlight>
 
[[File:MmaSierpinski.png]]
Line 1,283 ⟶ 1,962:
=={{header|MATLAB}}==
===Basic Version===
<langsyntaxhighlight MATLABlang="matlab">[x, x0] = deal(cat(3, [1 0]', [-1 0]', [0 sqrt(3)]'));
for k = 1 : 6
x = x(:,:) + x0 * 2 ^ k / 2;
end
patch('Faces', reshape(1 : 3 * 3 ^ k, 3, '')', 'Vertices', x(:,:)')</langsyntaxhighlight>
{{out}}
Fail to upload output image, use the one of PostScript:
Line 1,294 ⟶ 1,973:
 
===Bit Operator Version===
<langsyntaxhighlight MATLABlang="matlab">t = 0 : 2^16 - 1;
plot(t, bitand(t, bitshift(t, -8)), 'k.')</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Julia}}
{{libheader|imageman}}
Our triangle is ref on a black background.
<syntaxhighlight lang="nim">import imageman
 
const
Black = ColorRGBU [byte 0, 0, 0] # For background.
Red = ColorRGBU [byte 255, 0, 0] # For triangle.
 
proc drawSierpinski(img: var Image; txy: array[1..6, float]; levelsYet: Natural) =
var nxy: array[1..6, float]
if levelsYet > 0:
for i in 1..6:
let pos = if i < 5: i + 2 else: i - 4
nxy[i] = (txy[i] + txy[pos]) / 2
img.drawSierpinski([txy[1], txy[2], nxy[1], nxy[2], nxy[5], nxy[6]], levelsYet - 1)
img.drawSierpinski([nxy[1], nxy[2], txy[3], txy[4], nxy[3], nxy[4]], levelsyet - 1)
img.drawSierpinski([nxy[5], nxy[6], nxy[3], nxy[4], txy[5], txy[6]], levelsyet - 1)
else:
img.drawPolyline(closed = true, Red,
(txy[1].toInt, txy[2].toInt), (txy[3].toInt, txy[4].toInt),(txy[5].toInt, txy[6].toInt))
 
var image = initImage[ColorRGBU](800, 800)
image.fill(Black)
image.drawSierpinski([400.0, 100.0, 700.0, 500.0, 100.0, 500.0], 7)
image.savePNG("sierpinski_triangle.png", compression = 9)</syntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">use Game.SDL2;
use Game.Framework;
 
Line 1,366 ⟶ 2,073:
SCREEN_HEIGHT := 480
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">open Graphics
 
let round v =
Line 1,416 ⟶ 2,123:
let res = loop 6 [ initial_triangle ] in
List.iter draw_triangle res;
ignore (read_key ())</langsyntaxhighlight>
 
run with:
Line 1,425 ⟶ 2,132:
[[File:SierpT9.png|right|thumb|Output SierpT9.png]]
 
<langsyntaxhighlight lang="parigp">
\\ Sierpinski triangle fractal
\\ Note: plotmat() can be found here on
Line 1,438 ⟶ 2,145:
pSierpinskiT(9); \\ SierpT9.png
}
</langsyntaxhighlight>
{{Output}}
Line 1,449 ⟶ 2,156:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">my $levels = 6;
my $side = 512;
my $height = get_height($side);
Line 1,496 ⟶ 2,203:
'<g style="fill: #fff; stroke-width: 0;">',
fractal( $side/2, $height, $side*3/4, $height/2, $side/4, $height/2, $levels ),
'</g></svg>';</langsyntaxhighlight>
[https://github.com/SqrtNegInf/Rosettacode-Perl5-Smoke/blob/master/ref/sierpinski_triangle.svg See sierpinski_triangle] (offsite .svg image)
 
Line 1,502 ⟶ 2,209:
Can resize, and change the level from 1 to 12 (press +/-).
{{libheader|Phix/pGUI}}
<!--<syntaxhighlight lang="phix">-->
<lang Phix>-- demo\rosetta\SierpinskyTriangle.exw
<span style="color: #000080;font-style:italic;">-- demo\rosetta\SierpinskyTriangle.exw</span>
include pGUI.e
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
 
Ihandle dlg, canvas
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">canvas</span>
cdCanvas cddbuffer, cdcanvas
<span style="color: #004080;">cdCanvas</span> <span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cdcanvas</span>
 
procedure SierpinskyTriangle(integer level, atom x, atom y, atom w, atom h)
<span style="color: #008080;">procedure</span> <span style="color: #000000;">SierpinskyTriangle</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">level</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">w</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">h</span><span style="color: #0000FF;">)</span>
atom w2 = w/2, w4 = w/4, h2 = h/2
<span style="color: #004080;">atom</span> <span style="color: #000000;">w2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">w</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">w4</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">w</span><span style="color: #0000FF;">/</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">h</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span>
if level=1 then
<span style="color: #008080;">if</span> <span style="color: #000000;">level</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
cdCanvasBegin(cddbuffer,CD_CLOSED_LINES)
<span style="color: #000000;">cdCanvasBegin</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span><span style="color: #000000;">CD_CLOSED_LINES</span><span style="color: #0000FF;">)</span>
cdCanvasVertex(cddbuffer, x, y)
<span style="color: #000000;">cdCanvasVertex</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">)</span>
cdCanvasVertex(cddbuffer, x+w2, y+h)
<span style="color: #000000;">cdCanvasVertex</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">w2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">h</span><span style="color: #0000FF;">)</span>
cdCanvasVertex(cddbuffer, x+w, y)
<span style="color: #000000;">cdCanvasVertex</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">w</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">)</span>
cdCanvasEnd(cddbuffer)
<span style="color: #000000;">cdCanvasEnd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
else
<span style="color: #008080;">else</span>
SierpinskyTriangle(level-1, x, y, w2, h2)
<span style="color: #000000;">SierpinskyTriangle</span><span style="color: #0000FF;">(</span><span style="color: #000000;">level</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">w2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h2</span><span style="color: #0000FF;">)</span>
SierpinskyTriangle(level-1, x+w4, y+h2, w2, h2)
<span style="color: #000000;">SierpinskyTriangle</span><span style="color: #0000FF;">(</span><span style="color: #000000;">level</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">w4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">h2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">w2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h2</span><span style="color: #0000FF;">)</span>
SierpinskyTriangle(level-1, x+w2, y, w2, h2)
<span style="color: #000000;">SierpinskyTriangle</span><span style="color: #0000FF;">(</span><span style="color: #000000;">level</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">w2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">w2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h2</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
 
integer level = 7
<span style="color: #004080;">integer</span> <span style="color: #000000;">level</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">7</span>
 
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/)
<span style="color: #008080;">function</span> <span style="color: #000000;">redraw_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000080;font-style:italic;">/*posx*/</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000080;font-style:italic;">/*posy*/</span><span style="color: #0000FF;">)</span>
integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE")
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">w</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetIntInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"DRAWSIZE"</span><span style="color: #0000FF;">)</span>
cdCanvasActivate(cddbuffer)
<span style="color: #7060A8;">cdCanvasActivate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
cdCanvasClear(cddbuffer)
<span style="color: #7060A8;">cdCanvasClear</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
SierpinskyTriangle(level, w*0.05, h*0.05, w*0.9, h*0.9)
<span style="color: #000000;">SierpinskyTriangle</span><span style="color: #0000FF;">(</span><span style="color: #000000;">level</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">w</span><span style="color: #0000FF;">*</span><span style="color: #000000;">0.05</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h</span><span style="color: #0000FF;">*</span><span style="color: #000000;">0.05</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">w</span><span style="color: #0000FF;">*</span><span style="color: #000000;">0.9</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h</span><span style="color: #0000FF;">*</span><span style="color: #000000;">0.9</span><span style="color: #0000FF;">)</span>
cdCanvasFlush(cddbuffer)
<span style="color: #7060A8;">cdCanvasFlush</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
IupSetStrAttribute(dlg, "TITLE", "Sierpinsky Triangle (level %d)",{level})
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Sierpinsky Triangle (level %d)"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">level</span><span style="color: #0000FF;">})</span>
return IUP_DEFAULT
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
function map_cb(Ihandle ih)
<span style="color: #008080;">function</span> <span style="color: #000000;">map_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000000;">ih</span><span style="color: #0000FF;">)</span>
cdcanvas = cdCreateCanvas(CD_IUP, ih)
<span style="color: #000000;">cdcanvas</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCreateCanvas</span><span style="color: #0000FF;">(</span><span style="color: #004600;">CD_IUP</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ih</span><span style="color: #0000FF;">)</span>
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
<span style="color: #000000;">cddbuffer</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCreateCanvas</span><span style="color: #0000FF;">(</span><span style="color: #004600;">CD_DBUFFER</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cdcanvas</span><span style="color: #0000FF;">)</span>
cdCanvasSetBackground(cddbuffer, CD_WHITE)
<span style="color: #7060A8;">cdCanvasSetBackground</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_WHITE</span><span style="color: #0000FF;">)</span>
cdCanvasSetForeground(cddbuffer, CD_GRAY)
<span style="color: #7060A8;">cdCanvasSetForeground</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">CD_GRAY</span><span style="color: #0000FF;">)</span>
return IUP_DEFAULT
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
function esc_close(Ihandle /*ih*/, atom c)
<span style="color: #008080;">function</span> <span style="color: #000000;">esc_close</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
if c=K_ESC then return IUP_CLOSE end if
<span style="color: #008080;">if</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #004600;">K_ESC</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CLOSE</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if find(c,"+-") then
<span style="color: #008080;">if</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"+-"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
level = max(1,min(12,level+','-c))
<span style="color: #000000;">level</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">max</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">min</span><span style="color: #0000FF;">(</span><span style="color: #000000;">12</span><span style="color: #0000FF;">,</span><span style="color: #000000;">level</span><span style="color: #0000FF;">+</span><span style="color: #008000;">','</span><span style="color: #0000FF;">-</span><span style="color: #000000;">c</span><span style="color: #0000FF;">))</span>
IupRedraw(canvas)
<span style="color: #000000;">IupRedraw</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
return IUP_CONTINUE
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CONTINUE</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
procedure main()
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
IupOpen()
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
 
canvas = IupCanvas(NULL)
<span style="color: #000000;">canvas</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupCanvas</span><span style="color: #0000FF;">(</span><span style="color: #004600;">NULL</span><span style="color: #0000FF;">)</span>
IupSetAttribute(canvas, "RASTERSIZE", "640x640")
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"RASTERSIZE"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"640x640"</span><span style="color: #0000FF;">)</span>
IupSetCallback(canvas, "MAP_CB", Icallback("map_cb"))
<span style="color: #7060A8;">IupSetCallback</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"MAP_CB"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"map_cb"</span><span style="color: #0000FF;">))</span>
IupSetCallback(canvas, "ACTION", Icallback("redraw_cb"))
<span style="color: #7060A8;">IupSetCallback</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"ACTION"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"redraw_cb"</span><span style="color: #0000FF;">))</span>
 
dlg = IupDialog(canvas)
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">)</span>
IupSetAttribute(dlg, "TITLE", "Sierpinsky Triangle")
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Sierpinsky Triangle"</span><span style="color: #0000FF;">)</span>
IupSetCallback(dlg, "K_ANY", Icallback("esc_close"))
<span style="color: #7060A8;">IupSetCallback</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"K_ANY"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"esc_close"</span><span style="color: #0000FF;">))</span>
 
IupShow(dlg)
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
IupSetAttribute(canvas, "RASTERSIZE", NULL)
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"RASTERSIZE"</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">NULL</span><span style="color: #0000FF;">)</span>
IupMainLoop()
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
IupClose()
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
end procedure
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
main()</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
 
=={{header|PicoLisp}}==
[[File:Pil_sierpinski.png|thumb|right]]
Slight modification of the [[Sierpinski_triangle#PicoLisp|text version]], requires ImageMagick's display:
<langsyntaxhighlight PicoLisplang="picolisp">(de sierpinski (N)
(let (D '("1") S "0")
(do N
Line 1,589 ⟶ 2,300:
(prinl (length (car Img)) " " (length Img))
(mapc prinl Img) ) )
</syntaxhighlight>
</lang>
 
=={{header|PostScript}}==
[[File:Sierpinski-PS.png|thumb|right]]
<syntaxhighlight lang="postscript">%!PS
<lang PostScript>%!PS
 
/sierp { % level ax ay bx by cx cy
Line 1,624 ⟶ 2,335:
 
6 50 100 550 100 300 533 sierp
showpage</langsyntaxhighlight>
 
=={{header|Processing}}==
Line 1,630 ⟶ 2,341:
Should work with most versions of Processing
 
Recursive Sierpinski triangletriangles
 
<lang Processing>
===Pixel based===
 
<syntaxhighlight lang="processing">
PVector [] coord = {new PVector(0, 0), new PVector(150, 300), new PVector(300, 0)};
 
Line 1,652 ⟶ 2,366:
}
}
</syntaxhighlight>
</lang>
 
===Animated===
<syntaxhighlight lang="processing">
int depth = 5;
int interval = 50;
 
int currentTime;
int lastTime;
int progress = 0;
int lastProgress = 0;
//int finished = int(pow(3,depth));
boolean intervalExpired = false;
 
void setup() {
size(410, 230);
background(255);
fill(0);
lastTime = millis();
}
 
void draw() {
currentTime = millis();
triangle (10, 25, 100, depth);
}
 
void triangle (int x, int y, int l, int n) {
if (n == 0) {
checkIfIntervalExpired();
if (intervalExpired && progress == lastProgress) {
text("*", x, y);
lastProgress++;
intervalExpired = false;
}
progress++;
} else {
triangle(x, y+l, l/2, n-1);
triangle(x+l, y, l/2, n-1);
triangle(x+l*2, y+l, l/2, n-1);
}
}
 
void checkIfIntervalExpired() {
if (currentTime-lastTime > interval) {
lastTime = currentTime;
progress = 0;
intervalExpired = true;
}
}
 
void keyReleased() {
if (key==' ') { // reset
progress = 0;
lastProgress = 0;
background(255);
}
}
</syntaxhighlight>
 
===3D version===
<syntaxhighlight lang="processing">
import peasy.*;
 
int depth = 6; // recursion depth
int dWidth = 600;
int dHeight = 600;
 
color pyramidColor = color( 0 );
color bgColor = color( 255 );
 
// 3D Sierpinski tetrahedron vertices
PVector [] coord = {
new PVector( 0, 0, 0),
new PVector( 300, 0, 0),
new PVector( 150, 0, -260),
new PVector( 150, -245, -86.6)
};
int verts = coord.length;
float boxSize = 600/pow(3, depth);
 
// "random" start point (mid point)
PVector startPoint = new PVector(150, 183.7, 173.2);
 
PeasyCam cam;
 
void settings()
{
size(dWidth, dHeight, P3D);
}
 
void setup()
{
cam = new PeasyCam(this, startPoint.x, startPoint.y, startPoint.z, 400);
cam.setMaximumDistance(3000);
fill(pyramidColor);
stroke(pyramidColor);
}
 
void draw()
{
background(bgColor);
sierpinski(startPoint, depth);
}
 
void sierpinski(PVector currentPoint, int currentDepth)
{
if (currentDepth == 0) {
pushMatrix();
translate(currentPoint.x, 245+currentPoint.y, 260+currentPoint.z);
box(boxSize);
popMatrix();
return;
}
for (int v=0; v<verts; v++) {
sierpinski(new PVector(
(currentPoint.x+coord[v].x)/2,
(currentPoint.y+coord[v].y)/2,
(currentPoint.z+coord[v].z)/2),
currentDepth-1);
}
}
</syntaxhighlight>
 
=={{header|Prolog}}==
Line 1,664 ⟶ 2,499:
 
Works up to sierpinski(13).
<langsyntaxhighlight Prologlang="prolog">sierpinski(N) :-
sformat(A, 'Sierpinski order ~w', [N]),
new(D, picture(A)),
Line 1,693 ⟶ 2,528:
draw_Sierpinski(Window, N1, point(X, Y), Len1),
draw_Sierpinski(Window, N1, point(X1, Y1), Len1),
draw_Sierpinski(Window, N1, point(X2, Y1), Len1).</langsyntaxhighlight>
 
===Iterative version===
<langsyntaxhighlight Prologlang="prolog">:- dynamic top/1.
 
sierpinski_iterate(N) :-
Line 1,735 ⟶ 2,570:
; Lst2 = [point(X2, Y1)|Lst1]),
 
assert(top(Lst2)).</langsyntaxhighlight>
 
=={{header|Python}}==
{{libheader|Turtle}}
<langsyntaxhighlight lang="python">
# likelya thevery simplest possiblesimple version?
import turtle as t
def sier(n,length):
if (n == 0):
return
for i in range(3):
sier(n - 1, length / 2)
t.fd(length)
t.rt(120)
</syntaxhighlight>
</lang>
 
{{libheader|PyLab}}
[https://www.dropbox.com/s/gxnl8r8z0kbwi5v/Sierpinski_triangle_Phyton.png?dl=0 Sierpinski triangle image]
<syntaxhighlight lang="python">
# otra versión muy simple
from pylab import*
x=[[1,1],[1,0]]
for i in'123':x=kron(x,x)
imsave('a',x)
</syntaxhighlight>
 
{{libheader|NumPy}}
{{libheader|Turtle}}
[[File:SierpinskiTriangle-turtle.png|thumb|right]]
<langsyntaxhighlight lang="python">#!/usr/bin/env python
##########################################################################################
# a very complicated version
Line 1,775 ⟶ 2,620:
turt.forward(fwd)
return [turn, point, fwd, angle, turt]
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="python">##########################################################################################
# The drawing function
# --------------------
Line 1,836 ⟶ 2,681:
 
DrawSierpinskiTriangle(5)
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
<syntaxhighlight lang="quackery"> [ $ "turtleduck.qky" loadfile ] now!
 
[ 1 & ] is odd ( n --> b )
 
[ 4 times
[ 2dup walk
1 4 turn ]
2drop ] is square ( n/d --> )
 
[ dup
witheach
[ odd if
[ ' [ 0 0 0 ] fill
[ 2 1 square ] ]
2 1 fly ]
size -2 * 1 fly
1 4 turn
2 1 fly
-1 4 turn ] is showline ( [ --> )
[ [] 0 rot 0 join
witheach
[ tuck +
rot join swap ]
drop ] is nextline ( [ --> [ )
[ ' [ 1 ] swap
bit
1 - times
[ dup showline
nextline ]
showline ] is sierpinski ( n --> )
turtle
100 frames
5 8 turn
400 1 fly
3 8 turn
8 sierpinski
1 frame</syntaxhighlight>
 
{{output}}
[[File:Quackery Sierpinski triangle.png|500px]]
 
=={{header|R}}==
Line 1,844 ⟶ 2,734:
[[File:SierpTRo6.png|200px|right|thumb|Output SierpTRo6.png]]
[[File:SierpTRo8.png|200px|right|thumb|Output SierpTRo8.png]]
<syntaxhighlight lang="r">
<lang r>
## Plotting Sierpinski triangle. aev 4/1/17
## ord - order, fn - file name, ttl - plot title, clr - color
Line 1,865 ⟶ 2,755:
pSierpinskiT(6,,,"red");
pSierpinskiT(8);
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 1,882 ⟶ 2,772:
=={{header|Racket}}==
[[File : RacketSierpinski.png|thumb|right]]
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(require 2htdp/image)
Line 1,890 ⟶ 2,780:
(let ([t (sierpinski (- n 1))])
(freeze (above t (beside t t))))))
</syntaxhighlight>
</lang>
Test:
<langsyntaxhighlight lang="racket">
;; the following will show the graphics if run in DrRacket
(sierpinski 8)
Line 1,898 ⟶ 2,788:
(require file/convertible)
(display-to-file (convert (sierpinski 8) 'png-bytes) "sierpinski.png")
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 1,904 ⟶ 2,794:
[[File:Sierpinski-perl6.svg|thumb]]
This is a recursive solution. It is not really practical for more than 8 levels of recursion, but anything more than 7 is barely visible anyway.
<syntaxhighlight lang="raku" perl6line>my $levels = 8;
my $side = 512;
my $height = get_height($side);
Line 1,949 ⟶ 2,839:
'<g style="fill: #fff; stroke-width: 0;">',
fractal( $side/2, $height, $side*3/4, $height/2, $side/4, $height/2, $levels ),
'</g></svg>';</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "guilib.ring"
 
Line 1,997 ⟶ 2,887:
}
label1 { setpicture(p1) show() }
</syntaxhighlight>
</lang>
 
Output:
Line 2,006 ⟶ 2,896:
{{libheader|Shoes}}
[[File : sierpinski.shoes.png|thumb|right]]
<langsyntaxhighlight lang="ruby">Shoes.app(:height=>540,:width=>540, :title=>"Sierpinski Triangle") do
def triangle(slot, tri, color)
x, y, len = tri
Line 2,046 ⟶ 2,936:
end
end
end</langsyntaxhighlight>
 
{{libheader|RubyGems}}
{{libheader|JRubyArt}}
JRubyArt is a port of processing to ruby
<langsyntaxhighlight lang="ruby">
T_HEIGHT = sqrt(3) / 2
TOP_Y = 1 / sqrt(3)
Line 2,095 ⟶ 2,985:
triangle(cx0, cy0, cx1, cy1, cx2, cy2)
end
</syntaxhighlight>
</lang>
 
=={{header|Run BASIC}}==
[[File : SierpinskiRunBasic.png|thumb|right]]
<lang runbasic>graphic #g, 300,300
order = 8
width = 100
w = width * 11
dim canvas(w,w)
canvas(1,1) = 1
 
for x = 2 to 2^order -1
canvas(x,1) = 1
canvas(x,x) = 1
for y = 2 to x -1
canvas( x, y) = (canvas(x -1,y -1) + canvas(x -1, y)) mod 2
if canvas(x,y) mod 2 then #g "set "; width + (order*3) + y - x / 2;" "; x
next y
next x
render #g
#g "flush"
wait</lang>
 
=={{header|Rust}}==
Output is an SVG file.
<langsyntaxhighlight lang="rust">// [dependencies]
// svg = "0.8.0"
 
Line 2,183 ⟶ 3,052:
fn main() {
write_sierpinski_triangle("sierpinski_triangle.svg", 600, 8).unwrap();
}</langsyntaxhighlight>
 
{{out}}
[[Media:Sierpinski_triangle_rust.svg]]
See: [https://slack-files.com/T0CNUL56D-F016J89BST0-08e75660c9 sierpinski_triangle.svg] (offsite SVG image)
 
=={{header|Seed7}}==
[[File : SierpinskiSeed7.png|thumb|right]]
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "draw.s7i";
include "keybd.s7i";
Line 2,214 ⟶ 3,083:
end for;
ignore(getc(KEYBOARD));
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/graphic.htm#sierpinski]
Line 2,220 ⟶ 3,089:
=={{header|Sidef}}==
[[File:Sierpinski_triangle_sidef.png|200px|thumb|right]]
<langsyntaxhighlight lang="ruby">func sierpinski_triangle(n) -> Array {
var triangle = ['*']
{ |i|
Line 2,254 ⟶ 3,123:
var triangle = sierpinski_triangle(8)
var raw_png = triangle.to_png(bgcolor:'black', fgcolor:'red')
File('triangle.png').write(raw_png, :raw)</langsyntaxhighlight>
 
=={{header|Tcl}}==
This code maintains a queue of triangles to cut out; though a stack works just as well, the observed progress is more visually pleasing when a queue is used.
{{libheader|Tk}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
package require Tk
 
Line 2,283 ⟶ 3,152:
pack [canvas .c -width 400 -height 400 -background white]
update; # So we can see progress
sierpinski .c {200 10 390 390 10 390} 7</langsyntaxhighlight>
 
=={{header|TI-83 BASICVBScript}}==
VBScript does'nt have access to windows graphics. To achieve this i had to implement turtle graphics wtiting SVG commands to an HTML file. At the end the program opens the graphics in the default browser.
<lang ti83b>:1→X:1→Y
<syntaxhighlight lang="vb">
:Zdecimal
 
:Horizontal 3.1
option explicit
:Vertical -4.5
'outputs turtle graphics to svg file and opens it
:While 1
 
:X+1→X
const pi180= 0.01745329251994329576923690768489 ' pi/180
:DS<(Y,1
const pi=3.1415926535897932384626433832795 'pi
:While 0
class turtle
:X→Y
:1→X
dim fso
:End
dim fn
:If pxl-Test(Y-1,X) xor (pxl-Test(Y,X-1
dim svg
:PxlOn(Y,X
:End</lang>
dim iang 'radians
This could be made faster, but I just wanted to use the DS<( command
dim ori 'radians
dim incr
dim pdown
dim clr
dim x
dim y
 
public property let orient(n):ori = n*pi180 :end property
public property let iangle(n):iang= n*pi180 :end property
public sub pd() : pdown=true: end sub
public sub pu() :pdown=FALSE :end sub
public sub rt(i)
ori=ori - i*iang:
'if ori<0 then ori = ori+pi*2
end sub
public sub lt(i):
ori=(ori + i*iang)
'if ori>(pi*2) then ori=ori-pi*2
end sub
public sub bw(l)
x= x+ cos(ori+pi)*l*incr
y= y+ sin(ori+pi)*l*incr
' ori=ori+pi '?????
end sub
public sub fw(l)
dim x1,y1
x1=x + cos(ori)*l*incr
y1=y + sin(ori)*l*incr
if pdown then line x,y,x1,y1
x=x1:y=y1
end sub
Private Sub Class_Initialize()
setlocale "us"
initsvg
x=400:y=400:incr=100
ori=90*pi180
iang=90*pi180
clr=0
pdown=true
end sub
Private Sub Class_Terminate()
disply
end sub
private sub line (x,y,x1,y1)
svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>"
end sub
 
private sub disply()
dim shell
svg.WriteLine "</svg></body></html>"
svg.close
Set shell = CreateObject("Shell.Application")
shell.ShellExecute fn,1,False
end sub
 
private sub initsvg()
dim scriptpath
Set fso = CreateObject ("Scripting.Filesystemobject")
ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\"))
fn=Scriptpath & "SIERP.HTML"
Set svg = fso.CreateTextFile(fn,True)
if SVG IS nothing then wscript.echo "Can't create svg file" :vscript.quit
svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>"
svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>"
svg.writeline "</head>"&vbcrlf & "<body>"
svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">"
end sub
end class
 
 
sub sier(lev,lgth)
dim i
'wscript.echo lev,lgth
if lev=1 then
for i=1 to 3
x.fw lgth
x.lt 2
next
else
sier lev-1,lgth\2
x.fw lgth\2
sier lev-1,lgth\2
x.bw lgth\2
x.lt 1
x.fw lgth\2
x.rt 1
sier lev-1,lgth\2
x.lt 1
x.bw lgth\2
x.rt 1
end if
end sub
dim x
set x=new turtle
x.iangle=60
x.orient=0
x.incr=10
x.x=100:x.y=100
'star5
sier 7,64
set x=nothing 'outputs html file to browser
</syntaxhighlight>
=={{out}}==
[[File:Sierpinski triengle vbs.png]]
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|DOME}}
<langsyntaxhighlight ecmascriptlang="wren">import "graphics" for Canvas, Color
import "dome" for Window
 
Line 2,335 ⟶ 3,315:
}
}
}</langsyntaxhighlight>
 
{{out}}
[[File:Wren-Sierpinski_triangle_Graphical.png|400px]]
 
=={{header|XPL0}}==
[[File:TriangXPL0.gif|right]]
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
def Order=7, Size=1<<Order;
int X, Y;
Line 2,348 ⟶ 3,331:
X:= ChIn(1); \wait for keystroke
SetVid(3); \restore normal text display
]</langsyntaxhighlight>
 
=={{header|Yabasic}}==
[http://retrogamecoding.org/board/index.php?action=dlattach;topic=753.0;attach=1800;image Sierpinski Triangle 3D.png]
 
3D version.
<lang Yabasic>// Adpated from non recursive sierpinsky.bas for SmallBASIC 0.12.6 [B+=MGA] 2016-05-19 with demo mod 2016-05-29
 
//Sierpinski triangle gasket drawn with lines from any 3 given points
// WITHOUT RECURSIVE Calls
 
 
//first a sub, given 3 points of a triangle draw the traiangle within
//from the midpoints of each line forming the outer triangle
//this is the basic Sierpinski Unit that is repeated at greater depths
//3 points is 6 arguments to function plus a depth level
 
xmax=800:ymax=600
open window xmax,ymax
backcolor 0,0,0
color 255,0,0
clear window
 
sub SierLineTri(x1, y1, x2, y2, x3, y3, maxDepth)
local mx1, mx2, mx3, my1, my2, my3, ptcount, depth, i, X, Y
Y = 1
//load given set of 3 points into oa = outer triangles array, ia = inner triangles array
ptCount = 3
depth = 1
dim oa(ptCount - 1, 1) //the outer points array
oa(0, X) = x1
oa(0, Y) = y1
oa(1, X) = x2
oa(1, Y) = y2
oa(2, X) = x3
oa(2, Y) = y3
dim ia(3 * ptCount - 1, 1) //the inner points array
iaIndex = 0
while(depth <= maxDepth)
for i=0 to ptCount-1 step 3 //draw outer triangles at this level
if depth = 1 then
line oa(i,X), oa(i,Y), oa(i+1,X), oa(i+1,Y)
line oa(i+1,X), oa(i+1,Y), oa(i+2,X), oa(i+2,Y)
line oa(i,X), oa(i,Y), oa(i+2,X), oa(i+2,Y)
end if
if oa(i+1,X) < oa(i,X) then mx1 = (oa(i,X) - oa(i+1,X))/2 + oa(i+1,X) else mx1 = (oa(i+1,X) - oa(i,X))/2 + oa(i,X) endif
if oa(i+1,Y) < oa(i,Y) then my1 = (oa(i,Y) - oa(i+1,Y))/2 + oa(i+1,Y) else my1 = (oa(i+1,Y) - oa(i,Y))/2 + oa(i,Y) endif
if oa(i+2,X) < oa(i+1,X) then mx2 = (oa(i+1,X)-oa(i+2,X))/2 + oa(i+2,X) else mx2 = (oa(i+2,X)-oa(i+1,X))/2 + oa(i+1,X) endif
if oa(i+2,Y) < oa(i+1,Y) then my2 = (oa(i+1,Y)-oa(i+2,Y))/2 + oa(i+2,Y) else my2 = (oa(i+2,Y)-oa(i+1,Y))/2 + oa(i+1,Y) endif
if oa(i+2,X) < oa(i,X) then mx3 = (oa(i,X) - oa(i+2,X))/2 + oa(i+2,X) else mx3 = (oa(i+2,X) - oa(i,X))/2 + oa(i,X) endif
if oa(i+2,Y) < oa(i,Y) then my3 = (oa(i,Y) - oa(i+2,Y))/2 + oa(i+2,Y) else my3 = (oa(i+2,Y) - oa(i,Y))/2 + oa(i,Y) endif
//color 9 //testing
//draw all inner triangles
line mx1, my1, mx2, my2
line mx2, my2, mx3, my3
line mx1, my1, mx3, my3
//x1, y1 with mx1, my1 and mx3, my3
ia(iaIndex,X) = oa(i,X)
ia(iaIndex,Y) = oa(i,Y) : iaIndex = iaIndex + 1
ia(iaIndex,X) = mx1
ia(iaIndex,Y) = my1 : iaIndex = iaIndex + 1
ia(iaIndex,X) = mx3
ia(iaIndex,Y) = my3 : iaIndex = iaIndex + 1
//x2, y2 with mx1, my1 and mx2, my2
ia(iaIndex,X) = oa(i+1,X)
ia(iaIndex,Y) = oa(i+1,Y) : iaIndex = iaIndex + 1
ia(iaIndex,X) = mx1
ia(iaIndex,Y) = my1 : iaIndex = iaIndex + 1
ia(iaIndex,X) = mx2
ia(iaIndex,Y) = my2 : iaIndex = iaIndex + 1
//x3, y3 with mx3, my3 and mx2, my2
ia(iaIndex,X) = oa(i+2,X)
ia(iaIndex,Y) = oa(i+2,Y) : iaIndex = iaIndex + 1
ia(iaIndex,X) = mx2
ia(iaIndex,Y) = my2 : iaIndex = iaIndex + 1
ia(iaIndex,X) = mx3
ia(iaIndex,Y) = my3 : iaIndex = iaIndex + 1
next i
//update and prepare for next level
ptCount = ptCount * 3
depth = depth + 1
redim oa(ptCount - 1, 1 )
for i = 0 to ptCount - 1
oa(i, X) = ia(i, X)
oa(i, Y) = ia(i, Y)
next i
redim ia(3 * ptCount - 1, 1)
iaIndex = 0
wend
end sub
 
//Test Demo for the sub (NEW as 2016 - 05 - 29 !!!!!)
cx=xmax/2
cy=ymax/2
r=cy - 20
N=3
for i = 0 to 2
color 64+42*i,64+42*i,64+42*i
SierLineTri(cx, cy, cx+r*cos(2*pi/N*i), cy +r*sin(2*pi/N*i), cx + r*cos(2*pi/N*(i+1)), cy + r*sin(2*pi/N*(i+1)), 5)
next i
</lang>
 
Simple recursive version
<lang Yabasic>w = 800 : h = 600
open window w, h
window origin "lb"
 
sub SierpinskyTriangle(level, x, y, w, h)
local w2, w4, h2
w2 = w/2 : w4 = w/4 : h2 = h/2
if level=1 then
new curve
line to x, y
line to x+w2, y+h
line to x+w, y
line to x, y
else
SierpinskyTriangle(level-1, x, y, w2, h2)
SierpinskyTriangle(level-1, x+w4, y+h2, w2, h2)
SierpinskyTriangle(level-1, x+w2, y, w2, h2)
end if
end sub
 
SierpinskyTriangle(7, w*0.05, h*0.05, w*0.9, h*0.9)</lang>
 
=={{header|zkl}}==
Line 2,489 ⟶ 3,337:
Uses the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl
{{trans|XPL0}}
<langsyntaxhighlight lang="zkl">const Order=8, Size=(1).shiftLeft(Order);
img:=PPM(300,300);
foreach y,x in (Size,Size){ if(x.bitAnd(y)==0) img[x,y]=0xff0000 }
img.write(File("sierpinskiTriangle.ppm","wb"));</langsyntaxhighlight>
 
 
2,120

edits