One-line Sierpinski Triangle

Discussions related to mathematics, numerical methods, graph plotting etc.
Richard Russell
Posts: 457
Joined: Tue 18 Jun 2024, 09:32

One-line Sierpinski Triangle

Post by Richard Russell »

BASIC one-liners are divisive, but here's a one-line program to draw the Sierpinski triangle. It uses array slicing so needs BB4W or BBCSDL:

Code: Select all

DIM v(2,1),p(1):v()=320,500,640:REPEAT p()=p()/2+v(RND(3)-1,0TO):PLOT p(0),p(1):UNTIL 0
It took more than forty years to get around to adding array slicing to BBC BASIC, but now I find it invaluable and use it all the time.

sierpinski.png
You do not have the required permissions to view the files attached to this post.
Richard Russell
Posts: 457
Joined: Tue 18 Jun 2024, 09:32

Re: One-line Sierpinski Triangle

Post by Richard Russell »

Richard Russell wrote: Wed 20 Aug 2025, 15:33

Code: Select all

DIM v(2,1),p(1):v()=320,500,640:REPEAT p()=p()/2+v(RND(3)-1,0TO):PLOT p(0),p(1):UNTIL 0
Here's a breakdown of how it works:

Code: Select all

DIM v(2,1),p(1) : REM v() holds the coordinates of the three vertices, p() the current point
v()=320,500,640 : REM Initialise v() to the three vertices: (320,500), (640,0) and (0,0)
REPEAT          : REM Start the loop
p()=p()/2+v(RND(3)-1,0TO) : REM Move the current point half way to a randomly-chosen vertex
PLOT p(0),p(1)  : REM Plot the current point
UNTIL 0         : REM Loop for ever
Richard Russell
Posts: 457
Joined: Tue 18 Jun 2024, 09:32

Re: One-line Sierpinski Triangle

Post by Richard Russell »

According to the Profiler, about one-quarter of the time is spent calculating the coordinates and three-quarters plotting the points (BBCSDL):

Code: Select all

Time spent profiling: 11.528 seconds.

         0:                   DIM v(2,1),p(1):v()=320,500,640
         0:                   REPEAT
      2788:    24.18          p()=p()/2+v(RND(3)-1,0TO)
      8624:    74.81          PLOT p(0),p(1)
       116:     1.01          UNTIL 0

         0:                   Libraries and immediate mode
As is to be expected, plotting in BB4W is much slower, and takes up 98% of the time:

Code: Select all

         0:               DIM v(2,1),p(1):v()=320,500,640
         0:               REPEAT
       198:     1.98      p()=p()/2+v(RND(3)-1,0TO)
      9776:    97.76      PLOT p(0),p(1)
        26:     0.26      UNTIL 0