Sierpinski triangle: Difference between revisions

 
(26 intermediate revisions by 11 users not shown)
Line 35:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F sierpinski(n)
V d = [String(‘*’)]
L(i) 0 .< n
Line 42:
R d
 
print(sierpinski(4).join("\n"))</langsyntaxhighlight>
 
{{out}}
Line 65:
 
=={{header|8080 Assembly}}==
<langsyntaxhighlight 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
Line 125:
pop b
ret
nl: db 13,10,'$'</langsyntaxhighlight>
 
{{out}}
Line 149:
 
=={{header|8086 Assembly}}==
<langsyntaxhighlight 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
Line 190:
jnz line
ret
nl: db 13,10,'$'</langsyntaxhighlight>
 
{{out}}
Line 214:
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun pascal-row (prev)
(if (endp (rest prev))
(list 1)
Line 252:
(let ((height (1- (expt 2 levels))))
(print-odds (pascal-triangle height)
height)))</langsyntaxhighlight>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC Main()
BYTE x,y,size=[16]
 
Line 280:
FI
y==-1
OD</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sierpinski_triangle.png Screenshot from Atari 8-bit computer]
Line 304:
=={{header|Ada}}==
This Ada example creates a string of the binary value for each line, converting the '0' values to spaces.
<langsyntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
with Ada.Strings.Fixed;
with Interfaces; use Interfaces;
Line 356:
Sierpinski(N);
end loop;
end Sieteri_Triangles;</langsyntaxhighlight>
 
alternative using modular arithmetic:
<langsyntaxhighlight Adalang="ada">with Ada.Command_Line;
with Ada.Text_IO;
 
Line 386:
end if;
Sierpinski (N);
end Main;</langsyntaxhighlight>
{{out}}
<pre>XXXXXXXXXXXXXXXX
Line 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}} -->
<langsyntaxhighlight lang="algol68">PROC sierpinski = (INT n)[]STRING: (
FLEX[0]STRING d := "*";
FOR i TO n DO
Line 425:
);
 
printf(($gl$,sierpinski(4)))</langsyntaxhighlight>
 
=={{header|ALGOL W}}==
{{Trans|C}}
<langsyntaxhighlight lang="algolw">begin
integer SIZE;
SIZE := 16;
Line 442:
write();
end for_y
end.</langsyntaxhighlight>
 
=={{header|AppleScript}}==
Line 448:
{{Trans|Haskell}}
Centering any previous triangle block over two adjacent duplicates:
<langsyntaxhighlight AppleScriptlang="applescript">------------------- SIERPINKSI TRIANGLE ------------------
 
-- sierpinski :: Int -> [String]
Line 550:
on unwords(xs)
intercalate(space, xs)
end unwords</langsyntaxhighlight>
{{Out}}
<pre> *
Line 571:
Or generating each line as an XOR / Rule 90 / Pascal triangle rewrite of the previous line.
{{Trans|JavaScript}}
<langsyntaxhighlight AppleScriptlang="applescript">----------- SIERPINSKI TRIANGLE BY XOR / RULE 90 ---------
 
-- sierpinskiTriangle :: Int -> String
Line 717:
return lst
end tell
end zipWith</langsyntaxhighlight>
{{Out}}
<pre> *
Line 739:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">sierpinski: function [order][
s: shl 1 order
loop (s-1)..0 'y [
Line 751:
]
 
sierpinski 4</langsyntaxhighlight>
 
{{out}}
Line 773:
 
=={{header|ATS}}==
<syntaxhighlight lang="ats">
<lang ATS>
(* ****** ****** *)
//
Line 816:
//
} (* end of [main0] *)
</syntaxhighlight>
</lang>
 
=={{header|AutoHotkey}}==
ahk [http://www.autohotkey.com/forum/viewtopic.php?t=44657&postdays=0&postorder=asc&start=150 discussion]
<langsyntaxhighlight lang="autohotkey">Loop 6
MsgBox % Triangle(A_Index)
 
Line 838:
Triangle(n-1,x+u,y+u) ; smaller triangle down right
Return t
}</langsyntaxhighlight>
 
 
=={{header|APL}}==
<langsyntaxhighlight APLlang="apl">A←67⍴0⋄A[34]←1⋄' #'[1+32 67⍴{~⊃⍵:⍵,∇(1⌽⍵)≠¯1⌽⍵⋄⍬}A]</langsyntaxhighlight>
 
 
=={{header|AWK}}==
<langsyntaxhighlight AWKlang="awk"># WST.AWK - Waclaw Sierpinski's triangle contributed by Dan Nielsen
# syntax: GAWK -f WST.AWK [-v X=anychar] iterations
# example: GAWK -f WST.AWK -v X=* 2
Line 868:
}
exit(0)
}</langsyntaxhighlight>
 
=={{header|BASH (feat. sed & tr)}}==
Line 876:
other language just as well, but is particularly well suited for
tools like sed and tr.
<langsyntaxhighlight lang="bash">
#!/bin/bash
 
Line 900:
 
rec $1 | tr 'dsx' ' *'
</syntaxhighlight>
</lang>
 
=={{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 907 ⟶ 961:
<!-- {{works with|RapidQ}} doesn't work for me -- Erik Siers, 12 March 2012 -->
 
<langsyntaxhighlight lang="qbasic">DECLARE SUB triangle (x AS INTEGER, y AS INTEGER, length AS INTEGER, n AS INTEGER)
 
CLS
Line 920 ⟶ 974:
triangle x + length * 2, y + length, length / 2, n - 1
END IF
END SUB</langsyntaxhighlight>
 
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.
Line 926 ⟶ 980:
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">
<lang BASIC256>
clg
call triangle (1, 1, 60)
Line 941 ⟶ 995:
end if
end subroutine
</syntaxhighlight>
</lang>
 
 
==={{header|BBC BASIC}}===
<langsyntaxhighlight lang="bbcbasic"> MODE 8
OFF
Line 961 ⟶ 1,015:
PROCsierpinski(x%+l%+l%, y%+l%, l% DIV 2)
ENDIF
ENDPROC</langsyntaxhighlight>
 
==={{header|FreeBASIC}}===
<langsyntaxhighlight lang="freebasic">sub sier(x as uinteger, y as uinteger, l as uinteger)
if l=0 then
locate y, x: print "*"
Line 975 ⟶ 1,029:
 
cls
sier(1,1,2^3)</langsyntaxhighlight>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Triangle.bas"
110 TEXT 40
120 CALL TRIANGLE(1,1,8)
Line 989 ⟶ 1,043:
190 CALL TRIANGLE(X+2*L,Y+L,INT(L/2))
200 END IF
210 END DEF</langsyntaxhighlight>
 
=={{header|BCPL}}==
{{trans|C}}
<langsyntaxhighlight BCPLlang="bcpl">get "libhdr"
 
manifest $( SIZE = 1 << 4 $)
Line 1,004 ⟶ 1,058:
wrch('*N')
$)
$)</langsyntaxhighlight>
{{out}}
<pre> *
Line 1,027 ⟶ 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.
 
<langsyntaxhighlight lang="befunge">41+2>\#*1#2-#<:#\_$:1+v
v:$_:#`0#\\#00#:p#->#1<
>2/1\0p:2/\::>1-:>#v_1v
Line 1,033 ⟶ 1,087:
vg11<\*g11!:g 0-1:::<p<
>!*+!!\0g11p\ 0p1-:#^_v
@$$_\#!:#::#-^#1\$,+55<</langsyntaxhighlight>
 
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">{JPp{
-.'sgve!
J{JL[2./+.' j.*PppP.+PPj.+}m[
Line 1,043 ⟶ 1,097:
.+
}{vv{"*"}}PPie} 's sv
4 'sgve!unsh</langsyntaxhighlight>
 
=={{header|BQN}}==
<langsyntaxhighlight lang="bqn">Sierp ← {" •" ⊏˜ (⌽↕2⋆𝕩)⌽˘∾˘∾⟜0¨∧´∘∨⌜˜⥊↕2⥊˜𝕩}</langsyntaxhighlight>
 
{{out}}
Line 1,064 ⟶ 1,118:
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
 
#define SIZE (1 << 4)
Line 1,076 ⟶ 1,130:
}
return 0;
}</langsyntaxhighlight>
 
===Automaton===
This solution uses a cellular automaton (''rule 90'') with a proper initial status.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
Line 1,114 ⟶ 1,168:
}
free(cp);
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="c">void sierpinski_triangle(int n)
{
int i;
Line 1,133 ⟶ 1,187:
 
free(b);
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="c">int main()
{
sierpinski_triangle(4);
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections;
 
Line 1,180 ⟶ 1,234:
}
}
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="csharp">namespace RosettaCode {
class Program {
static void Main(string[] args) {
Line 1,189 ⟶ 1,243:
}
}
}</langsyntaxhighlight>
 
{{trans|C}}
{{works with|C sharp|C#|6.0+}}
<langsyntaxhighlight lang="csharp">using static System.Console;
class Sierpinsky
{
Line 1,208 ⟶ 1,262:
}
}
}</langsyntaxhighlight>
 
{{trans|OCaml}}
{{works with|C sharp|C#|3.0+}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,238 ⟶ 1,292:
Console.WriteLine(s);
}
}</langsyntaxhighlight>
 
Or, with fold / reduce (a.k.a. aggregate):
 
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,267 ⟶ 1,321:
foreach(string s in Sierpinski(4)) { Console.WriteLine(s); }
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{works with|C++11}}
A STL-centric recursive solution that uses the new lambda functions in C++11.
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <list>
Line 1,306 ⟶ 1,360:
sierpinski(4, ostream_iterator<string>(cout, "\n"));
return 0;
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
Line 1,312 ⟶ 1,366:
{{trans|Common Lisp}}
With a touch of Clojure's sequence handling.
<langsyntaxhighlight lang="clojure">(ns example
(:require [clojure.contrib.math :as math]))
 
Line 1,337 ⟶ 1,391:
(bit-xor (bit-shift-left v 1) (bit-shift-right v 1))))))
 
(sierpinski-triangle 4)</langsyntaxhighlight>
 
=={{header|CLU}}==
{{trans|Fortran}}
<langsyntaxhighlight lang="clu">sierpinski = proc (size: int) returns (string)
ss: stream := stream$create_output()
Line 1,367 ⟶ 1,421:
sierpinski(4)
)
end start_up</langsyntaxhighlight>
{{out}}
<pre> *
Line 1,388 ⟶ 1,442:
=={{header|COBOL}}==
{{trans|Fortran}} and retains a more Fortran-like coding style than is really idiomatic in COBOL.
<langsyntaxhighlight lang="cobol">identification division.
program-id. sierpinski-triangle-program.
data division.
Line 1,423 ⟶ 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).</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="lisp">(defun print-sierpinski (order)
(loop with size = (expt 2 order)
repeat size
Line 1,432 ⟶ 1,516:
do (fresh-line)
(loop for i below (integer-length v)
do (princ (if (logbitp i v) "*" " ")))))</langsyntaxhighlight>
 
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 1,440 ⟶ 1,524:
 
Alternate approach:
<langsyntaxhighlight lang="lisp">(defun sierpinski (n)
(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))</langsyntaxhighlight>
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
include "argv.coh";
 
Line 1,488 ⟶ 1,572:
print_nl();
y := y - 1;
end loop;</langsyntaxhighlight>
 
{{out}}
Line 1,511 ⟶ 1,595:
=={{header|D}}==
===Run-time Version===
<langsyntaxhighlight lang="d">void main() /*@safe*/ {
import std.stdio, std.algorithm, std.string, std.array;
 
Line 1,522 ⟶ 1,606:
}
d.join('\n').writeln;
}</langsyntaxhighlight>
{{out}}
<pre> *
Line 1,543 ⟶ 1,627:
===Compile-time Version===
Same output.
<langsyntaxhighlight lang="d">import std.string, std.range, std.algorithm;
 
string sierpinski(int level) pure nothrow /*@safe*/ {
Line 1,556 ⟶ 1,640:
 
pragma(msg, 4.sierpinski);
void main() {}</langsyntaxhighlight>
 
===Simple Version===
{{trans|C}}
Same output.
<langsyntaxhighlight lang="d">void showSierpinskiTriangle(in uint order) nothrow @safe @nogc {
import core.stdc.stdio: putchar;
 
Line 1,577 ⟶ 1,661:
void main() nothrow @safe @nogc {
4.showSierpinskiTriangle;
}</langsyntaxhighlight>
 
===Alternative Version===
This uses a different algorithm and shows a different output.
<langsyntaxhighlight lang="d">import core.stdc.stdio: putchar;
import std.algorithm: swap;
 
Line 1,622 ⟶ 1,706:
'\n'.putchar;
}
}</langsyntaxhighlight>
{{out}}
<pre> #
Line 1,693 ⟶ 1,777:
=={{header|Delphi}}==
{{trans|DWScript}}
<langsyntaxhighlight lang="delphi">program SierpinskiTriangle;
 
{$APPTYPE CONSOLE}
Line 1,718 ⟶ 1,802:
begin
PrintSierpinski(4);
end.</langsyntaxhighlight>
 
=={{header|Draco}}==
{{trans|C}}
<langsyntaxhighlight lang="draco">word SIZE = 1 << 4;
 
proc nonrec main() void:
Line 1,733 ⟶ 1,817:
writeln()
od
corp</langsyntaxhighlight>
{{out}}
<pre> *
Line 1,754 ⟶ 1,838:
=={{header|DWScript}}==
{{trans|E}}
<langsyntaxhighlight lang="delphi">procedure PrintSierpinski(order : Integer);
var
x, y, size : Integer;
Line 1,771 ⟶ 1,855:
 
PrintSierpinski(4);
</syntaxhighlight>
</lang>
 
=={{header|E}}==
<langsyntaxhighlight lang="e">def printSierpinski(order, out) {
def size := 2**order
for y in (0..!size).descending() {
Line 1,783 ⟶ 1,867:
out.println()
}
}</langsyntaxhighlight>
 
<syntaxhighlight lang ="e">? printSierpinski(4, stdout)</langsyntaxhighlight>
 
Non-ASCII version (quality of results will depend greatly on text renderer):
<langsyntaxhighlight lang="e">def printSierpinski(order, out) {
def size := 2**order
for y in (0..!size).descending() {
Line 1,797 ⟶ 1,881:
out.println()
}
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def sierpinski_triangle(n) do
f = fn(x) -> IO.puts "#{x}" end
Line 1,814 ⟶ 1,898:
end
 
RC.sierpinski_triangle(4)</langsyntaxhighlight>
 
=={{header|Elm}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="elm">import String exposing (..)
import Html exposing (..)
import Html.Attributes as A exposing (..)
Line 1,869 ⟶ 1,953:
, ("font-size", "1em")
, ("text-align", "left")
]</langsyntaxhighlight>
 
Link to live demo: http://dc25.github.io/sierpinskiElm/
Line 1,875 ⟶ 1,959:
=={{header|Erlang}}==
{{trans|OCaml}}
<langsyntaxhighlight lang="erlang">-module(sierpinski).
-export([triangle/1]).
 
Line 1,885 ⟶ 1,969:
triangle(N, Down, Sp) ->
NewDown = [Sp++X++Sp || X<-Down]++[X++" "++X || X <- Down],
triangle(N-1, NewDown, Sp++Sp).</langsyntaxhighlight>
 
=={{header|Euphoria}}==
{{trans|BASIC}}
<langsyntaxhighlight lang="euphoria">procedure triangle(integer x, integer y, integer len, integer n)
if n = 0 then
position(y,x) puts(1,'*')
Line 1,900 ⟶ 1,984:
 
clear_screen()
triangle(1,1,8,4)</langsyntaxhighlight>
 
=={{header|Excel}}==
Line 1,912 ⟶ 1,996:
 
{{Works with|Office 365 betas 2021}}
<langsyntaxhighlight lang="lisp">sierpinskiTriangle
=LAMBDA(c,
LAMBDA(n,
Line 1,956 ⟶ 2,040:
)
)(grid)
)</langsyntaxhighlight>
 
and also assuming the following generic bindings in the Name Manager for the WorkBook:
 
<langsyntaxhighlight lang="lisp">APPENDCOLS
=LAMBDA(xs,
LAMBDA(ys,
Line 2,018 ⟶ 2,102:
)
)
)</langsyntaxhighlight>
 
{{Out}}
Line 2,464 ⟶ 2,548:
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let sierpinski n =
let rec loop down space n =
if n = 0 then
Line 2,476 ⟶ 2,560:
let () =
List.iter (fun (i:string) -> System.Console.WriteLine(i)) (sierpinski 4)</langsyntaxhighlight>
 
=={{header|Factor}}==
{{trans|OCaml}}
<langsyntaxhighlight lang="factor">USING: io kernel math sequences ;
IN: sierpinski
 
Line 2,496 ⟶ 2,580:
 
: sierpinski ( n -- )
[ { "*" } " " ] dip (sierpinski) print ;</langsyntaxhighlight>
 
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}}==
{{incorrect|FALSE|DifferentRuns resultscorrectly with different interpreters (like http://morphett.info/false/false.html andin http://www.quirkster.com/iano/js/false-js.html}}.
Requires the pick character to be substituted with 'O' in the portable interpreter linked-to from https://strlen.com/false-language/.
<lang false>[[$][$1&["*"]?$~1&[" "]?2/]#%"
<syntaxhighlight lang="false">{ print spaces; in:n }
"]s: { stars }
[[$0>][" " 1-]#%]w:
[$@$@|@@&~&]x: { xor }
 
[1\[$][1-\2*\]#%]e: { 2^n }
{ left shift; in:x,y out:x<<y }
[e;!1\[$][\$s;!$2*x;!\1-]#%%]t:
[[$0>][\2*\ 1-]#%]l:
4t;!</lang>
 
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}}==
<langsyntaxhighlight FOCALlang="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
Line 2,521 ⟶ 2,638:
 
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)</langsyntaxhighlight>
 
{{out}}
Line 2,544 ⟶ 2,661:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: stars ( mask -- )
begin
dup 1 and if [char] * else bl then emit
Line 2,557 ⟶ 2,674:
loop 2drop ;
5 triangle</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="fortran">program Sierpinski_triangle
implicit none
Line 2,590 ⟶ 2,707:
end do
end subroutine Triangle
end program Sierpinski_triangle</langsyntaxhighlight>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Using parity of binomial coefficients
SierpinskiTriangle := function(n)
local i, j, s, b;
Line 2,630 ⟶ 2,747:
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * * </langsyntaxhighlight>
 
=={{header|gnuplot}}==
Making and printing a text string, using bit-twiddling to decide whether each character should be a space or a star.
 
<langsyntaxhighlight lang="gnuplot"># Return a string space or star to print at x,y.
# 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 2,650 ⟶ 2,767:
 
# Print rows 0 to 15, which is the order 4 triangle per the task.
print triangle(0,15)</langsyntaxhighlight>
 
=={{header|Go}}==
"Δ" (Greek capital letter delta) looks good for grain, as does Unicode triangle, "△". ASCII "." and "^" are pleasing. "/\\", "´`", and "◢◣"" make interesting wide triangles.
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,679 ⟶ 2,796:
fmt.Println(r)
}
}</langsyntaxhighlight>
 
=={{header|Golfscript}}==
Cambia el "3" a un número mayor para un triángulo más grande.
<langsyntaxhighlight lang="golfscript">' /\ /__\ '4/){.+\.{[2$.]*}%\{.+}%+\}3*;n*</langsyntaxhighlight>
{{out}}
<pre>
Line 2,706 ⟶ 2,823:
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def stPoints;
stPoints = { order, base=[0,0] ->
def right = [base[0], base[1]+2**order]
Line 2,721 ⟶ 2,838:
stPoints(order).each { grid[it[0]][it[1]] = (order%10).toString() }
grid
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">stGrid(0).reverse().each { println it.sum() }
println()
stGrid(1).reverse().each { println it.sum() }
Line 2,736 ⟶ 2,853:
stGrid(5).reverse().each { println it.sum() }
println()
stGrid(6).reverse().each { println it.sum() }</langsyntaxhighlight>
 
{{out}}
Line 2,876 ⟶ 2,993:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">sierpinski 0 = ["*"]
sierpinski n = map ((space ++) . (++ space)) down ++
map (unwords . replicate 2) down
Line 2,882 ⟶ 2,999:
space = replicate (2 ^ (n - 1)) ' '
 
main = mapM_ putStrLn $ sierpinski 4</langsyntaxhighlight>
{{out}}
<pre>
Line 2,903 ⟶ 3,020:
 
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:
<langsyntaxhighlight lang="haskell">import Data.List (intercalate)
 
sierpinski :: Int -> [String]
Line 2,916 ⟶ 3,033:
 
main :: IO ()
main = mapM_ putStrLn $ sierpinski 4</langsyntaxhighlight>
{{Out}}
<pre> ▲---------------
Line 2,937 ⟶ 3,054:
 
Using bitwise and between x and y coords:
<langsyntaxhighlight lang="haskell">import Data.Bits ((.&.))
 
sierpinski n = map row [m, m-1 .. 0] where
Line 2,945 ⟶ 3,062:
| otherwise = " "
 
main = mapM_ putStrLn $ sierpinski 4</langsyntaxhighlight>
 
{{Trans|JavaScript}}
 
<langsyntaxhighlight Haskelllang="haskell">import Data.List (intersperse)
 
-- Top down, each row after the first is an XOR / Rule90 rewrite.
Line 2,973 ⟶ 3,090:
 
main :: IO ()
main = putStr $ sierpinski 4</langsyntaxhighlight>
 
Or simply as a right fold:
 
<langsyntaxhighlight lang="haskell">sierpinski :: Int -> [String]
sierpinski n =
foldr
Line 2,993 ⟶ 3,110:
 
main :: IO ()
main = (putStrLn . unlines . sierpinski) 4</langsyntaxhighlight>
 
{{Out}}
Line 3,014 ⟶ 3,131:
 
=={{header|Haxe}}==
<langsyntaxhighlight lang="haxe">class Main
{
static function main()
Line 3,048 ⟶ 3,165:
}
}
}</langsyntaxhighlight>
 
=={{header|Hoon}}==
<langsyntaxhighlight Hoonlang="hoon">|= n=@ud
=+ m=0
=+ o=(reap 1 '*')
Line 3,059 ⟶ 3,176:
++ top (turn o |=(l=@t (rap 3 gap l gap ~)))
++ bot (turn o |=(l=@t (rap 3 l ' ' l ~)))
--</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight Iconlang="icon"># text based adaptaion of
 
procedure main(A)
Line 3,077 ⟶ 3,194:
writes((y=1,"\n")|"",canvas[x,y]," ") # print
 
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 3,096 ⟶ 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.
<langsyntaxhighlight lang="idl">pro sierp,n
s = (t = bytarr(3+2^(n+1))+32b)
t[2^n+1] = 42b
Line 3,103 ⟶ 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</langsyntaxhighlight>
 
=={{header|J}}==
There are any number of succinct ways to produce this in J.
Here's one that exploits self-similarity:
<langsyntaxhighlight lang="j"> |. _31]\ ,(,.~ , ])^:4 ,: '* '</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="j"> ' *' {~ '1' = (- |."_1 [: ": 2 | !/~) i._16</langsyntaxhighlight>
 
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 3,122 ⟶ 3,239:
Replace translations.
Recursive solution.
<langsyntaxhighlight lang="java">
 
public class SierpinskiTriangle {
Line 3,168 ⟶ 3,285:
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,192 ⟶ 3,309:
=={{header|JavaFX Script}}==
{{trans|Python}}
<langsyntaxhighlight lang="javafx">function sierpinski(n : Integer) {
var down = ["*"];
var space = " ";
Line 3,205 ⟶ 3,322:
}
 
sierpinski(4);</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 3,215 ⟶ 3,332:
mapping the binary pattern to centred strings.
 
<langsyntaxhighlight JavaScriptlang="javascript">(function (order) {
 
// Sierpinski triangle of order N constructed as
Line 3,273 ⟶ 3,390:
 
})(4);
</syntaxhighlight>
</lang>
 
Output (N=4)
Line 3,296 ⟶ 3,413:
====Imperative====
 
<langsyntaxhighlight lang="javascript">function triangle(o) {
var n = 1 << o,
line = new Array(2 * n),
Line 3,316 ⟶ 3,433:
document.write("<pre>\n");
triangle(6);
document.write("</pre>");</langsyntaxhighlight>
 
===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:
<langsyntaxhighlight lang="javascript">(() => {
'"use strict'";
 
// --------------- SIERPINSKI TRIANGLE ---------------
 
// sierpinski :: Int -> String
Line 3,330 ⟶ 3,449:
.reduce(
(xs, _, i) => {
const s = '" '".repeat(Math.pow(2, ** i));
 
return xs.map(x => s + x + s)
return .concat([
...xs.map(x => xs + ' 'x + xs),
...xs.map(x => `${x} ${x}`)
];
},
['"*'"]
).join('\n');
.join("\n");
 
// TEST ---------------------- TEST -----------------------
return sierpinski(4);
console.log(
})();</syntaxhighlight>
sierpinski(4)
);
})();</lang>
 
{{Trans|Haskell}}
Centering any preceding triangle block over two adjacent duplicates:
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'"use strict'";
 
// ----- LINES OF SIERPINSKI TRIANGLE AT LEVEL N -------------------------------
 
// sierpinski :: Int -> [String]
const sierpTriangle = n =>
// Previous triangle centered with left and right padding,
(n// >left 0)and ?right concat(ap([padding,
0 < n ? map(xs => intercalate(xs, ap(
ap([
[s => concat(replicate(Math.pow(2, (n - 1)), s))], [' ', '-']
))), map(
xs => ap([
// above a pair of duplicates, placed one character apart. compose(
map(xs ks => intercalateks.join('+', [xs, xs])""),
], [sierpTriangle replicate(2 ** (n - 1)])) : ['▲'];
)
])([" ", "-"])
.join(xs)
),
 
// above a pair of duplicates,
// placed one character apart.
map(s => `${s}+${s}`)
])([sierpTriangle(n - 1)])
.flat()
) : ["▲"];
 
// GENERIC FUNCTIONS -----------------------------------------------------
 
// ---------------------- TEST -----------------------
// replicate :: Int -> a -> [a]
const replicatemain = (n, a) => {
let v = [a],sierpTriangle(4)
o = [].join("\n");
if (n < 1) return o;
while (n > 1) {
if (n & 1) o = o.concat(v);
n >>= 1;
v = v.concat(v);
}
return o.concat(v);
};
 
// curry :: ((a, b) -> c) -> a -> b -> c
const curry = f => a => b => f(a, b);
 
// ---------------- GENERIC FUNCTIONS ----------------
// map :: (a -> b) -> [a] -> [b]
const map = curry((f, xs) => xs.map(f));
 
// Applyap a(<*>) list:: of[(a functions-> tob)] a-> list[a] of-> arguments[b]
//const <*>ap ::= [(afs -=> b)] -> [a] -> [b]
// The sequential application of each of a list
const ap = (fs, xs) => //
// of functions to each of a list of values.
[].concat.apply([], fs.map(f => //
// apList([x => 2 [].concat.apply([]* x, xs.map(x => [f(20 + x)])([1, 2, 3])));
// -> [2, 4, 6, 21, 22, 23]
xs => fs.flatMap(f => xs.map(f));
 
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
 
// intercalatecompose (<<<) :: String(b -> c) -> (a -> b) -> [a] -> Stringc
const intercalatecompose = (s, xs...fs) => xs.join(s);
// 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
);
 
// concat :: [[a]] -> [a] || [String] -> String
const concat = xs => {
if (xs.length > 0) {
const unit = typeof xs[0] === 'string' ? '' : [];
return unit.concat.apply(unit, xs);
} else return [];
};
 
// map :: (a -> b) -> [a] -> [b]
// TEST ------------------------------------------------------------------
returnconst unlines(sierpTrianglemap = f => xs => xs.map(4)f);
 
})();</lang>
 
// 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> ▲---------------
Line 3,429 ⟶ 3,556:
Or constructed as 2^N lines of Pascal's triangle mod 2,
and mapped to centred {1:asterisk, 0:space} strings.
<syntaxhighlight lang="javascript">(() => {
<lang JavaScript>
"use strict";
(order => {
 
// --------------- SIERPINSKI TRIANGLE ---------------
 
// sierpinski :: Int -> [Bool]
letconst sierpinski = intOrder => {
// Reduce/folding from the last item (base of list)
// which has zero left indent.
 
// asciiPascalMod2Each ::preceding Introw ->has [[Int]]one more indent space
let// asciiPascalMod2than =the nRowsrow =>beneath it.
rangepascalMod2Chars(1, nRows2 -** 1intOrder)
.reducereduceRight(sofar(a, x) => {([
let lstPrev = sofar`${a[1]}${x.slicejoin(-1" ")}\n${a[0];}`,
`${a[1]} `
]), ["", ""])[0];
 
// The composition of (asciiBinary . mod 2 . add)
// is reduced here to a rule from two parent characters
// to a single child character.
 
// pascalMod2Chars :: Int -> [[Char]]
// Rule 90 also reduces to the same XOR
const pascalMod2Chars = nRows =>
// relationship between left and right neighbours.
enumFromTo(1)(nRows - 1)
.reduce(sofar => {
const rows = sofar.slice(-1)[0];
 
// Rule 90 also returnreduces sofarto the same XOR
// relationship between left and right neighbours.concat([zipWith(
return (left, right) => left === right ? ' ' : '*',[
[' '].concat(lstPrev)..sofar,
lstPrev.concatzipWith(' ')
)]);l => r => l === r ? (
}, [ " "
['*'] // Tip of triangle) : "*"
)([" ", ...rows])([...rows, " "])
]);
}, [
["*"]
]);
 
// ---------------------- TEST -----------------------
// Reduce/folding from the last item (base of list)
// which hasmain zero:: leftIO indent.()
const main = () =>
sierpinski(4);
 
 
// Each preceding row has one more indent space than the row beneath it
// --------------------- GENERIC ---------------------
return asciiPascalMod2(Math.pow(2, intOrder))
.reduceRight((a, x) => {
return {
triangle: a.indent + x.join(' ') + '\n' + a.triangle,
indent: a.indent + ' '
}
}, {
triangle: '',
indent: ''
}).triangle
};
 
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
letconst zipWith = (f, xs, ys) =>
// A list constructed xs.lengthby ===zipping ys.lengthwith ? (a
// custom xs.map((xfunction, i)rather =>than f(x,with ys[i]))the
// default tuple ) : undefined,constructor.
xs => ys => xs.map(
(x, i) => f(x)(ys[i])
).slice(
0, Math.min(xs.length, ys.length)
);
 
// range(intFrom, intTo, optional intStep)
// Int -> Int -> Maybe Int -> [Int]
range = (m, n, step) => {
let d = (step || 1) * (n >= m ? 1 : -1);
 
// enumFromTo :: Int -> Int -> [Int]
return Array.from({
const enumFromTo = m =>
length: Math.floor((n - m) / d) + 1
}, (_, i)n => m + Array.from(i * d));{
}; length: 1 + n - m
}, (_, i) => m + i);
 
return sierpinski(order);
 
})(4);</lang>
 
// MAIN ---
return main();
})();</syntaxhighlight>
{{Out}}
<pre> *
Line 3,515 ⟶ 3,647:
'''Works with gojq, the Go implementation of jq'''
 
'''Preliminaries'''
This entry uses an L-system and turtle graphics to generate an SVG
<syntaxhighlight lang="jq">def elementwise(f):
file, which can be viewed using a web browser, at least if the file type is `.svg`.
transpose | map(f) ;
 
# input: an array of decimal numbers
See [[Category_talk:Jq-turtle]] for the turtle.jq module used here.
def bitwise_and:
Please note that the `include` directive below may need to be modified,
# Input: an integer
depending on the command-line options used
# Output: a stream of 0s and 1s
and the location of the included file.
def stream:
<lang jq>include "turtle" {search: "."};
recurse(if . > 0 then ./2|floor else empty end) | . % 2 ;
 
# Input: a 0-1 array
# Compute the curve using a Lindenmayer system of rules
def rulestoi:
reduce .[] as $c ( {power:1 , ans: 0};
# "H" signfies Horizontal motion
.ans += ($c * .power) | .power *= 2 )
{X: "XX",
| .ans;
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) ;
 
if any(.==0) then 0
def interpret($x):
else map([stream])
if $x == "+" then turtleRotate(-60)
| (map(length) | min) as $min
elif $x == "-" then turtleRotate(60)
| map( .[:$min] ) | elementwise(min) | toi
else turtleForward(20)
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>
def sierpinski_curve($n):
{{out}}
sierpinski($n)
As elsewhere.
| 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</lang>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function sierpinski(n, token::AbstractString="*")
x = fill(token, 1, 1)
for _ in 1:n
Line 3,585 ⟶ 3,700:
end
 
sierpinski(4) |> printsierpinski</langsyntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|C}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
const val ORDER = 4
Line 3,600 ⟶ 3,715:
println()
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,621 ⟶ 3,736:
* * * * * * * * * * * * * * * *
</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}}==
<langsyntaxhighlight lang="lb">nOrder=4
call triangle 1, 1, nOrder
end
Line 3,637 ⟶ 3,798:
call triangle x+length*2, y+length, n
END IF
END SUB</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">; Print rows of the triangle from 0 to :limit inclusive.
; 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 3,653 ⟶ 3,814:
]
print []
]</langsyntaxhighlight>
 
=={{header|Lua}}==
Ported from the list-comprehension Python version.
 
<langsyntaxhighlight lang="lua">function sierpinski(depth)
lines = {}
lines[1] = '*'
Line 3,674 ⟶ 3,835:
end
 
print(sierpinski(4))</langsyntaxhighlight>
{{out}}
<pre>
Line 3,696 ⟶ 3,857:
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">S := proc(n)
local i, j, values, position;
values := [ seq(" ",i=1..2^n-1), "*" ];
Line 3,710 ⟶ 3,871:
printf("%s\n",cat(op(convert(values, list))));
end do:
end proc:</langsyntaxhighlight>
{{out}}
<pre>
Line 3,733 ⟶ 3,894:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Cellular automaton (rule 90) based solution:
<langsyntaxhighlight lang="mathematica">n=4;Grid[CellularAutomaton[90,{{1},0},2^n-1]/.{0->" ",1->"*"},ItemSize->All]</langsyntaxhighlight>
Using built-in function:
<syntaxhighlight lang ="mathematica">SierpinskiMesh[3]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
STRING was introduced in version R2016b.
<langsyntaxhighlight MATLABlang="matlab">n = 4;
d = string('*');
for k = 0 : n - 1
Line 3,746 ⟶ 3,907:
end
disp(d.join(char(10)))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,767 ⟶ 3,928:
</pre>
===Cellular Automaton Version===
<langsyntaxhighlight MATLABlang="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)</langsyntaxhighlight>
 
===Mixed Version===
<langsyntaxhighlight lang="matlab">spy(mod(abs(pascal(32,1)),2)==1)</langsyntaxhighlight>
 
=={{header|NetRexx}}==
{{trans|Java}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 3,818 ⟶ 3,979:
end row
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,841 ⟶ 4,002:
=={{header|Nim}}==
{{trans|C}}
<langsyntaxhighlight lang="nim">const size = 1 shl 4 - 1
 
for y in countdown(size, 0):
Line 3,851 ⟶ 4,012:
else:
stdout.write "* "
stdout.write "\n"</langsyntaxhighlight>
 
{{out}}
Line 3,872 ⟶ 4,033:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let sierpinski n =
let rec loop down space n =
if n = 0 then
Line 3,884 ⟶ 4,045:
 
let () =
List.iter print_endline (sierpinski 4)</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 3,892 ⟶ 4,053:
automat(rule, n) runs cellular automaton for rule "rule" for n generations.
 
<langsyntaxhighlight Oforthlang="oforth">: nextGen(l, r)
| i |
StringBuffer new
Line 3,907 ⟶ 4,068:
 
: sierpinskiTriangle(n)
90 4 n * automat ;</langsyntaxhighlight>
 
{{out}}
Line 3,933 ⟶ 4,094:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
fun {NextTriangle Triangle}
Sp = {Spaces {Length Triangle}}
Line 3,951 ⟶ 4,112:
SierpinskiTriangles = {Iterate NextTriangle ["*"]}
in
{ForAll {Nth SierpinskiTriangles 5} System.showInfo}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
{{trans|C}}
<langsyntaxhighlight lang="parigp">Sierpinski(n)={
my(s=2^n-1);
forstep(y=s,0,-1,
Line 3,965 ⟶ 4,126:
)
};
Sierpinski(4)</langsyntaxhighlight>
{{out}}
<pre> *
Line 3,987 ⟶ 4,148:
{{trans|C}}
{{works with|Free Pascal}}
<langsyntaxhighlight lang="pascal">program Sierpinski;
 
function ipow(b, n : Integer) : Integer;
Line 4,004 ⟶ 4,165:
else
truth := false
end;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="pascal">function rule_90(ev : String) : String;
var
l, i : Integer;
Line 4,046 ⟶ 4,207:
writeln(b)
end
end;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="pascal">begin
triangle(4)
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
===version 1===
<langsyntaxhighlight lang="perl">sub sierpinski {
my ($n) = @_;
my @down = '*';
Line 4,065 ⟶ 4,226:
}
 
print "$_\n" foreach sierpinski 4;</langsyntaxhighlight>
 
===one-liner===
<langsyntaxhighlight 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;}'</langsyntaxhighlight>
 
=={{header|Phix}}==
{{Trans|C}}
<!--<langsyntaxhighlight Phixlang="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>
Line 4,088 ⟶ 4,249:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre style="font-size: 2px">
Line 4,156 ⟶ 4,317:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">def sierpinski
2 swap power 1 - var lim
lim 0 -1 3 tolist for
Line 4,170 ⟶ 4,331:
5 for
sierpinski
endfor</langsyntaxhighlight>
 
=={{header|PHP}}==
Line 4,176 ⟶ 4,337:
{{Trans|JavaScript}}
 
<langsyntaxhighlight PHPlang="php"><?php
 
function sierpinskiTriangle($order) {
Line 4,200 ⟶ 4,361:
 
sierpinskiTriangle(4);
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,220 ⟶ 4,381:
# # # # # # # # # # # # # # # #
</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}}
<langsyntaxhighlight PicoLisplang="picolisp">(de sierpinski (N)
(let (D '("*") S " ")
(do N
Line 4,233 ⟶ 4,449:
D ) )
 
(mapc prinl (sierpinski 4))</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">sierpinski: procedure options (main); /* 2010-03-30 */
declare t (79,79) char (1);
declare (i, j, k) fixed binary;
Line 4,284 ⟶ 4,500:
end make_triangle;
 
end sierpinski;</langsyntaxhighlight>
 
=={{header|PL/M}}==
<langsyntaxhighlight lang="plm">100H:
 
DECLARE ORDER LITERALLY '4';
Line 4,323 ⟶ 4,539:
 
CALL BDOS(0,0);
EOF</langsyntaxhighlight>
{{out}}
<pre> *
Line 4,345 ⟶ 4,561:
Solution using line buffer in an integer array oline, 0 represents ' '
(space), 1 represents '*' (star).
<langsyntaxhighlight lang="pop11">define triangle(n);
lvars k = 2**n, j, l, oline, nline;
initv(2*k+3) -> oline;
Line 4,365 ⟶ 4,581:
enddefine;
 
triangle(4);</langsyntaxhighlight>
 
Alternative solution, keeping all triangle as list of strings
<langsyntaxhighlight lang="pop11">define triangle2(n);
lvars acc = ['*'], spaces = ' ', j;
for j from 1 to n do
Line 4,378 ⟶ 4,594:
enddefine;
 
triangle2(4);</langsyntaxhighlight>
 
=={{header|PostScript}}==
This draws the triangles in a string-rewrite fashion, where all edges form a single polyline. 9 page document showing progession.
<langsyntaxhighlight lang="postscript">%!PS-Adobe-3.0
%%BoundingBox 0 0 300 300
 
Line 4,396 ⟶ 4,612:
0 1 8 { 300 300 scale 0 1 12 div moveto
X + F + F fill showpage } for
%%EOF</langsyntaxhighlight>
 
=={{header|PowerShell}}==
{{Trans|JavaScript}}
<langsyntaxhighlight lang="powershell">function triangle($o) {
$n = [Math]::Pow(2, $o)
$line = ,' '*(2*$n+1)
Line 4,420 ⟶ 4,636:
$line[$n+$i+1] = '█'
}
}</langsyntaxhighlight>
 
=={{header|Processing}}==
 
===Characters in drawing canvas version===
<langsyntaxhighlight lang="java">void setup() {
size(410, 230);
background(255);
Line 4,439 ⟶ 4,655:
sTriangle(x+l*2, y+l, l/2, n-1);
}
}</langsyntaxhighlight>
===Text in console version===
{{trans|Java}}
<langsyntaxhighlight lang="java">void setup() {
print(getSierpinskiTriangle(3));
}
Line 4,478 ⟶ 4,694:
return ns;
}
</syntaxhighlight>
</lang>
 
=={{header|Prolog}}==
Works with SWI-Prolog;
<langsyntaxhighlight Prologlang="prolog">sierpinski_triangle(N) :-
Len is 2 ** (N+1) - 1,
length(L, Len),
Line 4,522 ⟶ 4,738:
rule_90(' ',' ','*', '*').
rule_90(' ',' ',' ', ' ').
</syntaxhighlight>
</lang>
{{out}}
<pre> ?- sierpinski_triangle(4).
Line 4,544 ⟶ 4,760:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure Triangle (X,Y, Length, N)
If N = 0
DrawText( Y,X, "*",#Blue)
Line 4,563 ⟶ 4,779:
Repeat
Until WaitWindowEvent()=#PB_Event_CloseWindow
End</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">def sierpinski(n):
d = ["*"]
for i in xrange(n):
Line 4,573 ⟶ 4,789:
return d
 
print "\n".join(sierpinski(4))</langsyntaxhighlight>
 
 
Or, using fold / reduce {{works with|Python|3.x}}
<langsyntaxhighlight lang="python">import functools
 
def sierpinski(n):
Line 4,587 ⟶ 4,803:
return functools.reduce(aggregate, range(n), ["*"])
 
print("\n".join(sierpinski(4)))</langsyntaxhighlight>
 
and fold/reduce, wrapped as concatMap, can provide the list comprehensions too:
<langsyntaxhighlight lang="python">'''Sierpinski triangle'''
 
from functools import reduce
Line 4,620 ⟶ 4,836:
 
 
print(sierpinski(4))</langsyntaxhighlight>
{{Out}}
<pre> *
Line 4,641 ⟶ 4,857:
 
Use Python's long integer and bit operator to make an infinite triangle:
<langsyntaxhighlight lang="python">x = 1
while True:
print(bin(x)[2:].replace('0', ' '))
x ^= x<<1</langsyntaxhighlight>
 
=={{header|Quackery}}==
Line 4,650 ⟶ 4,866:
{{trans|Forth}}
 
<langsyntaxhighlight Quackerylang="quackery"> [ [ dup 1 &
iff char * else space
emit
Line 4,664 ⟶ 4,880:
2drop ] is triangle ( order --> )
 
4 triangle</langsyntaxhighlight>
 
{{out}}
Line 4,688 ⟶ 4,904:
=={{header|R}}==
Based on C# but using some of R's functionality to abbreviate code where possible.
<langsyntaxhighlight lang="r">sierpinski.triangle = function(n) {
len <- 2^(n+1)
b <- c(rep(FALSE,len/2),TRUE,rep(FALSE,len/2))
Line 4,700 ⟶ 4,916:
}
}
sierpinski.triangle(5)</langsyntaxhighlight>
 
Shortened to a function of one line.
<langsyntaxhighlight lang="r">sierpinski.triangle = function(n) {
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")</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(define (sierpinski n)
Line 4,720 ⟶ 4,936:
(map (λ(x) (~a x " " x)) prev)))))
(for-each displayln (sierpinski 5))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{trans|Perl}}
<syntaxhighlight lang="raku" perl6line>sub sierpinski ($n) {
my @down = '*';
my $space = ' ';
Line 4,735 ⟶ 4,951:
}
.say for sierpinski 4;</langsyntaxhighlight>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program constructs and displays a Sierpinski triangle of up to around order 10k.*/
parse arg n mark . /*get the order of Sierpinski triangle.*/
if n=='' | n=="," then n=4 /*Not specified? Then use the default.*/
Line 4,754 ⟶ 4,970:
say z /*display a line of the triangle. */
end /*j*/ /* [↑] finished showing triangle. */
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
'''output''' &nbsp; when using the default input of order: &nbsp; <tt> 4 </tt>
 
Line 4,959 ⟶ 5,175:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Sierpinski triangle
 
Line 4,982 ⟶ 5,198:
triangle(x+length*2, y+length, n)
ok
</syntaxhighlight>
</lang>
Output:
<pre>
Line 5,005 ⟶ 5,221:
=={{header|Ruby}}==
From the command line:
<langsyntaxhighlight lang="ruby">ruby -le'16.times{|y|print" "*(15-y),*(0..y).map{|x|~y&x>0?" ":" *"}}'</langsyntaxhighlight>
 
or, {{trans|Python}}
<langsyntaxhighlight lang="ruby">def sierpinski_triangle(n)
triangle = ["*"]
n.times do |i|
Line 5,018 ⟶ 5,234:
end
 
puts sierpinski_triangle(4)</langsyntaxhighlight>
 
Using fold / reduce (aka. inject):
 
<langsyntaxhighlight lang="ruby">def sierpinski_triangle(n)
(0...n).inject(["*"]) {|triangle, i|
space = " " * (2**i)
Line 5,029 ⟶ 5,245:
end
 
puts sierpinski_triangle(4)</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">nOrder=4
dim xy$(40)
for i = 1 to 40
Line 5,053 ⟶ 5,269:
call triangle x+length*2, y+length, n
END IF
END SUB</langsyntaxhighlight>
<pre> *
* *
Line 5,071 ⟶ 5,287:
* * * * * * * * * * * * * * * *</pre>
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
use std::iter::repeat;
 
Line 5,109 ⟶ 5,325:
}
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,132 ⟶ 5,348:
=={{header|Scala}}==
The Ruby command-line version (on Windows):
<langsyntaxhighlight lang="scala">scala -e "for(y<-0 to 15){println(\" \"*(15-y)++(0 to y).map(x=>if((~y&x)>0)\" \"else\" *\")mkString)}"</langsyntaxhighlight>
 
The Forth version:
<langsyntaxhighlight lang="scala">def sierpinski(n: Int) {
def star(n: Long) = if ((n & 1L) == 1L) "*" else " "
def stars(n: Long): String = if (n == 0L) "" else star(n) + " " + stars(n >> 1)
Line 5,144 ⟶ 5,360:
(bitmap << 1) ^ bitmap
}
}</langsyntaxhighlight>
 
The Haskell version:
<langsyntaxhighlight lang="scala">def printSierpinski(n: Int) {
def sierpinski(n: Int): List[String] = {
lazy val down = sierpinski(n - 1)
Line 5,158 ⟶ 5,374:
}
sierpinski(n) foreach println
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="scheme">(define (sierpinski n)
(for-each
(lambda (x) (display (list->string x)) (newline))
Line 5,173 ⟶ 5,389:
(map (lambda (x) (append x (list #\ ) x)) acc))
(append spaces spaces)
(- n 1))))))</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func array string: sierpinski (in integer: n) is func
Line 5,203 ⟶ 5,419:
begin
writeln(join(sierpinski(4), "\n"));
end func;</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="ruby">func sierpinski_triangle(n) {
var triangle = ['*']
{ |i|
Line 5,216 ⟶ 5,464:
}
 
say sierpinski_triangle(4)</langsyntaxhighlight>
 
=={{header|Swift}}==
{{trans|Java}}
<syntaxhighlight lang="text">import Foundation
 
// Easy get/set of charAt
Line 5,263 ⟶ 5,511:
line[n + i + 1] = "*"
}
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{trans|Perl}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
proc map {lambda list} {
Line 5,289 ⟶ 5,537:
}
 
puts [sierpinski_triangle 4]</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
Uses Wolfram Rule 90.
<langsyntaxhighlight lang="ti83b">PROGRAM:SIRPNSKI
:ClrHome
:Output(1,8,"^")
Line 5,323 ⟶ 5,571:
:L3→L2
:End
</syntaxhighlight>
</lang>
 
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">Input "Triangle order: ";n
n = 2^n
 
Line 5,347 ⟶ 5,595:
Print
Next
End</langsyntaxhighlight>
 
=={{header|Unlambda}}==
<langsyntaxhighlight Unlambdalang="unlambda">```ci``s``s`ks``s`k`s``s`kc``s``s``si`kr`k. `k.*k
`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</langsyntaxhighlight>
This produces an infinite, left-justified triangle:
<pre style="height:30ex;overflow:scroll;">
Line 5,397 ⟶ 5,645:
=={{header|Ursala}}==
the straightforward recursive solution
<langsyntaxhighlight Ursalalang="ursala">#import nat
 
triangle = ~&a^?\<<&>>! ^|RNSiDlrTSPxSxNiCK9xSx4NiCSplrTSPT/~& predecessor</langsyntaxhighlight>
the cheeky cellular automaton solution
<langsyntaxhighlight Ursalalang="ursala">#import std
#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/~& :/&</langsyntaxhighlight>
an example of each (converting from booleans to characters)
<langsyntaxhighlight Ursalalang="ursala">#show+
 
examples = mat0 ~&?(`*!,` !)*** <sierpinski3,triangle4></langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll;">
Line 5,439 ⟶ 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}}<langsyntaxhighlight lang="vb">Sub sierpinski(n As Integer)
Dim lim As Integer: lim = 2 ^ n - 1
For y = lim To 0 Step -1
Line 5,456 ⟶ 5,731:
sierpinski i
Next i
End Sub</langsyntaxhighlight>{{out}}
<pre style="font-size: 4px">
#
Line 5,584 ⟶ 5,859:
=={{header|VBScript}}==
{{trans|PowerShell}}
<syntaxhighlight lang="vb">
<lang vb>
Sub triangle(o)
n = 2 ^ o
Line 5,612 ⟶ 5,887:
 
triangle(4)
</syntaxhighlight>
</lang>
 
=={{header|Vedit macro language}}==
Line 5,619 ⟶ 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.
<langsyntaxhighlight lang="vedit">#3 = 16 // size (height) of the triangle
Buf_Switch(Buf_Free) // Open a new buffer for output
Ins_Char(' ', COUNT, #3*2+2) // fill first line with spaces
Line 5,636 ⟶ 5,911:
Ins_Char(#21, OVERWRITE)
Ins_Char('*', OVERWRITE)
}</langsyntaxhighlight>
 
===Recursive===
{{trans|BASIC}}
Vedit macro language does not have recursive functions, so some pushing and popping is needed to implement recursion.
<langsyntaxhighlight lang="vedit">#1 = 1 // x
#2 = 1 // y
#3 = 16 // length (height of the triangle / 2)
Line 5,669 ⟶ 5,944:
Num_Pop(1,4)
}
Return</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|C}}
<langsyntaxhighlight ecmascriptlang="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()
}</langsyntaxhighlight>
 
{{out}}
Line 5,702 ⟶ 5,977:
=={{header|X86 Assembly}}==
Translation of XPL0. Assemble with tasm, tlink /t
<langsyntaxhighlight lang="asm"> .model tiny
.code
.486
Line 5,729 ⟶ 6,004:
loop tri10 ;next I
ret
end start</langsyntaxhighlight>
 
{{out}}
Line 5,752 ⟶ 6,027:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code ChOut=8, CrLf=9;
def Order=4, Size=1<<Order;
int S1, S2, I;
Line 5,764 ⟶ 6,039:
S2:= S2 xor S1>>1;
];
]</langsyntaxhighlight>
 
{{out}}
Line 5,788 ⟶ 6,063:
=={{header|Yabasic}}==
{{trans|Phix}}
<langsyntaxhighlight Yabasiclang="yabasic">sub rep$(n, c$)
local i, s$
Line 5,813 ⟶ 6,088:
sierpinski(i)
next
</syntaxhighlight>
</lang>
 
=={{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}}
<langsyntaxhighlight lang="zkl">level,d := 3,T("*");
foreach n in (level + 1){
sp:=" "*(2).pow(n);
Line 5,823 ⟶ 6,158:
d.apply(fcn(a){ String(a," ",a) }));
}
d.concat("\n").println();</langsyntaxhighlight>
{{out}}
<pre>
6

edits