Sierpinski triangle/Graphical: Difference between revisions

m
m (→‎{{header|Phix}}: added syntax colouring the hard way)
(41 intermediate revisions by 19 users not shown)
Line 10:
It uses 320x200 mode, so the maximum order is 7.
 
<langsyntaxhighlight 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
Line 83:
section .bss
order: resb 1 ; Order of Sierpinski triangle
vmode: resb 1 ; Store old video mode (to restore later)</langsyntaxhighlight>
 
=={{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 167 ⟶ 200:
 
}
</syntaxhighlight>
</lang>
 
Document class:
<syntaxhighlight lang="actionscript3">
<lang ActionScript3>
package {
Line 193 ⟶ 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 216 ⟶ 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 322 ⟶ 438:
SDL_RenderDrawLine(sdlren, x1, y1, x2, y2);
}
%}</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
{{libheader|GDIP}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">#NoEnv
#SingleInstance, Force
SetBatchLines, -1
Line 424 ⟶ 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 436 ⟶ 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 554 ⟶ 985:
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
[[file:STriCpp.png|thumb|right|200px]]
<langsyntaxhighlight lang="cpp">
#include <windows.h>
#include <string>
Line 679 ⟶ 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 699 ⟶ 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 732 ⟶ 1,246:
}]),
wxFrame:show(Frame).
</syntaxhighlight>
</lang>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM SIERPINSKY
 
Line 752 ⟶ 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 795 ⟶ 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 813 ⟶ 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 860 ⟶ 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 904 ⟶ 1,508:
fmt.Println(err)
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 914 ⟶ 1,518:
 
[[File:Sierpinski-Haskell.svg|thumb|Sierpinski Triangle]]
<langsyntaxhighlight lang="haskell">import Diagrams.Prelude
import Diagrams.Backend.Cairo.CmdLine
 
Line 926 ⟶ 1,530:
 
main = defaultMain $ sierpinski !! 7
</syntaxhighlight>
</lang>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 932 ⟶ 1,536:
 
[[File:Sierpinski_Triangle_Unicon.PNG|thumb|Sample Output for order=8]]
<langsyntaxhighlight Iconlang="icon">link wopen
 
procedure main(A)
Line 947 ⟶ 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 1,039 ⟶ 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,104 ⟶ 1,695:
});
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 1,115 ⟶ 1,706:
{{Works with|Chrome}}
[[File:SierpTRjs.png|200px|right|thumb|Output SierpTRjs.png]]
<langsyntaxhighlight lang="html">
<!-- SierpinskiTriangle.html -->
<html>
Line 1,173 ⟶ 1,764:
<!--canvas id="cvsId" width="1280" height="1280" style="border: 2px inset;"></canvas-->
</body></html>
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 1,179 ⟶ 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,204 ⟶ 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,260 ⟶ 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,337 ⟶ 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,354 ⟶ 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,363 ⟶ 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,374 ⟶ 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,446 ⟶ 2,073:
SCREEN_HEIGHT := 480
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">open Graphics
 
let round v =
Line 1,496 ⟶ 2,123:
let res = loop 6 [ initial_triangle ] in
List.iter draw_triangle res;
ignore (read_key ())</langsyntaxhighlight>
 
run with:
Line 1,505 ⟶ 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,518 ⟶ 2,145:
pSierpinskiT(9); \\ SierpT9.png
}
</langsyntaxhighlight>
{{Output}}
Line 1,529 ⟶ 2,156:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">my $levels = 6;
my $side = 512;
my $height = get_height($side);
Line 1,576 ⟶ 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,582 ⟶ 2,209:
Can resize, and change the level from 1 to 12 (press +/-).
{{libheader|Phix/pGUI}}
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\SierpinskyTriangle.exw</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 1,653 ⟶ 2,280:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
 
=={{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,673 ⟶ 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,708 ⟶ 2,335:
 
6 50 100 550 100 300 533 sierp
showpage</langsyntaxhighlight>
 
=={{header|Processing}}==
Line 1,718 ⟶ 2,345:
===Pixel based===
 
<syntaxhighlight lang="processing">
<lang Processing>
PVector [] coord = {new PVector(0, 0), new PVector(150, 300), new PVector(300, 0)};
 
Line 1,739 ⟶ 2,366:
}
}
</syntaxhighlight>
</lang>
 
===Animated===
<syntaxhighlight lang="processing">
<lang Processing>
int depth = 5;
int interval = 50;
Line 1,796 ⟶ 2,423:
}
}
</syntaxhighlight>
</lang>
 
===3D version===
<syntaxhighlight lang="processing">
<lang Processing>
import peasy.*;
 
Line 1,860 ⟶ 2,487:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Prolog}}==
Line 1,872 ⟶ 2,499:
 
Works up to sierpinski(13).
<langsyntaxhighlight Prologlang="prolog">sierpinski(N) :-
sformat(A, 'Sierpinski order ~w', [N]),
new(D, picture(A)),
Line 1,901 ⟶ 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,943 ⟶ 2,570:
; Lst2 = [point(X2, Y1)|Lst1]),
 
assert(top(Lst2)).</langsyntaxhighlight>
 
=={{header|Python}}==
{{libheader|Turtle}}
<langsyntaxhighlight lang="python">
# a very simple version
import turtle as t
Line 1,957 ⟶ 2,584:
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,983 ⟶ 2,620:
turt.forward(fwd)
return [turn, point, fwd, angle, turt]
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="python">##########################################################################################
# The drawing function
# --------------------
Line 2,044 ⟶ 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 2,052 ⟶ 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 2,073 ⟶ 2,755:
pSierpinskiT(6,,,"red");
pSierpinskiT(8);
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 2,090 ⟶ 2,772:
=={{header|Racket}}==
[[File : RacketSierpinski.png|thumb|right]]
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(require 2htdp/image)
Line 2,098 ⟶ 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 2,106 ⟶ 2,788:
(require file/convertible)
(display-to-file (convert (sierpinski 8) 'png-bytes) "sierpinski.png")
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,112 ⟶ 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 2,157 ⟶ 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 2,205 ⟶ 2,887:
}
label1 { setpicture(p1) show() }
</syntaxhighlight>
</lang>
 
Output:
Line 2,214 ⟶ 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,254 ⟶ 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,303 ⟶ 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,391 ⟶ 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,422 ⟶ 3,083:
end for;
ignore(getc(KEYBOARD));
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/graphic.htm#sierpinski]
Line 2,428 ⟶ 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,462 ⟶ 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,491 ⟶ 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,543 ⟶ 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,556 ⟶ 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,697 ⟶ 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