Chaos game: Difference between revisions

12,864 bytes added ,  12 days ago
m (→‎{{header|F Sharp}}: Regularize header markup to recommended on category page)
 
(27 intermediate revisions by 14 users not shown)
Line 15:
* [http://www.geoastro.de/ChaosSpiel/ChaosEnglish.html The Game of Chaos]
<br><br>
 
=={{header|8086 Assembly}}==
{{trans|BASIC}}
Line 21 ⟶ 20:
This program will run on a PC with CGA-compatible graphics. It will keep running until a key is pressed.
 
<langsyntaxhighlight lang="asm"> cpu 8086
bits 16
vmode: equ 0Fh ; Get current video mode
Line 142 ⟶ 141:
xchg bx,bp ; Restore the registers
xchg cx,di
ret</langsyntaxhighlight>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC Main()
INT x,w=[220],h=[190]
BYTE y,i,CH=$02FC,COLOR1=$02C5,COLOR2=$02C6
Line 172 ⟶ 170:
OD
CH=$FF
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Chaos_game.png Screenshot from Atari 8-bit computer]
=={{header|Amazing Hopper}}==
{{trans|BASIC256}}
<p>Considerar que Hopper no usa modos gráficos, y solo imprime el caracter ascii 219 achicando el tamaño de caracteres de la terminal, dado la ilusión de un modo gráfico "arcaico".</p>
<syntaxhighlight lang="amazing hopper">
/* Chaos game - JAMBO hopper */
 
#include <jambo.h>
 
#define LIMITE 50000
 
Main
ancho = 700, alto = 150
x=0,y=0,color=0
vertice=0,
c=0, Let( c := Utf8(Chr(219)))
Let(x := Int(Rand(ancho)))
Let(y := Int(Rand(alto)))
 
mid ancho=0, Let( mid ancho:= Div(ancho,2))
 
Cls
i=LIMITE
Void(pixeles)
 
Loop
Ceil(Rand(3)), On gosub( EQ1, EQ2, EQ3 )
 
Set( Int(y), Int(x), color),Apndrow(pixeles)
--i
Back if (i) is not zero
 
Canvas-term
Cls
i=1
Iterator(++i, Leq(i,LIMITE), Colorfore([i,3]Get(pixeles)), \
Locate( [i,1]Get(pixeles), [i,2]Get(pixeles) ), Print(c) )
Pause
 
End
Subrutines
EQ1:
Let(x := Div(x, 2))
Let(y := Div(y, 2))
Let(color:=9), Return
 
EQ2:
Let(x := Add( mid ancho, Div(Sub(mid ancho, x), 2) ) )
Let(y := Sub( alto, Div( Sub(alto, y), 2 )))
Let(color:=10), Return
EQ3:
Let(x := Sub(ancho, Div( Sub(ancho, x), 2)))
Let(y := Div(y, 2))
Let(color:=4), Return
 
</syntaxhighlight>
{{out}}
[[File:Chaos Game - salida_juego.png]]
 
=={{header|BASIC}}==
This should require minimal adaptation to work with any of the older Microsoft-style BASICs. Users of other dialects will need to replace lines <tt>10</tt> and <tt>150</tt> with the appropriate statements to select a graphics output mode (if necessary) and to plot a pixel at <tt>x,y</tt> in colour <tt>v</tt>; they should also add <tt>LET</tt> throughout and <tt>170 END</tt> if their dialects require those things.
<langsyntaxhighlight lang="basic">10 SCREEN 1
20 X = INT(RND(0) * 200)
30 Y = INT(RND(0) * 173)
Line 193 ⟶ 248:
140 Y = Y/2
150 PSET X,Y,V
160 NEXT I</langsyntaxhighlight>
 
==={{header|Applesoft BASIC}}===
Adapted from the code given above.
<langsyntaxhighlight lang="basic">10 HGR2
20 X = INT(RND(1) * 200)
30 Y = INT(RND(1) * 173)
Line 212 ⟶ 268:
150 HCOLOR=V+4
160 HPLOT X,Y
170 NEXT I</langsyntaxhighlight>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">#Chaos game
<lang BASIC256>
#Chaos game
 
ancho = 500 : alto = 300
Line 247 ⟶ 302:
Refresh
ImgSave "chaos_game.jpg", "jpg"
End</syntaxhighlight>
End
 
</lang>
==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
{{works with|BASICA}}
<syntaxhighlight lang="qbasic">100 REM Chaos game
110 CLS
120 SCREEN 7 '320x200 EGA Color
130 X = INT(RND(1) * 200)
140 Y = INT(RND(1) * 173)
150 FOR I=1 TO 20000
160 V = INT(RND(1) * 3) + 1
170 ON V GOTO 180,210,240
180 X = X/2
190 Y = Y/2
200 GOTO 260
210 X = 100 + (100-X)/2
220 Y = 173 - (173-Y)/2
230 GOTO 260
240 X = 200 - (200-X)/2
250 Y = Y/2
260 PSET(X,Y),V
270 NEXT I
280 END</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 PROGRAM "ChaosGam.bas"
110 RANDOMIZE
120 GRAPHICS HIRES 4
130 LET X=RND(800):LET Y=RND(600)
140 FOR I=1 TO 20000
150 LET VERTEX=RND(3)
160 SELECT CASE VERTEX
170 CASE 0
180 LET X=X/2
190 LET Y=Y/2
200 CASE 1
210 LET X=400+(400-X)/2
220 LET Y=600-(600-Y)/2
230 CASE 2
240 LET X=800-(800-X)/2
250 LET Y=Y/2
260 END SELECT
270 SET INK VERTEX+1
280 PLOT X,Y
290 NEXT</syntaxhighlight>
 
==={{header|Locomotive Basic}}===
Adapted from the generic BASIC version. In [https://benchmarko.github.io/CPCBasic/cpcbasic.html CPCBasic] this program completes in less than a second. But on a real CPC (or equivalent emulator), the same program takes over six minutes to run. So using CPCBasic is strongly advised. On CPCBasic, one can also use "mode 3" instead of mode 1 in line 10 and increase iterations to e.g. 2000000 in line 40, resulting in a higher-resolution image.
<langsyntaxhighlight lang="locobasic">10 mode 1:randomize time:defint a-z
20 x = 640 * rnd
30 y = 400 * rnd
Line 267 ⟶ 366:
140 y = y/2
150 plot x,y,v
160 next i</langsyntaxhighlight>
 
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
<syntaxhighlight lang="qbasic">100 REM Chaos game
110 CLS
120 SCREEN 2
130 X = INT(RND(1) * 256)
140 Y = INT(RND(1) * 192)
150 FOR I=1 TO 20000
160 V = INT(RND(1) * 3) + 1
170 ON V GOTO 180,220,260
180 X = X/2
190 Y = Y/2
200 V = 8 'red
210 GOTO 290
220 X = 128 + (128-X)/2
230 Y = 192 - (192-Y)/2
240 V = 3 'green
250 GOTO 290
260 X = 256 - (256-X)/2
270 Y = Y/2
280 V = 7 'blue
290 PSET(X,Y),V
300 NEXT I
310 END</syntaxhighlight>
 
==={{header|Sinclair ZX81 BASIC}}===
Line 273 ⟶ 397:
 
Note that ZX81 BASIC does not have an explicit computed <code>GOTO</code>; we can, however, actually compute the value of an expression and then <code>GOTO</code> it as a line number.
<langsyntaxhighlight lang="basic"> 10 LET X=RND*46
20 LET Y=RND*40
30 FOR I=1 TO 5000
Line 287 ⟶ 411:
130 LET Y=Y/2
140 PLOT X,42-Y
150 NEXT I</langsyntaxhighlight>
{{out}}
Screenshot [http://www.edmundgriffiths.com/zx81chaosgame.jpg here]. As with most ZX81 graphics, you can obtain the very best results by making it quite small and looking at it from a long way away.
Line 293 ⟶ 417:
==={{header|ZX Spectrum Basic}}===
The final <code>INK</code> statement sets the foreground colour back to black.
<langsyntaxhighlight lang="basic"> 10 LET x=RND*200
20 LET y=RND*173
30 FOR i=1 TO 20000
Line 310 ⟶ 434:
160 PLOT x,y
170 NEXT i
180 INK 0</langsyntaxhighlight>
 
=={{header|C}}==
 
Interactive code which asks the side length of the starting triangle and number of iterations as inputs, a larger number of iterations produces a more accurate approximation of the Sierpinski fractal. Requires the [http://www.cs.colorado.edu/~main/bgi/cs1300/ WinBGIm] library.
 
<syntaxhighlight lang="c">
<lang C>
#include<graphics.h>
#include<stdlib.h>
Line 368 ⟶ 491:
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
 
<langsyntaxhighlight lang="csharp">using System.Diagnostics;
using System.Drawing;
 
Line 402 ⟶ 524:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
This program will generate the Sierpinski Triangle and save it to your hard drive.
<langsyntaxhighlight lang="cpp">
#include <windows.h>
#include <ctime>
Line 555 ⟶ 676:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
{{libheader|opticl}}
<langsyntaxhighlight lang="lisp">(defpackage #:chaos
(:use #:cl
#:opticl))
Line 587 ⟶ 707:
(setf (pixel image (first point) (second point))
(values 255 0 0)))
(write-png-file "chaos.png" image)))</langsyntaxhighlight>
=={{header|Delphi}}==
{{libheader| Winapi.Windows}}
Line 595 ⟶ 715:
{{libheader| Vcl.ExtCtrls}}
{{libheader| System.Generics.Collections}}
<syntaxhighlight lang="delphi">
<lang Delphi>
unit main;
 
Line 715 ⟶ 835:
end;
end;
end.</langsyntaxhighlight>
=={{header|EasyLang}}==
 
[https://easylang.dev/show/#cod=Zc1BCoMwEIXhfU7xL20FO1aKuMhJQhbFKgrVQAiS3L5MkW66GJj5eMwbwztEBhGTncfiEFoRHoI35aSenqHDm4wlPvdX2GaumjPlT+YQWbG0pKAgIgbYwjGRKbrHaUxI0+novZxP1j3xBe2pMjXZLf7CjbuqdlWFmvLTxnwA Run it]
[https://easylang.online/apps/_chaos-game.html Run it]
 
<syntaxhighlight>
<lang>set_color 900
color 900
x[] = [ 0 100 50 ]
y[] = [ 93 937 7 93 ]
x = randomf * 100
y = randomf * 100
for i range= 1 to 100000
move_pen move x y
draw_rect rect 0.3 0.3
h = randomrandint 3
x = (x + x[h]) / 2
y = (y + y[h]) / 2
.
.</lang>
</syntaxhighlight>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">; Chaos game
 
(defun make-array (size)
"Create an empty array with size*size elements."
(setq m-array (make-vector size nil))
(dotimes (i size)
(setf (aref m-array i) (make-vector size 0)))
m-array)
 
(defun chaos-next (p)
"Return the next coordinates."
(let* ((points (list (cons 1 0) (cons -1 0) (cons 0 (sqrt 3))))
(v (elt points (random 3)))
(x (car p))
(y (cdr p))
(x2 (car v))
(y2 (cdr v)))
(setq nx (/ (+ x x2) 2.0))
(setq ny (/ (+ y y2) 2.0))
(cons nx ny)))
 
(defun chaos-lines (arr size)
"Turn array into a string for XPM conversion."
(setq all "")
(dotimes (y size)
(setq line "")
(dotimes (x size)
(setq line (concat line (if (= (elt (elt arr y) x) 1) "*" "."))))
(setq all (concat all "\"" line "\",\n")))
all)
 
(defun chaos-show (arr size)
"Convert size*size array to XPM image and show it."
(insert-image (create-image (concat (format "/* XPM */
static char * chaos[] = {
\"%i %i 2 1\",
\". c #000000\",
\"* c #00ff00\"," size size)
(chaos-lines arr size) "};") 'xpm t)))
 
(defun chaos (size scale max-iter)
"Play the chaos game."
(let ((arr (make-array size))
(p (cons 0 0)))
(dotimes (it max-iter)
(setq p (chaos-next p))
(setq x (round (+ (/ size 2) (* scale (car p)))))
(setq y (round (+ (- size 10) (* -1 scale (cdr p)))))
(setf (elt (elt arr y) x) 1))
(chaos-show arr size)))
 
(chaos 400 180 50000) </syntaxhighlight>
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
open System.Windows.Forms
open System.Drawing
Line 758 ⟶ 933:
f.Paint.Add (fun args -> args.Graphics.DrawImage(bmp, Point(0, 0)))
f.Show()
</syntaxhighlight>
</lang>
=={{header|Forth}}==
{{works with|gforth|0.7.3}}
<br>
<syntaxhighlight lang="forth">#! /usr/bin/gforth
\ Chaos Game
 
require random.fs
 
\ initialize the random number generator with a time-dependent seed
utime drop seed !
 
\ parses a number from a string
: parse-number ( -- n )
s>number? invert throw drop
;
 
 
\ parse the width of the triangle, the number of steps and the output filename from the command-line
 
." width: " next-arg parse-number dup . cr CONSTANT WIDTH
." steps: " next-arg parse-number dup . cr CONSTANT STEPS
." output: " next-arg 2dup type cr 2CONSTANT OUT-FILE
 
 
\ height of the triangle: height = sqrt(3) / 2 * width
WIDTH 0 d>f 3e fsqrt f* 2e f/ fround f>d drop CONSTANT HEIGHT \ height of the triangle: height = sqrt(3) / 2 * width
 
 
\ coordinates of the three corners of the triangle
 
0 CONSTANT X1
0 CONSTANT Y1
WIDTH CONSTANT X2
0 CONSTANT Y2
WIDTH 2 / CONSTANT X3
HEIGHT CONSTANT Y3
 
 
\ minimal and maximal x and y coordinates
 
X1 X2 X3 min min CONSTANT XMIN
X1 X2 X3 max max CONSTANT XMAX
Y1 Y2 Y3 min min CONSTANT YMIN
Y1 Y2 Y3 max max CONSTANT YMAX
 
XMAX XMIN - 1+ CONSTANT XSIZE
YMAX YMIN - 1+ CONSTANT YSIZE
 
 
\ initialize array for all possible points
 
XSIZE YSIZE *
dup CREATE ARR cells allot
ARR swap cells erase
 
 
\ address of the cell corresponding to point (x,y)
: addr? ( x y -- addr )
XSIZE * + cells ARR +
;
 
\ scalar product of the 2-vectors
: sp ( x1 y1 x2 y2 -- n )
swap >r * r> rot * +
;
 
\ is the point (x,y) on the left of the ray from (px,py) to (qx,qy)?
: left? ( px py qx qy x y -- f )
{ px py qx qy x y }
py qy -
qx px -
x px -
y py -
sp 0>=
;
 
\ is the point (x,y) in the triangle?
: in-triangle? ( x y -- f )
{ x y }
X1 Y1 X2 Y2 x y left?
X2 Y2 X3 Y3 x y left?
X3 Y3 X1 Y1 x y left?
and and
;
 
\ generates a random number in [a,b]
: random-in-range ( a b -- n )
over - 1+ random +
;
 
\ generates a random point in the triangle
: random-in-triangle ( -- x y )
0 0
BEGIN
2drop
XMIN XMAX random-in-range
YMIN YMAX random-in-range
2dup in-triangle?
UNTIL
;
 
\ finds the middle of to points (px,py) and (qx,qy)
: middle ( px py qx qy -- x y )
swap -rot
+ 2/ -rot
+ 2/ swap
;
 
\ plays the chaos game for a number of steps
: game ( n -- )
random-in-triangle
rot
0 DO
2dup addr? true swap !
3 random CASE
0 OF X1 Y1 ENDOF
1 OF X2 Y2 ENDOF
2 OF X3 Y3 ENDOF
ENDCASE
middle
LOOP
2drop
;
 
\ writes the result in pbm-format
: write-pbm ( -- )
." P1" cr
XSIZE . YSIZE . cr
YMIN 1- YMAX -DO
XMAX 1+ XMIN DO
i j addr? @ IF 1 . ELSE 0 . THEN
LOOP
cr
1 -LOOP
;
 
\ writes the result to a pbm-file
: to-pbm ( c-addr u -- )
w/o create-file throw ['] write-pbm over outfile-execute close-file throw
;
 
\ play the game and save the result
STEPS game OUT-FILE to-pbm
 
bye</syntaxhighlight>
 
{{out}}
playing a million steps on a triangle with base length 1000:
<tt>./chaos-game.fs 1000 1000000 chao-game.pbm</tt>:]
[https://commons.wikimedia.org/wiki/File:Chaos_Game.png]<br>
=={{header|Fortran}}==
This FORTRAN code creates an output file which can be drawn with gnuplot.
<syntaxhighlight lang="fortran">
<lang Fortran>
PROGRAM CHAOS
IMPLICIT NONE
Line 806 ⟶ 1,130:
END FUNCTION ZAHL
END PROGRAM CHAOS
</syntaxhighlight>
</lang>
Gnuplot Code to draw file:
<syntaxhighlight lang="gnuplot">
<lang Gnuplot>
set terminal jpeg enhanced size 1600,960
set output 'chaos.jpg'
Line 814 ⟶ 1,138:
set style line 1 lc rgb '#0060ad' lt 1 lw 3 pt 7 ps 0.3
plot 'aus.csv' using 1:3 with points ls 1 notitle
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
{{trans|BASIC256}}
<langsyntaxhighlight lang="freebasic">
' Chaos game
Const ancho = 320, alto = 240
Line 848 ⟶ 1,171:
Sleep
End
</syntaxhighlight>
</lang>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Chaos_game}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution'''
 
[[File:Fōrmulæ - Chaos game 04.png]]
 
'''Test case. Sierpiński triangle'''
 
[[File:Fōrmulæ - Chaos game 05.png]]
 
[[File:Fōrmulæ - Chaos game 06.png]]
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
void local fn DoIt
long w = 460, h = 400, i, x = rnd(w), y = rnd(h)
for i = 1 to 50000
select ( rnd(3)-1 )
case 1
x = w/2+(w/2-x)/2
y = h-(h-y)/2
pen ,fn ColorRed
case 2
x = w-(w-x)/2
y = y/2
pen ,fn ColorGreen
case else
x = x/2
y = y/2
pen ,fn ColorBlue
end select
line x-0.5,y-0.5,x+0.5,y+0.5
next
end fn
 
window 1, @"Chaos Game", (0,0,460,400)
WindowSetBackgroundColor( 1, fn ColorWhite )
 
fn DoIt
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
HandleEvents
In '''[https://formulae.org/?example=Chaos_game this]''' page you can see the program(s) related to this task and their results.
</syntaxhighlight>
[[file:Chaos game FB.png]]
 
=={{header|GML}}==
Line 863 ⟶ 1,223:
 
'''"Game" Object Create Event:'''
<langsyntaxhighlight GMLlang="gml">offset = 32; //Distance from triangle vertices to edges of window
 
//triangle vertex coordinates
Line 893 ⟶ 1,253:
step_count = 0;
interval = 1; //Number of frames between each step. 1 = no delay
alarm[0] = interval;</langsyntaxhighlight>
 
 
'''"Game" Object Step Event:'''
<langsyntaxhighlight GMLlang="gml">if(step and step_count < max_iterations) //Wait for alarm to finish, or stop completely
{ // if the desired number of iterations is hit
vertex = choose(1, 2, 3);
Line 930 ⟶ 1,290:
step_count++;
}</langsyntaxhighlight>
 
 
'''"Game" Object Draw Event:'''
<langsyntaxhighlight GMLlang="gml">if(step_count < max_iterations)
{
draw_triangle(x1, y1, x2, y2, x3, y3, true);
draw_circle(px, py, 1, false);
draw_line(px, py, vx, vy);
}</langsyntaxhighlight>
 
 
'''"Game" Object Alarm 0:'''
<langsyntaxhighlight GMLlang="gml">step = true;
alarm[0] = interval;</langsyntaxhighlight>
 
 
'''"Point" Object Draw Event:'''
<langsyntaxhighlight GMLlang="gml">draw_circle(x, y, 5, false);</langsyntaxhighlight>
 
=={{header|Gnuplot}}==
{{trans|PARI/GP}}
Line 955 ⟶ 1,314:
[[File:ChGS3Gnu1.png|right|thumb|Output ChGS3Gnu1.png]]
 
<langsyntaxhighlight lang="gnuplot">
## Chaos Game (Sierpinski triangle) 2/16/17 aev
reset
Line 983 ⟶ 1,342:
set output
unset print
</syntaxhighlight>
</lang>
{{Output}}
<pre>
File: ChGS3Gnu1.png
</pre>
 
=={{header|Go}}==
This writes a simple GIF animation of the method.
<langsyntaxhighlight Golang="go">package main
 
import (
Line 1,095 ⟶ 1,453:
}
return err
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
 
{{libheader|JavaFX}}
 
<langsyntaxhighlight Groovylang="groovy">import javafx.animation.AnimationTimer
import javafx.application.Application
import javafx.scene.Scene
Line 1,169 ⟶ 1,526:
launch(ChaosGame)
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">import Control.Monad (replicateM)
import Control.Monad.Random (fromList)
 
Line 1,182 ⟶ 1,538:
gameOfChaos :: MonadRandom m => Int -> Transformations -> Point -> m [Point]
gameOfChaos n transformations x = iterateA (fromList transformations) x
where iterateA f x = scanr ($) x <$> replicateM n f</langsyntaxhighlight>
 
Some transformations:
 
<langsyntaxhighlight lang="haskell">-- the Sierpinsky`s triangle
triangle = [ (mid (0, 0), 1)
, (mid (1, 0), 1)
Line 1,202 ⟶ 1,558:
dragon = [(f1, 1), (f2, 1)]
where f1 (x,y) = (0.5*x - 0.5*y, 0.5*x + 0.5*y)
f2 (x,y) = (-0.5*x + 0.5*y+1, -0.5*x - 0.5*y)</langsyntaxhighlight>
 
Drawing the result:
<langsyntaxhighlight lang="haskell">import Control.Monad.Random (getRandomR)
import Graphics.Gloss
 
Line 1,213 ⟶ 1,569:
display window white $ foldMap point pts
where window = InWindow "Game of Chaos" (400,400) (0,0)
point (x,y) = translate (100*x) (100*y) $ circle 0.02 </langsyntaxhighlight>
 
=={{header|J}}==
[[File:j_chaos_game.png|300px|thumb|right]]
<syntaxhighlight lang="j">
<lang j>
Note 'plan, Working in complex plane'
Make an equilateral triangle.
Line 1,251 ⟶ 1,606:
 
'marker'plot NEW_POINTS
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
[[File:chaos_game.png|300px|thumb|right]]
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.awt.*;
import java.awt.event.*;
import java.util.*;
Line 1,344 ⟶ 1,698:
});
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Plots the fractal on an HTML <tt>canvas</tt> element.
<langsyntaxhighlight lang="javascript"><html>
 
<head>
Line 1,400 ⟶ 1,753:
</body>
 
</html></langsyntaxhighlight>
 
=={{header|Julia}}==
Run in REPL.
<langsyntaxhighlight lang="julia">using Luxor
 
function chaos()
Line 1,434 ⟶ 1,786:
finish()
preview()
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">//Version 1.1.51
 
import java.awt.*
Line 1,517 ⟶ 1,868:
}
}
}</langsyntaxhighlight>
 
{{output}}
Line 1,523 ⟶ 1,874:
Same as Java entry
</pre>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to chaosgame :sidelength :iterations
make "width :sidelength
make "height (:sidelength/2 * sqrt 3)
Line 1,553 ⟶ 1,903:
]
hideturtle
end</langsyntaxhighlight>
 
=={{header|Lua}}==
Needs L&Ouml;VE 2d Engine
<syntaxhighlight lang="lua">
<lang Lua>
math.randomseed( os.time() )
colors, orig = { { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } }, {}
Line 1,598 ⟶ 1,947:
love.graphics.draw( canvas )
end
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
{{trans|Locomotive Basic}}
Old style programming (GOTO, ON GOTO) inside Module. Export bitmap to Clipboard.
 
 
<syntaxhighlight lang="m2000 interpreter">
Module Chaos {
01 Read Ox as integer, Oy as Integer
02 def Screen$
05 cls 0,0 // black background, row for split screen
10 def integer x,y,i,v
20 x = 640 * rnd
30 y = 400 * rnd
40 for i=1 to 20000
50 v = rnd * 2 + 1
60 on v goto 70,100,130
70 x = x/2
80 y = y/2
90 goto 150
100 x = 320 + (320-x)/2
110 y = 400 - (400-y)/2
120 goto 150
130 x = 640 - (640-x)/2
140 y = y/2
150 pset v*2, x*twipsX+Ox,y*twipsY+Oy
160 next i
170 Move Ox, Oy
180 Copy 640*twipsX, 400*twipsY to Screen$
190 Clipboard Screen$
}
Call Chaos 3000, 3000
</syntaxhighlight>
{{output}}
[[File:Chaosgame.png|thumb]]
 
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">chaosGame := proc(numPoints)
local points, i;
randomize();
Line 1,618 ⟶ 2,003:
plots:-display( seq([plots:-display([seq(point(points[i]), i = 1..j)])], j = 1..numelems(points) ), insequence=true);
end use;
end proc:</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">points = 5000;
a = {0, 0};
b = {1, 0};
Line 1,630 ⟶ 2,014:
If[t == 0, d = Mean[{a, d}],
If[t == 1, d = Mean[{b, d}], d = Mean[{c, d}]]]; AppendTo[S, d]]
Graphics[Point[S]]</langsyntaxhighlight>
 
=={{header|Nim}}==
==={{header|Using a game library}}===
{{libheader|rapid}}
The "rapid" library is no longer maintained and this program fails to compile with last available version.
<langsyntaxhighlight lang="nim">import random
 
import rapid/gfx
Line 1,672 ⟶ 2,055:
ctx.noTexture()
update step:
discard</langsyntaxhighlight>
 
==={{header|Using SDL}}===
{{libheader|SDL2}}
<langsyntaxhighlight lang="nim">## needs sdl2 ("nimble install sdl2")
 
import sdl2, random
Line 1,732 ⟶ 2,115:
 
destroy render
destroy window</langsyntaxhighlight>
 
==={{header|Writing result into an image}}===
{{libheader|imageman}}
 
<langsyntaxhighlight Nimlang="nim">import math
import random
 
Line 1,813 ⟶ 2,196:
p = ((p.x + T[idx].x) / 2, (p.y + T[idx].y) / 2)
 
image.savePNG("chaos_game.png", compression = 9)</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Note: Find plotmat() here on RosettaCode Wiki.
{{Works with|PARI/GP|2.9.1 and above}}
[[File:SierpTri1.png|right|thumb|Output SierpTri1.png]]
<langsyntaxhighlight lang="parigp">
\\ Chaos Game (Sierpinski triangle) 2/15/17 aev
pChaosGameS3(size,lim)={
Line 1,835 ⟶ 2,217:
\\ Test:
pChaosGameS3(600,30000); \\ SierpTri1.png
</langsyntaxhighlight>
{{Output}}
<pre>
Line 1,842 ⟶ 2,224:
time = 751 ms.
</pre>
 
=={{header|Pascal}}==
<syntaxhighlight lang="pascal">
<lang Pascal>
program ChaosGame;
 
Line 1,922 ⟶ 2,303:
end.
 
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use Imager;
 
my $width = 1000;
Line 1,962 ⟶ 2,342:
}
 
$img->write(file => 'chaos_game_triangle.png');</langsyntaxhighlight>
 
=={{header|Phix}}==
Implements five of the fractals on the wikipedia page.
Line 1,969 ⟶ 2,348:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/chaos.htm here]. Press space to cycle through the five fractals.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Chaos_game.exw
Line 2,065 ⟶ 2,444:
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
 
=={{header|Plain English}}==
<langsyntaxhighlight lang="plainenglish">To run:
Start up.
Initialize our reference points.
Line 2,109 ⟶ 2,487:
If the number is 1, put the top spot into the reference spot.
If the number is 2, put the right spot into the reference spot.
If the number is 3, put the left spot into the reference spot.</langsyntaxhighlight>
{{out}}
[https://commons.wikimedia.org/wiki/File:Chaos-game.png]
 
=={{header|Processing}}==
<langsyntaxhighlight lang="java">size(300, 260);
 
background(#ffffff); // white
Line 2,142 ⟶ 2,519:
}
set(x, height-y, colour);
}</langsyntaxhighlight>
 
==={{header|Processing Python mode}}===
 
<langsyntaxhighlight lang="python">from __future__ import division
 
size(300, 260)
Line 2,170 ⟶ 2,547:
colour = color(0, 0, 255) # blue
 
set(x, height - y, colour)</langsyntaxhighlight>
 
=={{header|Python}}==
 
<syntaxhighlight lang="python">
<lang Python>
import argparse
import random
Line 2,291 ⟶ 2,667:
main(arg_parser.parse_args())
 
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="Quackery"> [ $ "turtleduck.qky" loadfile ] now!
 
[ 2 3 circle ] is dot ( --> )
 
[ 1 fly
-1 4 turn
1 fly
1 4 turn ] is toxy ( n n --> )
 
[ swap 2dup toxy
dot
1 2 turn
toxy
1 2 turn ] is plot ( n n --> )
 
[ 200 random
346 random
over 346 *
over 200 * < if
[ dip [ 400 + ]
692 swap - ] ] is intriangle ( --> n n )
 
[ 3 random
[ table
[ 2 /
dip [ 2 / ] ]
[ 2 /
dip [ 800 + 2 / ] ]
[ 692 + 2 /
dip [ 400 + 2 / ] ] ]
do ] is tovertex ( n n --> )
 
turtle
0 frames
-400 1 fly
1 4 turn
340 1 fly
-1 4 turn
intriangle
10000 times
[ i^ 100 mod 0= if frame
2dup plot
tovertex ]
2drop
1 frames</syntaxhighlight>
 
{{out}}
 
[[File:Quackery chaos game.png|thumb|center]]
 
=={{header|R}}==
Line 2,298 ⟶ 2,726:
{{Works with|R|3.3.1 and above}}
[[File:SierpTriR1.png|right|thumb|Output SierpTriR1.png]]
<syntaxhighlight lang="r">
<lang r>
# Chaos Game (Sierpinski triangle) 2/15/17 aev
# pChaosGameS3(size, lim, clr, fn, ttl)
Line 2,322 ⟶ 2,750:
}
pChaosGameS3(600, 30000, "red", "SierpTriR1", "Sierpinski triangle")
</langsyntaxhighlight>
{{Output}}
<pre>
Line 2,331 ⟶ 2,759:
</pre>
 
'''Alternative code:'''
 
<syntaxhighlight lang="r">
pta = c(1,2)
ptb = c(4,2)
ptc = c(2.5,4)
spt = c(1,2)
 
plot(t(data.frame(pta,ptb,ptc)),
xlab= "", ylab = "", pch = 19, asp =1,
xaxt='n',yaxt='n', ann=FALSE,frame.plot=FALSE)
points(x = spt[1], y = spt[2], col = "blue", pch = 19)
 
ittt = 100000
ptcex = .2
for (i in 1:ittt) {
d = sample(1:6,1,TRUE)
if (d == 1 | d == 2) {
pta1 = spt + ((pta-spt)/2)
points(pta1[1],pta1[2], col = "red", pch = 19, cex = ptcex)
spt=pta1
}
if (d == 3 | d == 4) {
ptb1 = spt + (ptb-spt)/2
points(ptb1[1],ptb1[2], col = "red", pch = 19, cex = ptcex)
spt=ptb1
}
if (d == 5 | d == 6) {
ptc1 = spt + (ptc-spt)/2
points(ptc1[1],ptc1[2], col = "red", pch = 19, cex = ptcex)
spt=ptc1
}
}
</syntaxhighlight>
=={{header|Racket}}==
 
{{trans|Haskell}}
 
<langsyntaxhighlight lang="racket">#lang racket
 
(require 2htdp/image)
Line 2,384 ⟶ 2,846:
(draw-triangle)
(draw-fern)
(draw-dragon)</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2018.10}}
 
<syntaxhighlight lang="raku" perl6line>use Image::PNG::Portable;
 
my ($w, $h) = (640, 640);
Line 2,407 ⟶ 2,868:
}
 
$png.write: 'Chaos-game-perl6.png';</langsyntaxhighlight>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX pgm draws a Sierpinski triangle by running the chaos game with a million points*/
parse value scrsize() with sd sw . /*obtain the depth and width of screen.*/
sw= sw - 2 /*adjust the screen width down by two. */
Line 2,435 ⟶ 2,895:
/* [↑] strip trailing blanks (output).*/
say strip(_, 'T') /*display one row (line) of the image. */
end /*row*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
 
This REXX program makes use of &nbsp; '''SCRSIZE''' &nbsp; REXX program (or
Line 2,650 ⟶ 3,110:
</pre>
</b>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Chaos game
 
Line 2,712 ⟶ 3,171:
}
label1 {setpicture(p1) show()}
</syntaxhighlight>
</lang>
* [https://lh3.googleusercontent.com/-xqBO5MB8fpc/Wg05SvwaF9I/AAAAAAAABDA/UGI2goKdDoAR6nbbGZF0YcuwGG6tancvACLcBGAs/s1600/CalmoSoftChaos.jpg Chaos Game (image)]
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">x = int(rnd(0) * 200)
y = int(rnd(0) * 173)
graphic #g, 200,200
Line 2,736 ⟶ 3,194:
#g set(x,y)
next
render #g</langsyntaxhighlight>
 
=={{header|Rust}}==
Dependencies: image, rand
<langsyntaxhighlight lang="rust">
extern crate image;
extern crate rand;
Line 2,783 ⟶ 3,240:
imgbuf.save("fractal.png").unwrap();
}
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
===Java Swing Interoperability===
<langsyntaxhighlight Scalalang="scala">import javax.swing._
import java.awt._
import java.awt.event.ActionEvent
Line 2,855 ⟶ 3,311:
)
 
}</langsyntaxhighlight>
 
=={{header|Scilab}}==
This script uses complex numbers to represent (x,y) coordinates: real part as x position, and imaginary part as y position.
<syntaxhighlight lang="text">//Input
n_sides = 3;
side_length = 1;
Line 2,903 ⟶ 3,358:
plot2d(real(points),imag(points),0)
plot2d(real(vertices),imag(vertices),-3);
set(gca(),'isoview','on');</langsyntaxhighlight>
{{out}}
It outputs a graphic window and prints on the console the time elapsed during iterations.
<pre>Time: 1.0424433s.</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">require('Imager')
 
var width = 600
Line 2,943 ⟶ 3,397:
}
 
img.write(file => 'chaos_game.png')</langsyntaxhighlight>
Output image: [https://github.com/trizen/rc/blob/master/img/chaos-game-sidef.png Chaos game]
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">BEGIN
INTEGER U, COLUMNS, LINES;
COLUMNS := 40;
Line 2,986 ⟶ 3,439:
END;
END
</syntaxhighlight>
</lang>
{{in}}
<pre>
Line 3,034 ⟶ 3,487:
XXX
</pre>
=={{header|Uiua}}==
<syntaxhighlight lang="Uiua">
Dim ← 500
Points ← [[50 ⌊÷2Dim] [-50Dim 50] [-50Dim -50Dim]]
# Uncomment to try different square or pentagonal references.
# Points ← [[50 50] [-50Dim 50] [50 -50Dim][-50Dim -50Dim]]
# Points ← [[50 ⌊÷2Dim] [⌊×0.4Dim 50] [⌊×0.4Dim -50Dim] [-50Dim 120] [-50Dim -120Dim]]
Colours ← [[1 0 0] [0 1 0] [0 0 1] [1 1 0] [1 0 1] [0 1 1]]
Rand ← ⌊×⚂
 
↯Dim_Dim_3 0
∧(⍜(⊡|[1 1 1]◌))Points
⊟Rand Dim Rand Dim
⍥(
Rand⧻Points
# Set next point and colour based on target.
⊃(⌊÷2+⊡:Points|⊙◌⊡:Colours)
⟜⍜⊡◌⊙:
)10000
# Uncomment to save image.
# &fwa "UiuaChaosGameSerpinski.png" &ime "png"
 
</syntaxhighlight>
{{out}}
[[File:UiuaChaosGameSerpinski.png|thumb|center|Render using colours associated with each target point.]]
 
=={{header|Wren}}==
Line 3,040 ⟶ 3,519:
{{libheader|Wren-dynamic}}
{{libheader|Wren-seq}}
<langsyntaxhighlight ecmascriptlang="wren">import "dome" for Window
import "graphics" for Canvas, Color
import "math" for Point
Line 3,101 ⟶ 3,580:
}
 
var Game = ChaosGame.new(640, 640)</langsyntaxhighlight>
 
=={{header|X86 Assembly}}==
Sixty bytes handles it.
<langsyntaxhighlight lang="asm"> 1 ;Assemble with: tasm, tlink /t
2 0000 .model tiny
3 0000 .code
Line 3,142 ⟶ 3,621:
36 0130 0140 002B 0255 Tx dw 320, 320-277, 320+277 ;equilateral triangle
37 0136 0000 01DF 01DF Ty dw 0, 479, 479
38 end start</langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">int Tx, Ty, X, Y, R;
[SetVid($12); \640x480x4 graphics
Tx:= [320, 320-277, 320+277]; \equilateral triangle
Line 3,157 ⟶ 3,635:
until KeyHit;
SetVid($03); \restore normal text mode
]</langsyntaxhighlight>
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">width = 640 : height = 480
open window width, height
window origin "lb"
Line 3,181 ⟶ 3,658:
color 255 * (vertex = 0), 255 * (vertex = 1), 255 * (vertex = 2)
dot x, y
next</langsyntaxhighlight>
 
=={{header|Z80 Assembly}}==
{{trans|BASIC}}
Line 3,190 ⟶ 3,666:
space key.
 
<langsyntaxhighlight lang="z80">VREG: equ 99h ; VDP register port
VR0: equ 0F3DFh ; Copy of VDP R0 in memory
VR1: equ 0F3E0h ; Copy of VDP R1 in memory
Line 3,359 ⟶ 3,835:
ld e,a ; -> C
exx
ret</langsyntaxhighlight>
 
 
=={{header|zkl}}==
This is a half assed animated process - a bunch of pixels are drawn every couple of seconds and the pixmap written [to the file system]. So, if you open the output file ("chaosGame.jpg") it will [auto] update and show the progression of the image.
Line 3,368 ⟶ 3,842:
{{trans|Java}}
[[File:ChaosGame.zkl.jpg|240px|thumb|right]]
<langsyntaxhighlight lang="zkl">w,h:=640,640;
bitmap:=PPM(w,h,0xFF|FF|FF); // White background
colors:=T(0xFF|00|00,0x00|FF|00,0x00|00|FF); // red,green,blue
Line 3,395 ⟶ 3,869:
 
done.wait(); // don't exit until thread is done
println("Done");</langsyntaxhighlight>
2,120

edits