Sierpinski triangle: Difference between revisions
→{{header|Factor}}
(175 intermediate revisions by 45 users not shown) | |||
Line 1:
{{task|Fractals}}
;Task
Produce an ASCII representation of a
;Example
The Sierpinski triangle of order '''4''' should look like this:
<pre>
Line 27:
;Related tasks
*
*
<br><br>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">F sierpinski(n)
V d = [String(‘*’)]
L(i) 0 .< n
V sp = ‘ ’ * (2 ^ i)
d = d.map(x -> @sp‘’x‘’@sp) [+] d.map(x -> x‘ ’x)
R d
print(sierpinski(4).join("\n"))</syntaxhighlight>
{{out}}
<pre>
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
</pre>
=={{header|8080 Assembly}}==
<syntaxhighlight lang="8080asm">argmt: equ 5Dh ; Command line argument
puts: equ 9 ; CP/M syscall to print a string
putch: equ 2 ; CP/M syscall to print a character
org 100h
mvi b,4 ; Default order is 4
mvi e,' ' ; Keep space in E since we're saving it anyway
lda argmt ; Argument given?
cmp e ; If not, use default
jz start
sui '0' ; Make sure given N makes sense
cpi 3 ; <3?
jc start
cpi 8 ; >=8?
jnc start
mov b,a
start: mvi a,1 ; Find size (2 ** order)
shift: rlc
dcr b
jnz shift
mov b,a ; B = size
mov c,a ; C = current line
line: mov d,c ; D = column
indent: mov a,e ; Indent line
call chout
dcr d
jnz indent
column: mov a,c ; line + col <= size?
add d
dcr a
cmp b
jnc cdone
mov a,c ; (line - 1) & col == 0?
dcr a
ana d
mov a,e ; space if not, star if so
jnz print
mvi a,'*'
print: call chout
mov a,e
call chout
inr d
jmp column
cdone: push b ; done, print newline
push d
lxi d,nl
mvi c,puts
call 5
pop d
pop b
dcr c ; next line
jnz line
ret
chout: push b ; save BC and DE
push d
mov e,a ; print character
mvi c,putch
call 5
pop d ; restore BC and DE
pop b
ret
nl: db 13,10,'$'</syntaxhighlight>
{{out}}
For order 4 (default if no given):
<pre> *
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *</pre>
=={{header|8086 Assembly}}==
<syntaxhighlight lang="asm">putch: equ 2 ; MS-DOS syscall to print character
puts: equ 9 ; MS-DOS syscall to print string
argmt: equ 5Dh ; MS-DOS still has FCB in same place as CP/M
cpu 8086
org 100h
section .text
mov cx,4 ; Default order is 4
mov al,[argmt]
sub al,'3' ; Argument is there and makes sense? (3 - 7)
cmp al,7-3
ja start ; If not, use default
add al,3 ; If so, use it
mov cl,al
start: mov bl,1 ; Let BL be the size (2 ** order)
shl bl,cl
mov bh,bl ; Let BH be the current line
line: mov cl,bh ; Let CL be the column
mov dl,' ' ; Indent line with spaces
mov ah,putch
indent: int 21h
loop indent
column: mov al,cl ; line + column <= size?
add al,bh
cmp al,bl
ja .done ; then column is done
mov al,bh ; (line - 1) & column == 0?
dec al
test al,cl
jnz .print ; space if not, star if so
mov dl,'*'
.print: int 21h
mov dl,' '
int 21h
inc cx ; next column
jmp column
.done: mov dx,nl ; done, print newline
mov ah,puts
int 21h
dec bh ; next line
jnz line
ret
nl: db 13,10,'$'</syntaxhighlight>
{{out}}
For order 4 (default if no order given):
<pre> *
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *</pre>
=={{header|ACL2}}==
<
(if (endp (rest prev))
(list 1)
Line 71 ⟶ 252:
(let ((height (1- (expt 2 levels))))
(print-odds (pascal-triangle height)
height)))</
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Main()
BYTE x,y,size=[16]
Graphics(0)
PutE() PutE()
y=size-1
DO
FOR x=1 TO y+2
DO Put(' ) OD
FOR x=0 TO size-y-1
DO
IF (x&y)=0 THEN
Print("* ")
ELSE
Print(" ")
FI
OD
PutE()
IF y=0 THEN
EXIT
FI
y==-1
OD</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sierpinski_triangle.png Screenshot from Atari 8-bit computer]
<pre>
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
</pre>
=={{header|Ada}}==
This Ada example creates a string of the binary value for each line, converting the '0' values to spaces.
<
with Ada.Strings.Fixed;
with Interfaces; use Interfaces;
Line 127 ⟶ 356:
Sierpinski(N);
end loop;
end Sieteri_Triangles;</
alternative using modular arithmetic:
<
with Ada.Text_IO;
Line 157 ⟶ 386:
end if;
Sierpinski (N);
end Main;</
{{out}}
<pre>XXXXXXXXXXXXXXXX
Line 181 ⟶ 410:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
<!-- {{does not work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 - test missing transput}} -->
<
FLEX[0]STRING d := "*";
FOR i TO n DO
Line 196 ⟶ 425:
);
printf(($gl$,sierpinski(4)))</
=={{header|ALGOL W}}==
{{Trans|C}}
<syntaxhighlight lang="algolw">begin
integer SIZE;
SIZE := 16;
for y := SIZE - 1 step - 1 until 0 do begin
integer x;
for i := 0 until y - 1 do writeon( " " );
x := 0;
while x + y < SIZE do begin
writeon( if number( bitstring( x ) and bitstring( y ) ) not = 0 then " " else "* " );
x := x + 1
end while_x_plus_y_lt_SIZE ;
write();
end for_y
end.</syntaxhighlight>
=={{header|AppleScript}}==
{{Trans|JavaScript}}
{{Trans|Haskell}}
Centering any previous triangle block over two adjacent duplicates:
<syntaxhighlight lang="applescript">------------------- SIERPINKSI TRIANGLE ------------------
-- sierpinski :: Int -> [String]
on sierpinski(n)
if n > 0 then
set previous to sierpinski(n - 1)
set padding to replicate(2 ^ (n - 1), space)
script alignedCentre
on |λ|(s)
concat(padding & s & padding)
end |λ|
end script
script adjacentDuplicates
on |λ|(s)
unwords(replicate(2, s))
end |λ|
end script
-- Previous triangle block centered,
-- and placed on 2 adjacent duplicates.
map(alignedCentre, previous) & map(adjacentDuplicates, previous)
else
{"*"}
end if
end sierpinski
--------------------------- TEST -------------------------
on run
unlines(sierpinski(4))
end run
-------------------- GENERIC FUNCTIONS -------------------
-- concat :: [[a]] -> [a] | [String] -> String
on concat(xs)
if length of xs > 0 and class of (item 1 of xs) is string then
set acc to ""
else
set acc to {}
end if
repeat with i from 1 to length of xs
set acc to acc & item i of xs
end repeat
acc
end concat
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
-- unlines, unwords :: [String] -> String
on unlines(xs)
intercalate(linefeed, xs)
end unlines
on unwords(xs)
intercalate(space, xs)
end unwords</syntaxhighlight>
{{Out}}
<pre> *
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *</pre>
Or generating each line as an XOR / Rule 90 / Pascal triangle rewrite of the previous line.
{{Trans|JavaScript}}
<syntaxhighlight lang="applescript">----------- SIERPINSKI TRIANGLE BY XOR / RULE 90 ---------
-- sierpinskiTriangle :: Int -> String
on sierpinskiTriangle(intOrder)
Line 215 ⟶ 582:
-- pascalModTwo :: Int -> [[String]]
script pascalModTwo
on
-- addRow [[Int]] -> [[Int]]
Line 225 ⟶ 592:
-- is reduced here to a rule from
-- two parent characters above,
-- to the child character below.
-- Rule 90 also reduces to this XOR relationship
-- between left and right neighbours.
-- rule :: Character -> Character -> Character
script rule
on
if a = b then
space
Line 235 ⟶ 605:
"*"
end if
end
end script
Line 241 ⟶ 611:
end nextRow
on
xs & {nextRow(item -1 of xs)}
end
end script
foldr(addRow, {{"*"}},
end
end script
Line 256 ⟶ 626:
script centred
on
set strIndent to indent of sofar
{triangle:strIndent & intercalate(space, row) & linefeed & ¬
triangle of sofar, indent:strIndent & space}
end
end script
triangle of foldr(centred, {triangle:"", indent:""}, ¬
pascalModTwo's
end sierpinskiTriangle
--------------------------- TEST -------------------------
on run
Line 276 ⟶ 646:
set the clipboard to strTriangle
strTriangle
end run
-------------------- GENERIC FUNCTIONS -------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m > n then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from
set end of lst to
end repeat
return lst
end
-- foldr :: (a -> b -> a) -> a -> [b] -> a
on foldr(f, startValue, xs)
set v to startValue
set
end repeat
end foldr
Line 318 ⟶ 686:
end intercalate
--
on
if
else
end if
end min
-- Lift 2nd class handler function into 1st class script wrapper
Line 339 ⟶ 702:
else
script
property
end script
end if
end mReturn
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end zipWith</syntaxhighlight>
{{Out}}
<pre> *
* *
Line 363 ⟶ 736:
* * * * * * * * * * * * * * * *
</pre>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">sierpinski: function [order][
s: shl 1 order
loop (s-1)..0 'y [
do.times: y -> prints " "
loop 0..dec s-y 'x [
if? zero? and x y -> prints "* "
else -> prints " "
]
print ""
]
]
sierpinski 4</syntaxhighlight>
{{out}}
<pre> *
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *</pre>
=={{header|ATS}}==
<syntaxhighlight lang="ats">
(* ****** ****** *)
//
Line 408 ⟶ 816:
//
} (* end of [main0] *)
</syntaxhighlight>
=={{header|AutoHotkey}}==
ahk [http://www.autohotkey.com/forum/viewtopic.php?t=44657&postdays=0&postorder=asc&start=150 discussion]
<
MsgBox % Triangle(A_Index)
Line 430 ⟶ 838:
Triangle(n-1,x+u,y+u) ; smaller triangle down right
Return t
}</syntaxhighlight>
=={{header|APL}}==
<syntaxhighlight lang="apl">A←67⍴0⋄A[34]←1⋄' #'[1+32 67⍴{~⊃⍵:⍵,∇(1⌽⍵)≠¯1⌽⍵⋄⍬}A]</syntaxhighlight>
=={{header|AWK}}==
<
# syntax: GAWK -f WST.AWK [-v X=anychar] iterations
# example: GAWK -f WST.AWK -v X=* 2
Line 455 ⟶ 868:
}
exit(0)
}</
=={{header|BASH (feat. sed & tr)}}==
Line 463 ⟶ 876:
other language just as well, but is particularly well suited for
tools like sed and tr.
<
#!/bin/bash
Line 487 ⟶ 900:
rec $1 | tr 'dsx' ' *'
</syntaxhighlight>
=={{header|Bash}}==
{{trans|BASH (feat. sed & tr)}}
{{works with|Bash|3.2.57}}
{{works with|Bash|5.2.9}}
<syntaxhighlight lang="bash">
#!/bin/bash
### BASH (pure-bash)
### https://rosettacode.org/wiki/Bourne_Again_SHell
### Ported from bash+sed+tr version
### Tested with bash versions 3.2.57 and 5.2.9
### This version completely avoids any number-theoretic workarounds.
### Instead, it repeatedly replaces characters by "blocks of characters".
### The strategy is in no way bash-specific,
### it would work with any other language just as well,
### but is particularly well suited for Bash Parameter Expansion
### ${parameter/pattern/string}
### syntax used for pure-bash global-pattern-substitution.
### (Search "man bash" output for "Parameter Expansion" for additional details
### on the
### ${parameter/pattern/string}
### and
### ${parameter:-word}
### syntax)
# Basic principle:
#
#
# x -> dxd d -> dd s -> s
# xsx dd s
#
# In the end all 'd' and 's' are removed.
function rec(){
if [ $1 == 0 ]
then
echo "x"
else
rec $[ $1 - 1 ] | while read line ; do
A="$line" ; A="${A//d/dd}" ; A="${A//x/dxd}" ; echo "$A"
A="$line" ; A="${A//d/dd}" ; A="${A//x/xsx}" ; echo "$A"
done
fi
}
### If the script has no arguments, then the default is n=4
### Else n is the first argument to the script
export n="${1:-4}"
B="$(rec "$n")" ; B="${B//d/ }" ; B="${B//s/ }" ; B="${B//x/*}"
echo "$B"
</syntaxhighlight>
=={{header|BASIC}}==
Line 494 ⟶ 961:
<!-- {{works with|RapidQ}} doesn't work for me -- Erik Siers, 12 March 2012 -->
<
CLS
Line 507 ⟶ 974:
triangle x + length * 2, y + length, length / 2, n - 1
END IF
END SUB</
Note: The total height of the triangle is 2 * parameter ''length''. It should be power of two so that the pattern matches evenly with the character cells. Value 16 will thus create pattern of 32 lines.
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">
clg
call triangle (1, 1, 60)
end
subroutine triangle (x, y, l)
if l = 0 then
color blue
text (x, y, "*")
else
call triangle (x, y + l, int(l/2))
call triangle (x + l, y, int(l/2))
call triangle (x + l * 2, y + l, int(l/2))
end if
end subroutine
</syntaxhighlight>
==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic"> MODE 8
OFF
Line 528 ⟶ 1,015:
PROCsierpinski(x%+l%+l%, y%+l%, l% DIV 2)
ENDIF
ENDPROC</
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">sub sier(x as uinteger, y as uinteger, l as uinteger)
if l=0 then
locate y, x: print "*"
else
sier(x,y+l,l\2)
sier(x+l,y,l\2)
sier(x+2*l,y+l,l\2)
end if
end sub
cls
sier(1,1,2^3)</syntaxhighlight>
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 PROGRAM "Triangle.bas"
110 TEXT 40
120 CALL TRIANGLE(1,1,8)
130 DEF TRIANGLE(X,Y,L)
140 IF L=0 THEN
150 PRINT AT Y,X:"*"
160 ELSE
170 CALL TRIANGLE(X,Y+L,INT(L/2))
180 CALL TRIANGLE(X+L,Y,INT(L/2))
190 CALL TRIANGLE(X+2*L,Y+L,INT(L/2))
200 END IF
210 END DEF</syntaxhighlight>
=={{header|BCPL}}==
{{trans|C}}
<syntaxhighlight lang="bcpl">get "libhdr"
manifest $( SIZE = 1 << 4 $)
let start() be
$( for y = SIZE-1 to 0 by -1 do
$( for i=1 to y do wrch(' ')
for x=0 to SIZE-y-1 do
writes((x & y) ~= 0 -> " ", "** ")
wrch('*N')
$)
$)</syntaxhighlight>
{{out}}
<pre> *
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *</pre>
=={{header|Befunge}}==
Line 534 ⟶ 1,081:
This is a version of the cellular automaton (''rule 90'') construction. The order, ''N'', is specified by the first number on the stack. It uses a single line of the playfield for the cell buffer, so the upper limit for ''N'' should be 5 on a standard Befunge-93 implementation. Interpreters with poor memory handling may not work with anything over 3, though, and a Befunge-98 interpreter should theoretically be unlimited.
<
v:$_:#`0#\\#00#:p#->#1<
>2/1\0p:2/\::>1-:>#v_1v
Line 540 ⟶ 1,087:
vg11<\*g11!:g 0-1:::<p<
>!*+!!\0g11p\ 0p1-:#^_v
@$$_\#!:#::#-^#1\$,+55<</
=={{header|Burlesque}}==
<syntaxhighlight lang="burlesque">{JPp{
-.'sgve!
J{JL[2./+.' j.*PppP.+PPj.+}m[
j{J" "j.+.+}m[
.+
}{vv{"*"}}PPie} 's sv
4 'sgve!unsh</syntaxhighlight>
=={{header|BQN}}==
<syntaxhighlight lang="bqn">Sierp ← {" •" ⊏˜ (⌽↕2⋆𝕩)⌽˘∾˘∾⟜0¨∧´∘∨⌜˜⥊↕2⥊˜𝕩}</syntaxhighlight>
{{out}}
<pre>
Sierp 3
┌─
╵" •
• •
• •
• • • •
• •
• • • •
• • • •
• • • • • • • • "
┘
</pre>
=={{header|C}}==
<
#define SIZE (1 << 4)
Line 555 ⟶ 1,130:
}
return 0;
}</
===Automaton===
This solution uses a cellular automaton (''rule 90'') with a proper initial status.
<
#include <stdlib.h>
#include <stdbool.h>
Line 593 ⟶ 1,168:
}
free(cp);
}</
<
{
int i;
Line 612 ⟶ 1,187:
free(b);
}</
<
{
sierpinski_triangle(4);
return EXIT_SUCCESS;
}</
=={{header|C sharp|C#}}==
<
using System.Collections;
Line 659 ⟶ 1,234:
}
}
}</
<
class Program {
static void Main(string[] args) {
Line 668 ⟶ 1,243:
}
}
}</
{{trans|C}}
{{works with|C sharp|C#|6.0+}}
<syntaxhighlight lang="csharp">using static System.Console;
class Sierpinsky
{
static void Main(string[] args)
{
int order;
if(!int.TryParse(args.Length > 0 ? args[0] : "", out order)) order = 4;
int size = (1 << order);
for (int y = size - 1; y >= 0; y--, WriteLine())
{
for (int i = 0; i < y; i++) Write(' ');
for (int x = 0; x + y < size; x++)
Write((x & y) != 0 ? " " : "* ");
}
}
}</syntaxhighlight>
{{trans|OCaml}}
{{works with|C sharp|C#|3.0+}}
<
using System.Collections.Generic;
using System.Linq;
Line 698 ⟶ 1,292:
Console.WriteLine(s);
}
}</
Or, with fold / reduce (a.k.a. aggregate):
<
using System.Collections.Generic;
using System.Linq;
Line 727 ⟶ 1,321:
foreach(string s in Sierpinski(4)) { Console.WriteLine(s); }
}
}</
=={{header|C++}}==
{{works with|C++11}}
A STL-centric recursive solution that uses the new lambda functions in C++11.
<
#include <string>
#include <list>
Line 766 ⟶ 1,360:
sierpinski(4, ostream_iterator<string>(cout, "\n"));
return 0;
}</
=={{header|Clojure}}==
Line 772 ⟶ 1,366:
{{trans|Common Lisp}}
With a touch of Clojure's sequence handling.
<
(:require [clojure.contrib.math :as math]))
Line 797 ⟶ 1,391:
(bit-xor (bit-shift-left v 1) (bit-shift-right v 1))))))
(sierpinski-triangle 4)</
=={{header|CLU}}==
{{trans|Fortran}}
<syntaxhighlight lang="clu">sierpinski = proc (size: int) returns (string)
ss: stream := stream$create_output()
for i: int in int$from_to(0, size*4-1) do
c: int := 1
for j: int in int$from_to(1, size*4-1-i) do
stream$putc(ss, ' ')
end
for k: int in int$from_to(0, i) do
if c//2=0 then
stream$puts(ss, " ")
else
stream$puts(ss, " *")
end
c := c*(i-k)/(k+1)
end
stream$putc(ss, '\n')
end
return(stream$get_contents(ss))
end sierpinski
start_up = proc ()
stream$puts(
stream$primary_output(),
sierpinski(4)
)
end start_up</syntaxhighlight>
{{out}}
<pre> *
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *</pre>
=={{header|COBOL}}==
{{trans|Fortran}} and retains a more Fortran-like coding style than is really idiomatic in COBOL.
<
program-id. sierpinski-triangle-program.
data division.
Line 836 ⟶ 1,477:
if r is equal to zero then display ' * ' with no advancing.
if r is not equal to zero then display ' ' with no advancing.
compute c = c * (i - k) / (k + 1).</
=={{header|Comal}}==
<syntaxhighlight lang="comal">0010 DIM part$(FALSE:TRUE) OF 2
0020 part$(FALSE):=" ";part$(TRUE):="* "
0030 INPUT "Order? ":order#
0040 size#:=2^order#
0050 FOR y#:=size#-1 TO 0 STEP -1 DO
0060 PRINT " "*y#,
0070 FOR x#:=0 TO size#-y#-1 DO PRINT part$(x# BITAND y#=0),
0080 PRINT
0090 ENDFOR y#
0100 END</syntaxhighlight>
{{out}}
<pre>Order? 4
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *</pre>
=={{header|Common Lisp}}==
<
(loop with size = (expt 2 order)
repeat size
Line 845 ⟶ 1,516:
do (fresh-line)
(loop for i below (integer-length v)
do (princ (if (logbitp i v) "*" " ")))))</
Printing each row could also be done by printing the integer in base 2 and replacing zeroes with spaces: <tt>(princ (substitute #\Space #\0 (format nil "~%~2,vR" (1- (* 2 size)) v)))</tt>
Line 853 ⟶ 1,524:
Alternate approach:
<
(if (= n 0) '("*")
(nconc (mapcar (lambda (e) (format nil "~A~A~0@*~A" (make-string (expt 2 (1- n)) :initial-element #\ ) e)) (sierpinski (1- n)))
(mapcar (lambda (e) (format nil "~A ~A" e e)) (sierpinski (1- n))))))
(mapc #'print (sierpinski 4))</
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
include "argv.coh";
var order: uint8 := 4; # default order
# Read order from command line if there is an argument
ArgvInit();
var argmt := ArgvNext();
if argmt != 0 as [uint8] then
var a: int32;
(a, argmt) := AToI(argmt);
if a<3 or 7<a then
print("Order must be between 3 and 7.");
print_nl();
ExitWithError();
end if;
order := a as uint8;
end if;
var one: uint8 := 1; # shift argument can't be constant...
var size: uint8 := one << order;
var y: uint8 := size;
while y > 0 loop
var x: uint8 := 0;
while x < y-1 loop
print_char(' ');
x := x + 1;
end loop;
x := 0;
while x + y <= size loop
if x & (y-1) != 0 then
print(" ");
else
print("* ");
end if;
x := x + 1;
end loop;
print_nl();
y := y - 1;
end loop;</syntaxhighlight>
{{out}}
<pre> *
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *</pre>
=={{header|D}}==
===Run-time Version===
<
import std.stdio, std.algorithm, std.string, std.array;
Line 873 ⟶ 1,606:
}
d.join('\n').writeln;
}</
{{out}}
<pre> *
Line 894 ⟶ 1,627:
===Compile-time Version===
Same output.
<
string sierpinski(int level) pure nothrow /*@safe*/ {
Line 907 ⟶ 1,640:
pragma(msg, 4.sierpinski);
void main() {}</
===Simple Version===
{{trans|C}}
Same output.
<
import core.stdc.stdio: putchar;
Line 928 ⟶ 1,661:
void main() nothrow @safe @nogc {
4.showSierpinskiTriangle;
}</
===Alternative Version===
This uses a different algorithm and shows a different output.
<
import std.algorithm: swap;
Line 973 ⟶ 1,706:
'\n'.putchar;
}
}</
{{out}}
<pre> #
Line 1,044 ⟶ 1,777:
=={{header|Delphi}}==
{{trans|DWScript}}
<
{$APPTYPE CONSOLE}
Line 1,069 ⟶ 1,802:
begin
PrintSierpinski(4);
end.</
=={{header|Draco}}==
{{trans|C}}
<syntaxhighlight lang="draco">word SIZE = 1 << 4;
proc nonrec main() void:
unsigned SIZE x, y;
for y from SIZE-1 downto 0 do
for x from 1 upto y do write(' ') od;
for x from 0 upto SIZE - y - 1 do
write(if x & y ~= 0 then " " else "* " fi)
od;
writeln()
od
corp</syntaxhighlight>
{{out}}
<pre> *
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *</pre>
=={{header|DWScript}}==
{{trans|E}}
<
var
x, y, size : Integer;
Line 1,090 ⟶ 1,855:
PrintSierpinski(4);
</syntaxhighlight>
=={{header|E}}==
<
def size := 2**order
for y in (0..!size).descending() {
Line 1,102 ⟶ 1,867:
out.println()
}
}</
<syntaxhighlight lang
Non-ASCII version (quality of results will depend greatly on text renderer):
<
def size := 2**order
for y in (0..!size).descending() {
Line 1,116 ⟶ 1,881:
out.println()
}
}</
=={{header|Elixir}}==
{{trans|Erlang}}
<
def sierpinski_triangle(n) do
f = fn(x) -> IO.puts "#{x}" end
Line 1,133 ⟶ 1,898:
end
RC.sierpinski_triangle(4)</
=={{header|Elm}}==
{{trans|Haskell}}
<
import Html exposing (..)
import Html.Attributes as A exposing (..)
Line 1,187 ⟶ 1,953:
, ("font-size", "1em")
, ("text-align", "left")
]</
Link to live demo: http://dc25.github.io/sierpinskiElm/
Line 1,193 ⟶ 1,959:
=={{header|Erlang}}==
{{trans|OCaml}}
<
-export([triangle/1]).
Line 1,203 ⟶ 1,969:
triangle(N, Down, Sp) ->
NewDown = [Sp++X++Sp || X<-Down]++[X++" "++X || X <- Down],
triangle(N-1, NewDown, Sp++Sp).</
=={{header|Euphoria}}==
{{trans|BASIC}}
<
if n = 0 then
position(y,x) puts(1,'*')
Line 1,218 ⟶ 1,984:
clear_screen()
triangle(1,1,8,4)</
=={{header|Excel}}==
===LAMBDA===
Binding the names '''sierpinskiTriangle''', '''sierpCentered''' and '''sierpDoubled''' to the following lambda expressions in the Name Manager of the Excel WorkBook:
(See [https://www.microsoft.com/en-us/research/blog/lambda-the-ultimatae-excel-worksheet-function/ LAMBDA: The ultimate Excel worksheet function])
{{Works with|Office 365 betas 2021}}
<syntaxhighlight lang="lisp">sierpinskiTriangle
=LAMBDA(c,
LAMBDA(n,
IF(0 = n,
c,
LET(
prev, sierpinskiTriangle(c)(n - 1),
APPENDROWS(
sierpCentered(prev)
)(
sierpDoubled(prev)
)
)
)
)
)
sierpCentered
=LAMBDA(grid,
LET(
nRows, ROWS(grid),
padding, IF(
SEQUENCE(nRows, nRows, 1, 1),
" "
),
APPENDCOLS(
APPENDCOLS(padding)(grid)
)(padding)
)
)
sierpDoubled
=LAMBDA(grid,
APPENDCOLS(
APPENDCOLS(grid)(
IF(SEQUENCE(ROWS(grid), 1, 1, 1),
" "
)
)
)(grid)
)</syntaxhighlight>
and also assuming the following generic bindings in the Name Manager for the WorkBook:
<syntaxhighlight lang="lisp">APPENDCOLS
=LAMBDA(xs,
LAMBDA(ys,
LET(
nx, COLUMNS(xs),
colIndexes, SEQUENCE(1, nx + COLUMNS(ys)),
rowIndexes, SEQUENCE(MAX(ROWS(xs), ROWS(ys))),
IFERROR(
IF(nx < colIndexes,
INDEX(ys, rowIndexes, colIndexes - nx),
INDEX(xs, rowIndexes, colIndexes)
),
NA()
)
)
)
)
APPENDROWS
=LAMBDA(xs,
LAMBDA(ys,
LET(
nx, ROWS(xs),
rowIndexes, SEQUENCE(nx + ROWS(ys)),
colIndexes, SEQUENCE(
1,
MAX(COLUMNS(xs), COLUMNS(ys))
),
IFERROR(
IF(rowIndexes <= nx,
INDEX(xs, rowIndexes, colIndexes),
INDEX(ys, rowIndexes - nx, colIndexes)
),
NA()
)
)
)
)
gridString
=LAMBDA(grid,
LET(
ixCol, SEQUENCE(ROWS(grid), 1, 1, 1),
CHAR(10) & CONCAT(
APPENDCOLS(
IF(ixCol, " ")
)(
APPENDCOLS(grid)(
IF(ixCol, CHAR(10))
)
)
)
)
)</syntaxhighlight>
{{Out}}
As grids:
(Each formula in the B column (adjacent to an integer in the A column) defines an array which populates a whole grid (for example the range B12:P19) with a Sierpinski triangle).
{| class="wikitable"
|-
|||style="text-align:right; font-family:serif; font-style:italic; font-size:120%;"|fx
! colspan="16" style="text-align:left; vertical-align: bottom; font-family:Arial, Helvetica, sans-serif !important;"|=sierpinskiTriangle("▲")(A2)
|- style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff;"
|
| A
| B
| C
| D
| E
| F
| G
| H
| I
| J
| K
| L
| M
| N
| O
| P
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 2
| style="font-weight:bold" | 0
| style="text-align:center; background-color:#cbcefb" | ▲
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 3
| style="font-weight:bold" |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 4
| style="font-weight:bold" | 1
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
|
|
|
|
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 5
| style="font-weight:bold" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" | ▲
|
|
|
|
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 6
| style="font-weight:bold" |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 7
| style="font-weight:bold" | 2
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 8
| style="font-weight:bold" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" |
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 9
| style="font-weight:bold" |
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 10
| style="font-weight:bold" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" | ▲
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 11
| style="font-weight:bold" |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 12
| style="font-weight:bold" | 3
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 13
| style="font-weight:bold" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 14
| style="font-weight:bold" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 15
| style="font-weight:bold" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 16
| style="font-weight:bold" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 17
| style="font-weight:bold" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" |
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 18
| style="font-weight:bold" |
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 19
| style="font-weight:bold" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" | ▲
| style="text-align:center" |
| style="text-align:center" | ▲
|}
or as strings, using a monospaced font, and the '''wrap text''' alignment setting in Excel:
{| class="wikitable"
|-
|||style="text-align:right; font-family:serif; font-style:italic; font-size:120%;"|fx
! colspan="2" style="text-align:left; vertical-align: bottom; font-family:Arial, Helvetica, sans-serif !important;"|=gridString(sierpinskiTriangle("*")(A2))
|- style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff;"
|
| A
| B
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 1
| style="font-weight:bold" | Iterations
| style="font-weight:bold" | Sierpinski Triangle
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 2
| style="text-align:right" | 0
| style="background-color:#cbcefb" |
*
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 3
| style="text-align:right" | 1
|
*
* *
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 4
| style="text-align:right" | 2
|
*
* *
* *
* * * *
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 5
| style="text-align:right" | 3
|
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 6
| style="text-align:right" | 4
|
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
|}
=={{header|F Sharp|F#}}==
<
let rec loop down space n =
if n = 0 then
Line 1,233 ⟶ 2,560:
let () =
List.iter (fun (i:string) -> System.Console.WriteLine(i)) (sierpinski 4)</
=={{header|Factor}}==
{{trans|OCaml}}
<
IN: sierpinski
Line 1,253 ⟶ 2,580:
: sierpinski ( n -- )
[ { "*" } " " ] dip (sierpinski) print ;</
A more idiomatic version taking advantage of the '''''with''''', '''''each-integer''''', and '''''?''''' combinator as well as leveraging the looping combinator '''''each-integer'''''.
<syntaxhighlight lang="factor">USING: command-line io io.streams.string kernel math math.parser
namespaces sequences ;
IN: sierpinski
: plot ( i j -- )
bitand zero? "* " " " ? write ;
: pad ( n -- )
1 - [ " " write ] times ;
: plot-row ( n -- )
dup 1 + [ tuck - plot ] with each-integer ;
: sierpinski ( n -- )
dup '[ _ over - pad plot-row nl ] each-integer ;</syntaxhighlight>
=={{header|FALSE}}==
Requires the pick character to be substituted with 'O' in the portable interpreter linked-to from https://strlen.com/false-language/.
<syntaxhighlight lang="false">{ print spaces; in:n }
[[$0>][" " 1-]#%]w:
{ left shift; in:x,y out:x<<y }
[[$0>][\2*\ 1-]#%]l:
1 4 l;! { SIZE = 1<<4 }
$ { y = SIZE }
[$0>] { y > 0 }
[1-
$w;!
1ø { x = SIZE }
[$0>]
[1-
1ø$2ø\-&0= { !((x - y) & y) }
$ ["* "]?
~ [" "]?
]#%
10,
]#%%</syntaxhighlight>
=={{header|FOCAL}}==
<syntaxhighlight lang="focal">01.10 A "ORDER",O;S S=2^(O+1)
01.20 F X=0,S;S L(X)=0
01.30 S L(S/2)=1
01.40 F I=1,S/2;D 2;D 3
01.90 Q
02.10 F X=1,S-1;D 2.3
02.20 T !;R
02.30 I (L(X)),2.4,2.5
02.40 T " "
02.50 T "*"
03.10 F X=0,S;S K(X)=FABS(L(X-1)-L(X+1))
03.20 F X=0,S;S L(X)=K(X)</syntaxhighlight>
{{out}}
<pre>ORDER:4
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *</pre>
=={{header|Forth}}==
<
begin
dup 1 and if [char] * else bl then emit
Line 1,278 ⟶ 2,674:
loop 2drop ;
5 triangle</
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
This method calculates a Pascal's triangle and replaces every odd number with a * and every even number with a space. The limitation of this approach is the size of the numbers in the Pascal's triangle. Tryng to print an order 8 Sierpinski's triangle will overflow a 32 bit integer and an order 16 will overflow a 64 bit integer.
<
implicit none
Line 1,311 ⟶ 2,707:
end do
end subroutine Triangle
end program Sierpinski_triangle</
=={{header|GAP}}==
<
SierpinskiTriangle := function(n)
local i, j, s, b;
Line 1,351 ⟶ 2,747:
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * * </
=={{header|gnuplot}}==
Making and printing a text string, using bit-twiddling to decide whether each character should be a space or a star.
<
# Must have x<y. x<0 is the left side of the triangle.
# If x<-y then it's before the left edge and the return is a space.
Line 1,371 ⟶ 2,767:
# Print rows 0 to 15, which is the order 4 triangle per the task.
print triangle(0,15)</
=={{header|Go}}==
"Δ" (Greek capital letter delta) looks good for grain, as does Unicode triangle, "△". ASCII "." and "^" are pleasing. "/\\", "´`", and "◢◣"" make interesting wide triangles.
<
import (
Line 1,400 ⟶ 2,796:
fmt.Println(r)
}
}</
=={{header|Golfscript}}==
Cambia el "3" a un número mayor para un triángulo más grande.
<syntaxhighlight lang="golfscript">' /\ /__\ '4/){.+\.{[2$.]*}%\{.+}%+\}3*;n*</syntaxhighlight>
{{out}}
<pre>
/\
/__\
/\ /\
/__\/__\
/\ /\
/__\ /__\
/\ /\ /\ /\
/__\/__\/__\/__\
/\ /\
/__\ /__\
/\ /\ /\ /\
/__\/__\ /__\/__\
/\ /\ /\ /\
/__\ /__\ /__\ /__\
/\ /\ /\ /\ /\ /\ /\ /\
/__\/__\/__\/__\/__\/__\/__\/__\
</pre>
=={{header|Groovy}}==
Solution:
<
stPoints = { order, base=[0,0] ->
def right = [base[0], base[1]+2**order]
Line 1,419 ⟶ 2,838:
stPoints(order).each { grid[it[0]][it[1]] = (order%10).toString() }
grid
}</
Test:
<
println()
stGrid(1).reverse().each { println it.sum() }
Line 1,434 ⟶ 2,853:
stGrid(5).reverse().each { println it.sum() }
println()
stGrid(6).reverse().each { println it.sum() }</
{{out}}
Line 1,574 ⟶ 2,993:
=={{header|Haskell}}==
<
sierpinski n = map ((space ++) . (++ space)) down ++
map (unwords . replicate 2) down
Line 1,580 ⟶ 2,999:
space = replicate (2 ^ (n - 1)) ' '
main = mapM_ putStrLn $ sierpinski 4</
{{out}}
<pre>
Line 1,598 ⟶ 3,017:
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *</pre>
We can see how the approach above (centering a preceding block over two duplicates) generates a framing rectangle at each stage, by making the right padding (plus the extra space between duplicates) more distinct and visible:
<syntaxhighlight lang="haskell">import Data.List (intercalate)
sierpinski :: Int -> [String]
sierpinski 0 = ["▲"]
sierpinski n =
[ flip
intercalate
([replicate (2 ^ (n - 1))] <*> " -"),
(<>) <*> ('+' :)
]
>>= (<$> sierpinski (n - 1))
main :: IO ()
main = mapM_ putStrLn $ sierpinski 4</syntaxhighlight>
{{Out}}
<pre> ▲---------------
▲+▲--------------
▲-+ ▲-------------
▲+▲+▲+▲------------
▲---+ ▲-----------
▲+▲--+ ▲+▲----------
▲-+ ▲-+ ▲-+ ▲---------
▲+▲+▲+▲+▲+▲+▲+▲--------
▲-------+ ▲-------
▲+▲------+ ▲+▲------
▲-+ ▲-----+ ▲-+ ▲-----
▲+▲+▲+▲----+ ▲+▲+▲+▲----
▲---+ ▲---+ ▲---+ ▲---
▲+▲--+ ▲+▲--+ ▲+▲--+ ▲+▲--
▲-+ ▲-+ ▲-+ ▲-+ ▲-+ ▲-+ ▲-+ ▲-
▲+▲+▲+▲+▲+▲+▲+▲+▲+▲+▲+▲+▲+▲+▲+▲</pre>
Using bitwise and between x and y coords:
<
sierpinski n = map row [m, m-1 .. 0] where
Line 1,610 ⟶ 3,062:
| otherwise = " "
main = mapM_ putStrLn $ sierpinski 4</
{{Trans|JavaScript}}
<syntaxhighlight lang="haskell">import Data.List (intersperse)
-- Top down, each row after the first is an XOR / Rule90 rewrite.
-- Bottom up, each line above the base is indented 1 more space.
sierpinski :: Int -> String
sierpinski = fst . foldr spacing ([], []) . rule90 . (2 ^)
where
rule90 = scanl next "*" . enumFromTo 1 . subtract 1
where
next =
const
. ( (zipWith xor . (' ' :))
<*> (<> " ")
)
xor l r
| l == r = ' '
| otherwise = '*'
spacing x (s, w) =
( concat
[w, intersperse ' ' x, "\n", s],
w <> " "
)
main :: IO ()
main = putStr $ sierpinski 4</syntaxhighlight>
Or simply as a right fold:
<syntaxhighlight lang="haskell">sierpinski :: Int -> [String]
sierpinski n =
foldr
( \i xs ->
let s = replicate (2 ^ i) ' '
in fmap ((s <>) . (<> s)) xs
<> fmap
( (<>)
<*> (' ' :)
)
xs
)
["*"]
[n - 1, n - 2 .. 0]
main :: IO ()
main = (putStrLn . unlines . sierpinski) 4</syntaxhighlight>
{{Out}}
<pre> *
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *</pre>
=={{header|Haxe}}==
<
{
static function main()
Line 1,647 ⟶ 3,165:
}
}
}</
=={{header|Hoon}}==
<syntaxhighlight lang="hoon">|= n=@ud
=+ m=0
=+ o=(reap 1 '*')
|^ ?: =(m n) o
$(m +(m), o (weld top bot))
++ gap (fil 3 (pow 2 m) ' ')
++ top (turn o |=(l=@t (rap 3 gap l gap ~)))
++ bot (turn o |=(l=@t (rap 3 l ' ' l ~)))
--</syntaxhighlight>
=={{header|Icon}} and {{header|Unicon}}==
This is a text based adaption of a program from the IPL and Icon Graphics book. The triangle is presented with a twist. Based on an idea from "Chaos and Fractals" by Peitgen, Jurgens, and Saupe.
<
procedure main(A)
Line 1,665 ⟶ 3,194:
writes((y=1,"\n")|"",canvas[x,y]," ") # print
end</
{{libheader|Icon Programming Library}}
Line 1,684 ⟶ 3,213:
=={{header|IDL}}==
The only 'special' thing here is that the math is done in a byte array, filled with the numbers 32 and 42 and then output through a "<tt>string(array)</tt>" which prints the ascii representation of each individual element in the array.
<
s = (t = bytarr(3+2^(n+1))+32b)
t[2^n+1] = 42b
Line 1,691 ⟶ 3,220:
for i=1,n_elements(t)-2 do if s[i-1] eq s[i+1] then t[i]=32b else t[i]=42b
end
end</
=={{header|J}}==
There are any number of succinct ways to produce this in J.
Here's one that exploits self-similarity:
<
Here, (,.~ , ])^:4 ,: '* ' is the basic structure (with 4 iterations) and the rest of it is just formatting.
Here's one that leverages the relationship between Sierpinski's and Pascal's triangles:
<
Here, !/~ i._16 gives us [[Pascal's_triangle|pascal's triangle]] (and we want a power of 2 (or, for the formatting we are using here a negative of a power of 2) for the size of the square in which contains the triangle, and (2 + |/~) i._16 is a [[Boolean_values#J|boolean]] representation where the 1s correspond to odd values in pascal's triangle, and the rest is just formatting.
Line 1,708 ⟶ 3,237:
=={{header|Java}}==
Replace translations.
Recursive solution.
<syntaxhighlight lang="java">
public class SierpinskiTriangle {
public static void main(String[] args) {
System.out.println(getSierpinskiTriangle(4));
}
private static final String getSierpinskiTriangle(int n) {
}
String
String [] split
int length = split.length;
// Top triangle
StringBuilder sb = new StringBuilder();
String top = buildSpace((int)Math.pow(2, n-1));
for ( int i = 0 ; i < length ;i++ ) {
sb.append(top);
sb.append(split[i]);
sb.append("\n");
}
// Two triangles side by side
for ( int i = 0 ; i < length ;i++ ) {
sb.append(split[i]);
sb.append(buildSpace(length-i));
sb.append(split[i]);
sb.append("\n");
}
return sb.toString();
}
StringBuilder sb = new StringBuilder();
n--;
}
return sb.toString();
}
}
</syntaxhighlight>
{{out}}
<pre>
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
</pre>
=={{header|JavaFX Script}}==
{{trans|Python}}
<
var down = ["*"];
var space = " ";
Line 1,775 ⟶ 3,322:
}
sierpinski(4);</
=={{header|JavaScript}}==
Line 1,782 ⟶ 3,329:
====Functional====
Using a functional idiom of JavaScript, we can
mapping the binary pattern to centred strings.
<syntaxhighlight lang="javascript">(function (order) {
// Sierpinski triangle of order N constructed as
// Pascal triangle of 2^N rows mod 2
// with 1 encoded as "▲"
// and 0 encoded as " "
function sierpinski(intOrder) {
return function asciiPascalMod2(intRows) {
return range(1, intRows - 1)
.reduce(function (lstRows) {
var lstPrevRow = lstRows.slice(-1)[0];
// Each new row is a function of the previous row
return lstRows.concat([zipWith(function (left, right) {
// The composition ( asciiBinary . mod 2 . add )
// reduces to a rule from 2 parent characters
// to a single child character
// Rule 90 also reduces to the same XOR
// relationship between left and right neighbours
return left === right ? " " : "▲";
}, [' '].concat(lstPrevRow), lstPrevRow.concat(' '))]);
}(Math.pow(2, intOrder))
// As centred lines, from bottom (0 indent) up (indent below + 1)
.reduceRight(function
triangle: sofar.
indent: sofar.indent + " "
};
}, {
triangle: "",
indent: ""
}).triangle;
};
var zipWith = function (f, xs, ys) {
return xs.length === ys.length ?
}) :
},
range = function (m, n)
});
};
//
return sierpinski(order);
})(4);
</syntaxhighlight>
Output (N=4)
<pre>
====Imperative====
<
var n = 1 << o,
i, j, t, u;
for (i = 0; i <
document.write(line.join('') + "\n");
t = (line[j - 1] == line[j + 1] ? ' ' : '*');
line[j - 1] = u;
u = t;
}
line[n + i] = t;
line[n + i + 1] = '*';
}
}
document.write("<pre>\n");
triangle(6);
document.write("</pre>");</
===ES6===
Directly in terms of the built-in Array methods '''.map''', '''.reduce''', and '''.from''', and without much abstraction, possibly at the cost of some legibility:
<syntaxhighlight lang="javascript">(() => {
"use strict";
// --------------- SIERPINSKI TRIANGLE ---------------
// sierpinski :: Int -> String
const sierpinski = n =>
Array.from({
length: n
})
.reduce(
(xs, _, i) => {
const s = " ".repeat(2 ** i);
return [
...xs.map(x => s + x + s),
...xs.map(x => `${x} ${x}`)
];
},
["*"]
)
.join("\n");
// ---------------------- TEST -----------------------
return sierpinski(4);
})();</syntaxhighlight>
{{Trans|Haskell}}
Centering any preceding triangle block over two adjacent duplicates:
<syntaxhighlight lang="javascript">(() => {
"use strict";
// ----- LINES OF SIERPINSKI TRIANGLE AT LEVEL N -----
// sierpinski :: Int -> [String]
const sierpTriangle = n =>
// Previous triangle centered with
// left and right padding,
0 < n ? (
ap([
map(
xs => ap([
compose(
ks => ks.join(""),
replicate(2 ** (n - 1))
)
])([" ", "-"])
.join(xs)
),
// above a pair of duplicates,
// placed one character apart.
map(s => `${s}+${s}`)
])([sierpTriangle(n - 1)])
.flat()
) : ["▲"];
// ---------------------- TEST -----------------------
const main = () =>
sierpTriangle(4)
.join("\n");
// ---------------- GENERIC FUNCTIONS ----------------
// ap (<*>) :: [(a -> b)] -> [a] -> [b]
const ap = fs =>
// The sequential application of each of a list
// of functions to each of a list of values.
// apList([x => 2 * x, x => 20 + x])([1, 2, 3])
// -> [2, 4, 6, 21, 22, 23]
xs => fs.flatMap(f => xs.map(f));
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
// A function defined by the right-to-left
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
x => x
);
// map :: (a -> b) -> [a] -> [b]
const map = f => xs => xs.map(f);
// replicate :: Int -> a -> [a]
const replicate = n =>
// A list of n copies of x.
x => Array.from({
length: n
}, () => x);
// ---------------------- TEST -----------------------
return main();
})();</syntaxhighlight>
{{Out}}
<pre> ▲---------------
▲+▲--------------
▲-+ ▲-------------
▲+▲+▲+▲------------
▲---+ ▲-----------
▲+▲--+ ▲+▲----------
▲-+ ▲-+ ▲-+ ▲---------
▲+▲+▲+▲+▲+▲+▲+▲--------
▲-------+ ▲-------
▲+▲------+ ▲+▲------
▲-+ ▲-----+ ▲-+ ▲-----
▲+▲+▲+▲----+ ▲+▲+▲+▲----
▲---+ ▲---+ ▲---+ ▲---
▲+▲--+ ▲+▲--+ ▲+▲--+ ▲+▲--
▲-+ ▲-+ ▲-+ ▲-+ ▲-+ ▲-+ ▲-+ ▲-
▲+▲+▲+▲+▲+▲+▲+▲+▲+▲+▲+▲+▲+▲+▲+▲</pre>
Or constructed as 2^N lines of Pascal's triangle mod 2,
and mapped to centred {1:asterisk, 0:space} strings.
<syntaxhighlight lang="javascript">(() => {
"use strict";
// --------------- SIERPINSKI TRIANGLE ---------------
// sierpinski :: Int -> [Bool]
// Reduce/folding from the last item (base of list)
// which has zero
//
`${a[1]} `
]), ["", ""])[0];
// pascalMod2Chars :: Int -> [[Char]]
const pascalMod2Chars = nRows =>
const rows = sofar.slice(-1)[0];
// relationship between left
zipWith(
l => r => l === r ? (
" "
) : "*"
)([" ", ...rows])([...rows, " "])
]);
}, [
["*"]
]);
// ---------------------- TEST -----------------------
// main ::
const main = () =>
// --------------------- GENERIC ---------------------
// zipWith ::
const zipWith = f
// A list constructed by zipping with a
// custom function, rather than with
// default tuple
0, Math.min(xs.length, ys.length)
);
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => Array.from({
length: 1 + n - m
}, (_, i) => m + i);
// MAIN ---
return main();
})();</syntaxhighlight>
{{Out}}
<pre> *
* *
Line 2,000 ⟶ 3,642:
* * * * * * * *
* * * * * * * * * * * * * * * *</pre>
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
'''Preliminaries'''
<syntaxhighlight lang="jq">def elementwise(f):
transpose | map(f) ;
# input: an array of decimal numbers
def bitwise_and:
# Input: an integer
# Output: a stream of 0s and 1s
def stream:
recurse(if . > 0 then ./2|floor else empty end) | . % 2 ;
# Input: a 0-1 array
def toi:
reduce .[] as $c ( {power:1 , ans: 0};
.ans += ($c * .power) | .power *= 2 )
| .ans;
if any(.==0) then 0
else map([stream])
| (map(length) | min) as $min
| map( .[:$min] ) | elementwise(min) | toi
end;</syntaxhighlight>
<syntaxhighlight lang="jq">
def sierpinski:
pow(2; .) as $size
| range($size-1; -1; -1) as $y
| reduce range(0; $size - $y) as $x ( (" " * $y);
. + (if ([$x,$y]|bitwise_and) == 0 then "* " else " " end));
4 | sierpinski</syntaxhighlight>
{{out}}
As elsewhere.
=={{header|Julia}}==
{{works with|Julia|0.6}}
<syntaxhighlight lang="julia">function sierpinski(n, token::AbstractString="*")
end
function printsierpinski(m::Matrix)
for r in 1:size(m, 1)
println(join(m[r, :]))
end
end
sierpinski(4) |> printsierpinski</syntaxhighlight>
=={{header|Kotlin}}==
{{trans|C}}
<syntaxhighlight lang="scala">// version 1.1.2
const val ORDER = 4
const val SIZE = 1 shl ORDER
fun main(args: Array<String>) {
for (x in 0 until SIZE - y) print(if ((x and y) != 0) " " else "* ")
println()
}
}</syntaxhighlight>
{{out}}
<pre>
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
</pre>
=={{header|Lambdatalk}}==
===1) define===
<syntaxhighlight lang="scheme">
{def sierp
{def sierp.r
{lambda {:order :length :angle}
{if {= :order 0}
then M:length // move :length
else {sierp.r {- :order 1} // recurse
{/ :length 2}
{- :angle}}
T:angle // turn :angle
{sierp.r {- :order 1} // recurse
{/ :length 2}
{+ :angle}}
T:angle // turn :angle
{sierp.r {- :order 1} // recurse
{/ :length 2}
{- :angle}}
}}}
{lambda {:order :length}
{if {= {% :order 2} 0} // if :order is even
then {sierp.r :order :length 60} // recurse with 60°
else T60 // else turn 60°
{sierp.r :order :length -60} // recurse with -60°
}}}
-> sierp
</syntaxhighlight>
===2) draw===
Four curves drawn in 50ms on a PowerBookPro. using the turtle primitive.
<syntaxhighlight lang="scheme">
{svg {@ width="580" height="580" style="box-shadow:0 0 8px #000;"}
{polyline {@ points="{turtle 50 5 0 {sierp 1 570}}"
stroke="#ccc" fill="transparent" stroke-width="7"}}
{polyline {@ points="{turtle 50 5 0 {sierp 3 570}}"
stroke="#8ff" fill="transparent" stroke-width="5"}}
{polyline {@ points="{turtle 50 5 0 {sierp 5 570}}"
stroke="#f88" fill="transparent" stroke-width="3"}}
{polyline {@ points="{turtle 50 5 0 {sierp 7 570}}"
stroke="#000" fill="transparent" stroke-width="1"}}
</syntaxhighlight>
===3) output===
See http://lambdaway.free.fr/lambdawalks/?view=sierpinsky
=={{header|Liberty BASIC}}==
<
call triangle 1, 1, nOrder
end
Line 2,050 ⟶ 3,798:
call triangle x+length*2, y+length, n
END IF
END SUB</
=={{header|Logo}}==
<
; limit=15 gives the order 4 form per the task.
; The range of :y is arbitrary, any rows of the triangle can be printed.
Line 2,066 ⟶ 3,814:
]
print []
]</
=={{header|Lua}}==
Ported from the list-comprehension Python version.
<syntaxhighlight lang="lua">function sierpinski(depth)
lines = {}
lines[1] = '*'
for i = 2, depth+1 do
sp = string.rep(' ', 2^(i-2))
tmp = {}
for idx, line in ipairs(lines) do
tmp[idx] = sp .. line .. sp
tmp[idx+#lines] = line .. ' ' .. line
end
lines = tmp
end
return table.concat(lines, '\n')
end
print(sierpinski(4))</syntaxhighlight>
{{out}}
<pre>
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
</pre>
=={{header|Maple}}==
<
local i, j, values, position;
values := [ seq(" ",i=1..2^n-1), "*" ];
Line 2,083 ⟶ 3,871:
printf("%s\n",cat(op(convert(values, list))));
end do:
end proc:</
{{out}}
<pre>
Line 2,104 ⟶ 3,892:
</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Cellular automaton (rule 90) based solution:
<
Using built-in function:
<syntaxhighlight lang="mathematica">SierpinskiMesh[3]</syntaxhighlight>
=={{header|MATLAB}}==
STRING was introduced in version R2016b.
<syntaxhighlight lang="matlab">n = 4;
d = string('*');
for k = 0 : n - 1
sp = repelem(' ', 2 ^ k);
d = [sp + d + sp, d + ' ' + d];
end
disp(d.join(char(10)))
</syntaxhighlight>
{{out}}
<pre>
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
</pre>
===Cellular Automaton Version===
<syntaxhighlight lang="matlab">n = 2 ^ 4 - 1;
tr = + ~(-n : n);
for k = 1:n
tr(k + 1, :) = bitget(90, 1 + filter2([4 2 1], tr(k, :)));
end
char(10 * tr + 32)</syntaxhighlight>
===Mixed Version===
<syntaxhighlight lang="matlab">spy(mod(abs(pascal(32,1)),2)==1)</syntaxhighlight>
=={{header|NetRexx}}==
{{trans|Java}}
<
options replace format comments java crossref symbols nobinary
Line 2,149 ⟶ 3,979:
end row
return
</syntaxhighlight>
{{out}}
<pre>
Line 2,172 ⟶ 4,002:
=={{header|Nim}}==
{{trans|C}}
<
for y in countdown(size, 0):
Line 2,182 ⟶ 4,012:
else:
stdout.write "* "
stdout.write "\n"</
{{out}}
<pre> *
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * * </pre>
=={{header|OCaml}}==
<
let rec loop down space n =
if n = 0 then
Line 2,197 ⟶ 4,045:
let () =
List.iter print_endline (sierpinski 4)</
=={{header|Oforth}}==
Line 2,205 ⟶ 4,053:
automat(rule, n) runs cellular automaton for rule "rule" for n generations.
<
| i |
StringBuffer new
Line 2,220 ⟶ 4,068:
: sierpinskiTriangle(n)
90 4 n * automat ;</
{{out}}
Line 2,246 ⟶ 4,094:
=={{header|Oz}}==
<
fun {NextTriangle Triangle}
Sp = {Spaces {Length Triangle}}
Line 2,264 ⟶ 4,112:
SierpinskiTriangles = {Iterate NextTriangle ["*"]}
in
{ForAll {Nth SierpinskiTriangles 5} System.showInfo}</
=={{header|PARI/GP}}==
{{trans|C}}
<
my(s=2^n-1);
forstep(y=s,0,-1,
Line 2,278 ⟶ 4,126:
)
};
Sierpinski(4)</
{{out}}
<pre> *
Line 2,300 ⟶ 4,148:
{{trans|C}}
{{works with|Free Pascal}}
<
function ipow(b, n : Integer) : Integer;
Line 2,317 ⟶ 4,165:
else
truth := false
end;</
<
var
l, i : Integer;
Line 2,359 ⟶ 4,207:
writeln(b)
end
end;</
<
triangle(4)
end.</
=={{header|Perl}}==
===version 1===
<syntaxhighlight lang="perl">sub sierpinski {
my ($n) = @_;
my @down = '*';
Line 2,377 ⟶ 4,226:
}
print "$_\n" foreach sierpinski 4;</
===one-liner===
<syntaxhighlight lang="perl">
perl -le '$l=40;$l2="!" x $l;substr+($l2^=$l2),$l/2,1,"\xFF";for(1..16){local $_=$l2;y/\0\xFF/ */;print;($lf,$rt)=map{substr $l2 x 2,$_%$l,$l;}1,-1;$l2=$lf^$rt;select undef,undef,undef,.1;}'</syntaxhighlight>
=={{header|Phix}}==
{{Trans|C}}
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">procedure</span> <span style="color: #000000;">sierpinski</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">lim</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">=</span><span style="color: #000000;">lim</span> <span style="color: #008080;">to</span> <span style="color: #000000;">0</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">lim</span><span style="color: #0000FF;">-</span><span style="color: #000000;">y</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">and_bits</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: #008000;">" "</span><span style="color: #0000FF;">:</span><span style="color: #008000;">"* "</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">5</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">sierpinski</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre style="font-size: 2px">
Line 2,474 ⟶ 4,315:
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
</pre>
=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">def sierpinski
2 swap power 1 - var lim
lim 0 -1 3 tolist for
var y
32 y 1 + repeat print
0 lim y - 2 tolist for
y bitand if 32 32 chain else "* " endif print
endfor
nl
endfor
enddef
5 for
sierpinski
endfor</syntaxhighlight>
=={{header|PHP}}==
{{Trans|JavaScript}}
<syntaxhighlight lang="php"><?php
function sierpinskiTriangle($order) {
$char = '#';
$n = 1 << $order;
$line = array();
for ($i = 0 ; $i <= 2 * $n ; $i++) {
$line[$i] = ' ';
}
$line[$n] = $char;
for ($i = 0 ; $i < $n ; $i++) {
echo implode('', $line), PHP_EOL;
$u = $char;
for ($j = $n - $i ; $j < $n + $i + 1 ; $j++) {
$t = ($line[$j - 1] == $line[$j + 1] ? ' ' : $char);
$line[$j - 1] = $u;
$u = $t;
}
$line[$n + $i] = $t;
$line[$n + $i + 1] = $char;
}
}
sierpinskiTriangle(4);
</syntaxhighlight>
{{out}}
<pre> #
# #
# #
# # # #
# #
# # # #
# # # #
# # # # # # # #
# #
# # # #
# # # #
# # # # # # # #
# # # #
# # # # # # # #
# # # # # # # #
# # # # # # # # # # # # # # # #
</pre>
=={{header|Picat}}==
{{trans|E}}
<syntaxhighlight lang="picat">go =>
foreach(N in 1..4)
sierpinski(N),
nl
end,
nl.
sierpinski(N) =>
Size = 2**N,
foreach(Y in Size-1..-1..0)
printf("%s", [' ' : _I in 1..Y]),
foreach(X in 0..Size-Y-1)
printf("%s ", cond(X /\ Y == 0, "*", " "))
end,
nl
end.</syntaxhighlight>
{{out}}
<pre> *
* *
*
* *
* *
* * * *
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * * </pre>
=={{header|PicoLisp}}==
{{trans|Python}}
<
(let (D '("*") S " ")
(do N
Line 2,487 ⟶ 4,449:
D ) )
(mapc prinl (sierpinski 4))</
=={{header|PL/I}}==
<
declare t (79,79) char (1);
declare (i, j, k) fixed binary;
Line 2,538 ⟶ 4,500:
end make_triangle;
end sierpinski;</
=={{header|PL/M}}==
<syntaxhighlight lang="plm">100H:
DECLARE ORDER LITERALLY '4';
/* CP/M BDOS CALL */
BDOS: PROCEDURE (FN, ARG);
DECLARE FN BYTE, ARG ADDRESS;
GO TO 5;
END BDOS;
PUT$CHAR: PROCEDURE (CHAR);
DECLARE CHAR BYTE;
CALL BDOS(2, CHAR);
END PUT$CHAR;
/* PRINT SIERPINSKI TRIANGLE */
DECLARE (X, Y, SIZE) BYTE;
SIZE = SHL(1, ORDER);
Y = SIZE - 1;
DO WHILE Y <> -1;
DO X = 0 TO Y;
CALL PUT$CHAR(' ');
END;
DO X = 0 TO SIZE-Y-1;
IF (X AND Y) = 0
THEN CALL PUT$CHAR('*');
ELSE CALL PUT$CHAR(' ');
CALL PUT$CHAR(' ');
END;
Y = Y - 1;
CALL PUT$CHAR(13);
CALL PUT$CHAR(10);
END;
CALL BDOS(0,0);
EOF</syntaxhighlight>
{{out}}
<pre> *
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *</pre>
=={{header|Pop11}}==
Solution using line buffer in an integer array oline, 0 represents ' '
(space), 1 represents '*' (star).
<
lvars k = 2**n, j, l, oline, nline;
initv(2*k+3) -> oline;
Line 2,563 ⟶ 4,581:
enddefine;
triangle(4);</
Alternative solution, keeping all triangle as list of strings
<
lvars acc = ['*'], spaces = ' ', j;
for j from 1 to n do
Line 2,576 ⟶ 4,594:
enddefine;
triangle2(4);</
=={{header|PostScript}}==
This draws the triangles in a string-rewrite fashion, where all edges form a single polyline. 9 page document showing progession.
<
%%BoundingBox 0 0 300 300
Line 2,594 ⟶ 4,612:
0 1 8 { 300 300 scale 0 1 12 div moveto
X + F + F fill showpage } for
%%EOF</
=={{header|PowerShell}}==
{{Trans|JavaScript}}
<
$n = [Math]::Pow(2, $o)
$line = ,' '*(2*$n+1)
Line 2,618 ⟶ 4,636:
$line[$n+$i+1] = '█'
}
}</
=={{header|Processing}}==
===Characters in drawing canvas version===
<syntaxhighlight lang="java">void setup() {
size(410, 230);
background(255);
fill(0);
sTriangle (10, 25, 100, 5);
}
void sTriangle(int x, int y, int l, int n) {
if( n == 0) text("*", x, y);
else {
sTriangle(x, y+l, l/2, n-1);
sTriangle(x+l, y, l/2, n-1);
sTriangle(x+l*2, y+l, l/2, n-1);
}
}</syntaxhighlight>
===Text in console version===
{{trans|Java}}
<syntaxhighlight lang="java">void setup() {
print(getSierpinskiTriangle(3));
}
String getSierpinskiTriangle(int n) {
if ( n == 0 ) {
return "*";
}
String s = getSierpinskiTriangle(n-1);
String [] split = s.split("\n");
int length = split.length;
// Top triangle
String ns = "";
String top = buildSpace((int)pow(2, n-1));
for ( int i = 0; i < length; i++ ) {
ns += top;
ns += split[i];
ns += "\n";
}
// Two triangles side by side
for ( int i = 0; i < length; i++ ) {
ns += split[i];
ns += buildSpace(length-i);
ns += split[i];
ns += "\n";
}
return ns.toString();
}
String buildSpace(int n) {
String ns = "";
while ( n > 0 ) {
ns += " ";
n--;
}
return ns;
}
</syntaxhighlight>
=={{header|Prolog}}==
Works with SWI-Prolog;
<
Len is 2 ** (N+1) - 1,
length(L, Len),
Line 2,662 ⟶ 4,738:
rule_90(' ',' ','*', '*').
rule_90(' ',' ',' ', ' ').
</syntaxhighlight>
{{out}}
<pre> ?- sierpinski_triangle(4).
Line 2,684 ⟶ 4,760:
=={{header|PureBasic}}==
<
If N = 0
DrawText( Y,X, "*",#Blue)
Line 2,703 ⟶ 4,779:
Repeat
Until WaitWindowEvent()=#PB_Event_CloseWindow
End</
=={{header|Python}}==
<
d = ["*"]
for i in xrange(n):
Line 2,713 ⟶ 4,789:
return d
print "\n".join(sierpinski(4))</
Or, using fold / reduce {{works with|Python|3.x}}
<
def sierpinski(n):
Line 2,726 ⟶ 4,803:
return functools.reduce(aggregate, range(n), ["*"])
print("\n".join(sierpinski(4)))</
and fold/reduce, wrapped as concatMap, can provide the list comprehensions too:
<syntaxhighlight lang="python">'''Sierpinski triangle'''
from functools import reduce
from operator import add
# sierpinski :: Int -> String
def sierpinski(n):
'''Nth iteration of a Sierpinksi triangle.'''
def go(xs, i):
s = ' ' * (2 ** i)
return concatMap(lambda x: [s + x + s])(xs) + (
concatMap(lambda x: [x + ' ' + x])(xs)
)
return '\n'.join(reduce(go, range(n), '*'))
# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f):
'''A concatenated list or string over which a function f
has been mapped.
The list monad can be derived by using an (a -> [b])
function which wraps its output in a list (using an
empty list to represent computational failure).
'''
return lambda xs: (
reduce(add, map(f, xs), [])
)
print(sierpinski(4))</syntaxhighlight>
{{Out}}
<pre> *
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *</pre>
Use Python's long integer and bit operator to make an infinite triangle:
<
while True:
print(bin(x)[2:].replace('0', ' '))
x ^= x<<1</
=={{header|Quackery}}==
{{trans|Forth}}
<syntaxhighlight lang="quackery"> [ [ dup 1 &
iff char * else space
emit
1 >> dup while
sp again ]
drop ] is stars ( mask --> )
[ bit
1 over times
[ cr over i^ - times sp
dup stars
dup 1 << ^ ]
2drop ] is triangle ( order --> )
4 triangle</syntaxhighlight>
{{out}}
<pre> *
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *</pre>
=={{header|R}}==
Based on C# but using some of R's functionality to abbreviate code where possible.
<
len <- 2^(n+1)
b <- c(rep(FALSE,len/2),TRUE,rep(FALSE,len/2))
Line 2,748 ⟶ 4,916:
}
}
sierpinski.triangle(5)</
Shortened to a function of one line.
<
c(paste(ifelse(b<<- c(rep(FALSE,2^(n+1)/2),TRUE,rep(FALSE,2^(n+1)/2)),"*"," "),collapse=""),replicate(2^n-1,paste(ifelse(b<<-xor(c(FALSE,b[1:2^(n+1)]),c(b[2:(2^(n+1)+1)],FALSE)),"*"," "),collapse="")))
}
cat(sierpinski.triangle(5),sep="\n")</
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(define (sierpinski n)
Line 2,768 ⟶ 4,936:
(map (λ(x) (~a x " " x)) prev)))))
(for-each displayln (sierpinski 5))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{trans|Perl}}
<syntaxhighlight lang="raku" line>sub sierpinski ($n) {
my @down = '*';
my $space = ' ';
for ^$n {
@down = |("$space$_$space" for @down), |("$_ $_" for @down);
$space x= 2;
}
return @down;
}
.say for sierpinski 4;</syntaxhighlight>
=={{header|REXX}}==
<
parse arg n mark . /*get the order of Sierpinski triangle.*/
if n=='' | n=="," then n=4 /*Not specified? Then use the default.*/
Line 2,787 ⟶ 4,970:
say z /*display a line of the triangle. */
end /*j*/ /* [↑] finished showing triangle. */
/*stick a fork in it, we're all done. */</
'''output''' when using the default input of order: <tt> 4 </tt>
Line 2,990 ⟶ 5,173:
<br><br>
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Sierpinski triangle
norder=4
xy = list(40)
for i = 1 to 40
xy[i] = " "
next
triangle(1, 1, norder)
for i = 1 to 36
see xy[i] + nl
next
func triangle(x, y, n)
if n = 0
xy[y] = left(xy[y],x-1) + "*" + substr(xy[y],x+1)
else
n=n-1
length=pow(2,n)
triangle(x, y+length, n)
triangle(x+length, y, n)
triangle(x+length*2, y+length, n)
ok
</syntaxhighlight>
Output:
<pre>
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
</pre>
=={{header|Ruby}}==
From the command line:
<
or, {{trans|Python}}
<
triangle = ["*"]
n.times do |i|
Line 3,006 ⟶ 5,234:
end
puts sierpinski_triangle(4)</
Using fold / reduce (aka. inject):
<
(0...n).inject(["*"]) {|triangle, i|
space = " " * (2**i)
Line 3,017 ⟶ 5,245:
end
puts sierpinski_triangle(4)</
=={{header|Run BASIC}}==
<
dim xy$(40)
for i = 1 to 40
Line 3,041 ⟶ 5,269:
call triangle x+length*2, y+length, n
END IF
END SUB</
<pre> *
* *
Line 3,058 ⟶ 5,286:
* * * * * * * *
* * * * * * * * * * * * * * * *</pre>
=={{header|Rust}}==
<syntaxhighlight lang="rust">
use std::iter::repeat;
fn sierpinski(order: usize) {
let mut triangle = vec!["*".to_string()];
for i in 0..order {
let space = repeat(' ').take(2_usize.pow(i as u32)).collect::<String>();
// save original state
let mut d = triangle.clone();
// extend existing lines
d.iter_mut().for_each(|r| {
let new_row = format!("{}{}{}", space, r, space);
*r = new_row;
});
// add new lines
triangle.iter().for_each(|r| {
let new_row = format!("{}{}{}", r, " ", r);
d.push(new_row);
});
triangle = d;
}
triangle.iter().for_each(|r| println!("{}", r));
}
fn main() {
let order = std::env::args()
.nth(1)
.unwrap_or_else(|| "4".to_string())
.parse::<usize>()
.unwrap();
sierpinski(order);
}
</syntaxhighlight>
{{out}}
<pre>
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
</pre>
=={{header|Scala}}==
The Ruby command-line version (on Windows):
<
The Forth version:
<
def star(n: Long) = if ((n & 1L) == 1L) "*" else " "
def stars(n: Long): String = if (n == 0L) "" else star(n) + " " + stars(n >> 1)
Line 3,073 ⟶ 5,360:
(bitmap << 1) ^ bitmap
}
}</
The Haskell version:
<
def sierpinski(n: Int): List[String] = {
lazy val down = sierpinski(n - 1)
Line 3,087 ⟶ 5,374:
}
sierpinski(n) foreach println
}</
=={{header|Scheme}}==
{{trans|Haskell}}
<
(for-each
(lambda (x) (display (list->string x)) (newline))
Line 3,102 ⟶ 5,389:
(map (lambda (x) (append x (list #\ ) x)) acc))
(append spaces spaces)
(- n 1))))))</
=={{header|Seed7}}==
<
const func array string: sierpinski (in integer: n) is func
Line 3,132 ⟶ 5,419:
begin
writeln(join(sierpinski(4), "\n"));
end func;</
=={{header|SETL}}==
<syntaxhighlight lang="setl">program sierpinski;
const size = 4;
loop for i in [0..size*4-1] do
putchar(' ' * (size*4-1-i));
c := 1;
loop for j in [0..i] do
putchar(if c mod 2=0 then " " else " *" end);
c := c*(i-j) div (j+1);
end loop;
print;
end loop;
end program;</syntaxhighlight>
{{out}}
<pre> *
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *</pre>
=={{header|Sidef}}==
<
var triangle = ['*']
{ |i|
var sp = (' ' *
triangle = (triangle.map {|x| sp + x + sp} +
triangle.map {|x| x + ' ' + x})
} * n
triangle.join("\n")
}
say sierpinski_triangle(4)
=={{header|Swift}}==
{{trans|Java}}
<syntaxhighlight lang="text">import Foundation
// Easy get/set of charAt
Line 3,192 ⟶ 5,511:
line[n + i + 1] = "*"
}
}</
=={{header|Tcl}}==
{{trans|Perl}}
<
proc map {lambda list} {
Line 3,218 ⟶ 5,537:
}
puts [sierpinski_triangle 4]</
=={{header|TI-83 BASIC}}==
Uses Wolfram Rule 90.
<
:ClrHome
:Output(1,8,"^")
Line 3,252 ⟶ 5,571:
:L3→L2
:End
</syntaxhighlight>
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">Input "Triangle order: ";n
n = 2^n
Line 3,276 ⟶ 5,595:
Print
Next
End</
=={{header|Unlambda}}==
<
`k``s``s``s``s`s`k`s``s`ksk`k``s``si`kk`k``s`kkk
`k``s`k`s``si`kk``s`kk``s``s``s``si`kk`k`s`k`s``s`ksk`k`s`k`s`k`si``si`k`ki
`k``s`k`s``si`k`ki``s`kk``s``s``s``si`kk`k`s`k`s`k`si`k`s`k`s``s`ksk``si`k`ki
`k`ki``s`k`s`k`si``s`kkk</
This produces an infinite, left-justified triangle:
<pre style="height:30ex;overflow:scroll;">
Line 3,326 ⟶ 5,645:
=={{header|Ursala}}==
the straightforward recursive solution
<
triangle = ~&a^?\<<&>>! ^|RNSiDlrTSPxSxNiCK9xSx4NiCSplrTSPT/~& predecessor</
the cheeky cellular automaton solution
<
#import nat
rule = -$<0,&,0,0,&,0,0,0>@rSS zipp0*ziD iota8
evolve "n" = @iNC ~&x+ rep"n" ^C\~& @h rule*+ swin3+ :/0+ --<0>
sierpinski = iota; --<&>@NS; iota; ^H/evolve@z @NS ^T/~& :/&</
an example of each (converting from booleans to characters)
<
examples = mat0 ~&?(`*!,` !)*** <sierpinski3,triangle4></
{{out}}
<pre style="height:30ex;overflow:scroll;">
Line 3,368 ⟶ 5,687:
* * * * * * * * * * * * * * * *
</pre>
=={{header|Uxntal}}==
<syntaxhighlight lang="Uxntal">( uxncli sierpinski.rom )
|100 @on-reset ( -> )
#10 STHk #01 SUB
&ver ( -- )
DUP
#00 EQUk ?{
&pad ( -- )
#2018 DEO
INC GTHk ?&pad
} POP
#00
&fill
ANDk #202a ROT ?{ SWP } POP #18 DEO
#2018 DEO
INC ADDk STHkr LTH ?&fill
POP2
#0a18 DEO
#01 SUB DUP #ff NEQ ?&ver
POP POPr
BRK</syntaxhighlight>
The triangle size is given by the first instruction <code>#10</code>, representing the number of rows to print.
=={{header|VBA}}==
{{Trans|Phix}}<syntaxhighlight lang="vb">Sub sierpinski(n As Integer)
Dim lim As Integer: lim = 2 ^ n - 1
For y = lim To 0 Step -1
Debug.Print String$(y, " ")
For x = 0 To lim - y
Debug.Print IIf(x And y, " ", "# ");
Next
Debug.Print
Next y
End Sub
Public Sub main()
Dim i As Integer
For i = 1 To 5
sierpinski i
Next i
End Sub</syntaxhighlight>{{out}}
<pre style="font-size: 4px">
#
# #
#
# #
# #
# # # #
#
# #
# #
# # # #
# #
# # # #
# # # #
# # # # # # # #
#
# #
# #
# # # #
# #
# # # #
# # # #
# # # # # # # #
# #
# # # #
# # # #
# # # # # # # #
# # # #
# # # # # # # #
# # # # # # # #
# # # # # # # # # # # # # # # #
#
# #
# #
# # # #
# #
# # # #
# # # #
# # # # # # # #
# #
# # # #
# # # #
# # # # # # # #
# # # #
# # # # # # # #
# # # # # # # #
# # # # # # # # # # # # # # # #
# #
# # # #
# # # #
# # # # # # # #
# # # #
# # # # # # # #
# # # # # # # #
# # # # # # # # # # # # # # # #
# # # #
# # # # # # # #
# # # # # # # #
# # # # # # # # # # # # # # # #
# # # # # # # #
# # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # </pre>
=={{header|VBScript}}==
{{trans|PowerShell}}
<syntaxhighlight lang="vb">
Sub triangle(o)
n = 2 ^ o
Line 3,399 ⟶ 5,887:
triangle(4)
</syntaxhighlight>
=={{header|Vedit macro language}}==
Line 3,406 ⟶ 5,894:
The macro writes the fractal into an edit buffer where it can be viewed and saved to file if required.
This allows creating images larger than screen, the size is only limited by free disk space.
<
Buf_Switch(Buf_Free) // Open a new buffer for output
Ins_Char(' ', COUNT, #3*2+2) // fill first line with spaces
Line 3,423 ⟶ 5,911:
Ins_Char(#21, OVERWRITE)
Ins_Char('*', OVERWRITE)
}</
===Recursive===
{{trans|BASIC}}
Vedit macro language does not have recursive functions, so some pushing and popping is needed to implement recursion.
<
#2 = 1 // y
#3 = 16 // length (height of the triangle / 2)
Line 3,456 ⟶ 5,944:
Num_Pop(1,4)
}
Return</
=={{header|Wren}}==
{{trans|C}}
<syntaxhighlight lang="wren">var size = 1 << 4
for (y in size-1..0) {
System.write(" " * y)
for (x in 0...size-y) System.write((x&y != 0) ? " " : "* ")
System.print()
}</syntaxhighlight>
{{out}}
<pre>
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
</pre>
=={{header|X86 Assembly}}==
Translation of XPL0. Assemble with tasm, tlink /t
<
.code
.486
Line 3,487 ⟶ 6,004:
loop tri10 ;next I
ret
end start</
{{out}}
Line 3,510 ⟶ 6,027:
=={{header|XPL0}}==
<
def Order=4, Size=1<<Order;
int S1, S2, I;
Line 3,522 ⟶ 6,039:
S2:= S2 xor S1>>1;
];
]</
{{out}}
Line 3,543 ⟶ 6,060:
* * * * * * * * * * * * * * * *
</pre>
=={{header|Yabasic}}==
{{trans|Phix}}
<syntaxhighlight lang="yabasic">sub rep$(n, c$)
local i, s$
for i = 1 to n
s$ = s$ + c$
next
return s$
end sub
sub sierpinski(n)
local lim, y, x
lim = 2**n - 1
for y = lim to 0 step -1
print rep$(y, " ");
for x = 0 to lim-y
if and(x, y) then print " "; else print "* "; end if
next
print
next
end sub
for i = 1 to 5
sierpinski(i)
next
</syntaxhighlight>
=={{header|Zig}}==
{{trans|C}}
<syntaxhighlight lang="zig">const std = @import("std");
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
const size: u16 = 1 << 4;
var y = size;
while (y > 0) {
y -= 1;
for (0..y) |_| try stdout.writeByte(' ');
for (0..size - y) |x| try stdout.writeAll(if (x & y != 0) " " else "* ");
try stdout.writeByte('\n');
}
}</syntaxhighlight>
===Automaton===
{{trans|C}}
{{works with|Zig|0.11.0dev}}
<syntaxhighlight lang="zig">const std = @import("std");
const Allocator = std.mem.Allocator;
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
try sierpinski_triangle(allocator, stdout, 4);
}</syntaxhighlight><syntaxhighlight lang="zig">inline fn truth(x: u8) bool {
return x == '*';
}</syntaxhighlight><syntaxhighlight lang="zig">fn rule_90(allocator: Allocator, evstr: []u8) !void {
var cp = try allocator.dupe(u8, evstr);
defer allocator.free(cp); // free does "free" for last node in arena
for (evstr, 0..) |*evptr, i| {
var s = [2]bool{
if (i == 0) false else truth(cp[i - 1]),
if (i + 1 == evstr.len) false else truth(cp[i + 1]),
};
evptr.* = if ((s[0] and !s[1]) or (!s[0] and s[1])) '*' else ' ';
}
}</syntaxhighlight><syntaxhighlight lang="zig">fn sierpinski_triangle(allocator: Allocator, writer: anytype, n: u8) !void {
const len = std.math.shl(usize, 1, n + 1);
var b = try allocator.alloc(u8, len);
defer allocator.free(b);
for (b) |*ptr| ptr.* = ' ';
b[len >> 1] = '*';
try writer.print("{s}\n", .{b});
for (0..len / 2 - 1) |_| {
try rule_90(allocator, b);
try writer.print("{s}\n", .{b});
}
}</syntaxhighlight>
=={{header|zkl}}==
{{trans|D}}
<syntaxhighlight lang
foreach n in (
sp
d
}
d.concat("\n").println();</
{{out}}
<pre>
|