Brownian tree: Difference between revisions

m
m (syntax highlighting fixup automation)
 
(18 intermediate revisions by 8 users not shown)
Line 1:
[[Category:Raster graphics operations]]
[[Category:Geometry]]
{{Wikipedia|Brownian_tree}}
{{task|Fractals}}
[[Category:Raster graphics operations]]
[[File:Brownian_tree.jpg|450px||right]]
 
Line 16 ⟶ 17:
 
<br>Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape. <br><br>
 
=={{header|Action!}}==
Calculations on a real Atari 8-bit computer take quite long time. It is recommended to use an emulator capable with increasing speed of Atari CPU.
<syntaxhighlight lang=Action"action!">BYTE FUNC CheckNeighbors(CARD x BYTE y)
IF Locate(x-1,y-1)=1 THEN RETURN (1) FI
IF Locate(x,y-1)=1 THEN RETURN (1) FI
Line 111:
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Brownian_tree.png Screenshot from Atari 8-bit computer]
 
=={{header|Ada}}==
{{libheader|SDLAda}}
<syntaxhighlight lang=Ada"ada">with Ada.Numerics.Discrete_Random;
 
with SDL.Video.Windows.Makers;
Line 239 ⟶ 238:
SDL.Finalise;
end Brownian_Tree;</syntaxhighlight>
 
=={{header|Applesoft BASIC}}==
Uses XDRAW to plot to Hi-res GRaphics, in fullscreen [POKE 49234,0] 280 x 192, effectively 140 x 192 because colors stretch over two pixels, using a single pixel shape. The POKEs create one shape in a shape table starting at address 768 and point addresses 232 and 233 to this address. Address 234 is the collision counter which is used to detect if the randomly placed seed has hit anything and if the moving seed has collided with the tree. Plotting the seed creates an animation effect of the seed moving around in it's Brownian way.<syntaxhighlight lang="applesoftbasic">0GOSUB2:FORQ=0TOTSTEP0:X=A:Y=B:FORO=0TOTSTEP0:XDRAWTATX,Y:X=INT(RND(T)*J)*Z:Y=INT(RND(T)*H):XDRAWTATX,Y:O=PEEK(C)>0:NEXTO:FORP=0TOTSTEP0:A=X:B=Y:R=INT(RND(T)*E):X=X+X(R):Y=Y+Y(R):IFX<0ORX>MORY<0ORY>NTHENNEXTQ
1 XDRAW T AT X,Y:P = NOT PEEK (C): XDRAW T AT A,B: NEXT P: XDRAW T AT X,Y:Q = A = 0 OR A = M OR B = 0 OR B = N: NEXT Q: END
2 T = 1:Z = 2:E = 8:C = 234
Line 257 ⟶ 255:
14 HGR : POKE 49234,0
15 ROT= 0: SCALE= 1: RETURN</syntaxhighlight>
=={{header|ATS}}==
 
[[File:Brownian tree.2023.05.07.18.48.00.png|thumb|alt=A brownian tree, black on white.]]
[[File:Brownian tree.2023.05.07.18.48.25.png|thumb|alt=A brownian tree, black on white.]]
[[File:Brownian tree.2023.05.07.18.49.01.png|thumb|alt=A brownian tree, black on white.]]
[[File:Brownian tree.2023.05.07.18.49.34.png|thumb|alt=A brownian tree, black on white.]]
 
The program outputs a Portable Arbitrary Map. Shown are some examples for 10000 particles on 300x300 grid.
 
<syntaxhighlight lang="ats">
(* This program pours all the particles onto the square at once, with
one of them as seed, and then lets the particles move around.
 
Compile with
patscc -std=gnu2x -D_GNU_SOURCE -g -O3 -DATS_MEMALLOC_LIBC brownian_tree_task.dats
 
You may need the -D_GNU_SOURCE to get a declaration of the
random(3) function. *)
(*------------------------------------------------------------------*)
 
%{^
#include <stdlib.h>
%}
 
#include "share/atspre_staload.hats"
 
#define NIL list_nil ()
#define :: list_cons
 
extern castfn lint2int : {i : int} lint i -<> int i
implement g1int2int<lintknd,intknd> i = lint2int i
 
extern fn random () : [i : nat] lint i = "mac#random"
extern fn srandom (seed : uint) : void = "mac#srandom"
extern fn atoi (s : string) : int = "mac#atoi"
 
(*------------------------------------------------------------------*)
 
datatype grid_position =
| Wall
| Empty
| Sticky
| Freely_moving
 
fn {}
grid_position_equal
(x : grid_position,
y : grid_position)
:<> bool =
case+ x of
| Wall () => (case+ y of Wall () => true | _ => false)
| Empty () => (case+ y of Empty () => true | _ => false)
| Sticky () => (case+ y of Sticky () => true | _ => false)
| Freely_moving () =>
(case+ y of Freely_moving () => true | _ => false)
 
fn {}
grid_position_notequal
(x : grid_position,
y : grid_position)
:<> bool =
~grid_position_equal (x, y)
 
overload = with grid_position_equal
overload <> with grid_position_notequal
 
(*------------------------------------------------------------------*)
 
abstype container (w : int, h : int) = ptr
 
local
 
typedef _container (w : int, h : int) =
'{M = matrixref (grid_position, w, h),
w = int w,
h = int h}
 
in (* local *)
 
assume container (w, h) = _container (w, h)
 
fn {}
container_make
{w, h : pos}
(w : int w,
h : int h)
: container (w, h) =
'{M = matrixref_make_elt<grid_position> (i2sz w, i2sz h, Empty),
w = w, h = h}
 
fn {}
container_width
{w, h : pos}
(C : container (w, h))
: int w =
C.w
 
fn {}
container_height
{w, h : pos}
(C : container (w, h))
: int h =
C.h
 
fn {}
container_get_at
{w, h : pos}
(C : container (w, h),
x : intBtwe (~1, w),
y : intBtwe (~1, h))
: grid_position =
let
macdef M = C.M
in
if (0 <= x) * (x < C.w) * (0 <= y) * (y < C.h) then
M[x, C.h, y]
else
Wall
end
 
fn
container_set_at
{w, h : pos}
(C : container (w, h),
x : intBtw (0, w),
y : intBtw (0, h),
gpos : grid_position)
: void =
let
macdef M = C.M
in
M[x, C.h, y] := gpos
end
 
end (* local *)
 
overload width with container_width
overload height with container_height
overload [] with container_get_at
overload [] with container_set_at
 
(*------------------------------------------------------------------*)
 
fn
random_direction () :
@(intBtwe (~1, 1), intBtwe (~1, 1)) =
let
val r1 = random ()
val r2 = random ()
val dx : intBtwe (0, 2) = g1i2i (r1 \nmod 3)
and dy : intBtwe (0, 2) = g1i2i (r2 \nmod 3)
in
@(pred dx, pred dy)
end
 
fn
in_sticky_position
{w, h : pos}
(C : container (w, h),
x : intBtw (0, w),
y : intBtw (0, h))
: bool =
(C[pred x, pred y] = Sticky () ||
C[pred x, y] = Sticky () ||
C[pred x, succ y] = Sticky () ||
C[succ x, pred y] = Sticky () ||
C[succ x, y] = Sticky () ||
C[succ x, succ y] = Sticky () ||
C[x, pred y] = Sticky () ||
C[x, succ y] = Sticky ())
 
fn
find_placement_for_another_particle
{w, h : pos}
(C : container (w, h))
: @(intBtw (0, w), intBtw (0, h)) =
let
val w = width C and h = height C
 
fun
loop () : @(intBtw (0, w), intBtw (0, h)) =
let
val r1 = random ()
val r2 = random ()
val x : intBtw (0, w) = g1i2i (r1 \nmod w)
and y : intBtw (0, h) = g1i2i (r2 \nmod h)
in
if C[x, y] <> Empty () then
loop ()
else
@(x, y)
end
in
loop ()
end
 
fn
move_particles
{w, h : pos}
(C : container (w, h),
particles : &List0 @(intBtw (0, w), intBtw (0, h)) >> _)
: void =
let
typedef coords = @(intBtw (0, w), intBtw (0, h))
 
fun
loop {n : nat} .<n>.
(particles : list (coords, n),
new_lst : List0 coords)
: List0 coords =
case+ particles of
| NIL => new_lst
| @(x0, y0) :: tl =>
let
val @(dx, dy) = random_direction ()
val x1 = x0 + dx and y1 = y0 + dy
in
if C[x1, y1] = Empty () then
let
val () = assertloc (0 <= x1)
val () = assertloc (x1 < width C)
val () = assertloc (0 <= y1)
val () = assertloc (y1 < height C)
in
C[x1, y1] := C[x0, y0];
C[x0, y0] := Empty ();
loop (tl, @(x1, y1) :: new_lst)
end
else
(* Our rule is: if there is anything where it WOULD have
moved to, then the particle does not move. *)
loop (tl, @(x0, y0) :: new_lst)
end
in
particles := loop (particles, NIL)
end
 
fn
find_which_particles_are_stuck
{w, h : pos}
(C : container (w, h),
particles : &List0 @(intBtw (0, w), intBtw (0, h)) >> _)
: void =
(* Our rule is: if a particle is next to something that ALREADY was
stuck, then it too is stuck. Otherwise it remains free. *)
let
typedef coords = @(intBtw (0, w), intBtw (0, h))
 
fun
loop {n : nat} .<n>.
(particles : list (coords, n),
new_lst : List0 coords)
: List0 coords =
case+ particles of
| NIL => new_lst
| @(x, y) :: tl =>
if in_sticky_position (C, x, y) then
begin
C[x, y] := Sticky ();
loop (tl, new_lst)
end
else
loop (tl, @(x, y) :: new_lst)
in
particles := loop (particles, NIL)
end
 
fn
pour_particles
{w, h : pos}
{n : nat}
(C : container (w, h),
n : int n,
free_particles : &List0 @(intBtw (0, w), intBtw (0, h))?
>> List0 @(intBtw (0, w), intBtw (0, h)))
: void =
if n = 0 then
free_particles := NIL
else
let
typedef coords = @(intBtw (0, w), intBtw (0, h))
 
fun
loop {i : nat | i <= n - 1}
.<(n - 1) - i>.
(particles : list (coords, i),
i : int i)
: list (coords, n - 1) =
if i = pred n then
particles
else
let
val @(x, y) = find_placement_for_another_particle C
in
C[x, y] := Freely_moving;
loop (@(x, y) :: particles, succ i)
end
 
val @(xseed, yseed) = find_placement_for_another_particle C
in
C[xseed, yseed] := Sticky ();
free_particles := loop (NIL, 0)
end
 
fn
go_until_all_particles_are_stuck
{w, h : pos}
(C : container (w, h),
free_particles : List0 @(intBtw (0, w), intBtw (0, h)))
: void =
let
typedef coords = @(intBtw (0, w), intBtw (0, h))
 
fun
loop (free_particles : &List0 coords >> _) : void =
case+ free_particles of
| NIL => ()
| _ :: _ =>
begin
move_particles (C, free_particles);
find_which_particles_are_stuck (C, free_particles);
loop free_particles
end
 
var free_particles : List0 coords = free_particles
in
find_which_particles_are_stuck (C, free_particles);
loop free_particles
end
 
fn
build_a_tree {w, h : pos}
{n : nat}
(w : int w,
h : int h,
n : int n)
: container (w, h) =
let
val C = container_make (w, h)
var free_particles : List0 @(intBtw (0, w), intBtw (0, h))
in
pour_particles (C, n, free_particles);
go_until_all_particles_are_stuck (C, free_particles);
C
end
 
fn
write_a_PAM_image
{w, h : pos}
(outf : FILEref,
C : container (w, h),
seed : uint)
: void =
let
val w = width C and h = height C
 
fun
count_particles
{x, y : nat | x <= w; y <= h}
.<h - y, w - x>.
(x : int x,
y : int y,
n : int)
: int =
if y = h then
n
else if x = w then
count_particles (0, succ y, n)
else if C[x, y] = Empty () then
count_particles (succ x, y, n)
else
count_particles (succ x, y, succ n)
 
fun
loop {x, y : nat | x <= w; y <= h}
.<h - y, w - x>.
(x : int x,
y : int y)
: void =
if y = h then
()
else if x = w then
loop (0, succ y)
else
begin
fprint_val<char>
(outf, if C[x, y] = Empty () then '\1' else '\0');
loop (succ x, y)
end
in
fprintln! (outf, "P7");
fprintln! (outf, "# Number of particles = ",
count_particles (0, 0, 0));
fprintln! (outf, "# Seed = ", seed);
fprintln! (outf, "WIDTH ", width C);
fprintln! (outf, "HEIGHT ", height C);
fprintln! (outf, "DEPTH 1");
fprintln! (outf, "MAXVAL 1");
fprintln! (outf, "TUPLTYPE BLACKANDWHITE");
fprintln! (outf, "ENDHDR");
loop (0, 0)
end
 
(*------------------------------------------------------------------*)
 
implement
main0 (argc, argv) =
let
val args = list_vt2t (listize_argc_argv (argc, argv))
val nargs = argc
in
if nargs <> 5 then
begin
fprintln! (stderr_ref, "Usage: ", args[0],
" width height num_particles seed");
exit 1
end
else
let
val w = g1ofg0 (atoi (args[1]))
and h = g1ofg0 (atoi (args[2]))
and num_particles = g1ofg0 (atoi (args[3]))
and seed = g1ofg0 (atoi (args[4]))
in
if (w < 1) + (h < 1) + (num_particles < 0) + (seed < 0) then
begin
fprintln! (stderr_ref, "Illegal command line argument.");
exit 1
end
else
let
val seed : uint = g0i2u seed
val () = srandom seed
val C = build_a_tree (w, h, num_particles)
in
write_a_PAM_image (stdout_ref, C, seed)
end
end
end
 
(*------------------------------------------------------------------*)
</syntaxhighlight>
 
=={{header|AutoHotkey}}==
Line 262 ⟶ 702:
Takes a little while to run, be patient.
Requires the [http://www.autohotkey.com/forum/topic32238.html GDI+ Standard Library by Tic]
<syntaxhighlight lang=AHK"ahk">SetBatchLines -1
Process, Priority,, high
size := 400
Line 318 ⟶ 758:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> SYS "SetWindowText", @hwnd%, "Brownian Tree"
SIZE = 400
Line 348 ⟶ 788:
</syntaxhighlight>
[[File:Brownian_BBC.gif]]
 
=={{header|C}}==
{{libheader|FreeImage}}
<syntaxhighlight lang="c">#include <string.h>
#include <stdlib.h>
#include <time.h>
Line 421 ⟶ 860:
{{trans|D}}
This version writes the image as Portable Bit Map to stdout and doesn't move already set particles.
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <time.h>
Line 465 ⟶ 904:
}</syntaxhighlight>
Run-time about 12.4 seconds with SIDE=600, NUM_PARTICLES=10000.
 
=={{header|C sharp|C#}}==
{{works with|C#|3.0}}
{{libheader|System.Drawing}}
<syntaxhighlight lang="csharp">using System;
using System.Drawing;
 
Line 520 ⟶ 958:
}
}</syntaxhighlight>
 
=={{header|C++}}==
[[File:brownianTree_cpp.png|300px]]
 
For an animated version based on this same code see: [[Brownian tree/C++ animated]]
<syntaxhighlight lang="cpp">#include <windows.h>
#include <iostream>
#include <string>
Line 820 ⟶ 1,257:
}
//--------------------------------------------------------------------</syntaxhighlight>
 
=={{header|Common Lisp}}==
When the random walk lands on a set pixel it sets the pixel at the previous position.
Line 826 ⟶ 1,262:
The former produces denser trees than the latter. If compiled with SBCL, providing a command line argument will invoke the latter method.
Requires Quicklisp library manager and the CL-GD package for producing PNG images.
<syntaxhighlight lang="lisp">;;; brownian.lisp
;;; sbcl compile: first load and then (sb-ext:save-lisp-and-die "brownian" :executable t :toplevel #'brownian::main)
(ql:quickload "cl-gd")
Line 912 ⟶ 1,348:
:compression-level 6 :if-exists :supersede)))
</syntaxhighlight>
 
=={{header|D}}==
Uses the module of the Grayscale Image task. Partial {{trans|PureBasic}}
<syntaxhighlight lang="d">void main() {
import core.stdc.stdio, std.random, grayscale_image;
 
Line 955 ⟶ 1,390:
World side = 600, num_particles = 10_000, cropped (about 20 seconds run-time with dmd, about 4.3 seconds with ldc2):
<center>[[File:Dla_10000_d.png]]</center>
 
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">const
SIZE = 256;
NUM_PARTICLES = 1000;
Line 1,011 ⟶ 1,445:
end;
end;</syntaxhighlight>
 
=={{header|EasyLang}}==
 
[https://easylang.dev/show/#cod=dZHLboMwEEX3/oqzLoqxiahUCfIjiAUlRrVK7IjQFv6+snmkqpKFrfH1eM6dcet7PxxRaLTojaOrajKleAm7uPhvQ67IlRhMO6JkHpboKr3lkKCVqinRwlHyppQSPx+2N1gKnIDBXE0zCoCJkqFxZ+vG+PiAjvr8RP9yo+3pqnmHTQFYU5xihhSwwHR0EBmekmkpG8J5JSd3xJED2Qp+KNuOiQKFH5i3YOJURhdRXOKYDe+DaT5XvtwqPLC9eYQ42smTkgWb6QoO0/oz6EXqqtnfK/n/pWzoYT90WC7+jH6lZPMH7frTMiPBkuLin2/Xt96Y654un7QlhRS/ Run it]
[https://easylang.online/apps/_brownian-tree.html Run it]
 
<syntaxhighlight lang=text>color3 0 1 1
color3 0 1 1
len f[] 200 * 200
move 50 50
Line 1,024 ⟶ 1,458:
while i < n
repeat
x = randomrandint 200 - 1
y = randomrandint 200 - 1
until f[y * 200 + x + 1] <> 1
.
while 1 = 1
xo = x
yo = y
x += randomrandint 3 - 12
y += randomrandint 3 - 12
if x < 0 or y < 0 or x >= 200 or y >= 200
break 1
.
if f[y * 200 + x + 1] = 1
move xo / 2 yo / 2
rect 0.5 0.5
f[yo * 200 + xo + 1] = 1
i += 1
if i mod 16 = 0
Line 1,048 ⟶ 1,482:
.
.
.
.</syntaxhighlight>
</syntaxhighlight>
 
=={{header|Evaldraw}}==
 
Based on the C version. Shows the brownian tree animate. Color each particle based on the time it settled. Dont overwrite existing particles.
 
[[File:Brownian tree from initial particle at center.gif|thumb|alt=Brownian trees form patterns similar to dendrites in nature|Animated brownian tree over the coarse of circa 1000 frames]]
 
<syntaxhighlight lang="c">
enum{SIZE=256, PARTICLES_PER_FRAME=10, PARTICLE_OK, GIVE_UP};
static world[SIZE][SIZE];
()
{
// set the seed
if (numframes==0) world[SIZE/2][SIZE/2] = 1;
t = klock();
simulate_brownian_tree(t);
 
cls(0);
for (y = 0; y < SIZE; y++){
for (x = 0; x < SIZE; x++){
cell = world[y][x];
if ( cell ) {
s = 100; // color scale
setcol(128+(s*cell % 128), 128+(s*.7*cell % 128), 128+(s*.1*cell % 128) );
setpix(x,y);
}
}
}
moveto(0,SIZE+15);
setcol(0xffffff);
printf("%g frames", numframes);
}
 
plop_particle(&px, &py) {
for (try=0; try<1000; try++) {
px = int(rnd*SIZE);
py = int(rnd*SIZE);
if (world[py][px] == 0) return PARTICLE_OK;
}
return GIVE_UP;
}
 
simulate_brownian_tree(time){
for(iter=0; iter<PARTICLES_PER_FRAME; iter++) // Rate of particle creation
{
// set particle's initial position
px=0; py=0;
if ( plop_particle(px,py) == GIVE_UP ) return;
 
while (1) { // Keep iterating until we bump into a solid particle
// randomly choose a direction
dx = int(rnd * 3) - 1;
dy = int(rnd * 3) - 1;
if (dx + px < 0 || dx + px >= SIZE || dy + py < 0 || dy + py >= SIZE)
{
// Restart if outside of screen
if ( plop_particle(px,py) == GIVE_UP ) return;
}else if (world[py + dy][px + dx]){
// bumped into something
world[py][px] = time;
break;
}else{
py += dy;
px += dx;
}
}
}
}
 
</syntaxhighlight>
 
=={{header|Factor}}==
This example sets four spawn points, one in each corner of the image, giving the result a vague x-shaped appearance. For visual reasons, movement is restricted to diagonals. So be careful if you change the seed or spawns — they should all fall on the same diagonal.
<syntaxhighlight lang=factor>USINGheaderUSING: accessors images images.loader kernel literals math
math.vectors random sets ;
FROM: sets => in? ;
Line 1,102 ⟶ 1,609:
{{out}}
[https://i.imgur.com/qDVylB9.png image]
 
=={{header|Fantom}}==
 
<syntaxhighlight lang="fantom">
using fwt
using gfx
Line 1,208 ⟶ 1,714:
}
</syntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
Line 1,216 ⟶ 1,721:
For RCImageBasic and RCImageIO, see [[Basic bitmap storage/Fortran]] and [[Write ppm file#Fortran]]
 
<syntaxhighlight lang="fortran">program BrownianTree
use RCImageBasic
use RCImageIO
Line 1,322 ⟶ 1,827:
 
end program</syntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' version 16-03-2017
' compile with: fbc -s gui
 
Line 1,384 ⟶ 1,888:
Beep : Sleep 5000
End</syntaxhighlight>
 
=={{header|Gnuplot}}==
{{Works with|gnuplot|5.0 (patchlevel 3) and above}}
Line 1,391 ⟶ 1,894:
'''plotff.gp''' - Plotting from any data-file with 2 columns (space delimited), and writing to png-file.<br>
Especially useful to plot colored fractals using points.
<syntaxhighlight lang="gnuplot">
## plotff.gp 11/27/16 aev
## Plotting from any data-file with 2 columns (space delimited), and writing to png-file.
Line 1,417 ⟶ 1,920:
[[File:BT43gp.png|right|thumb|Output BT43gp.png]]
 
<syntaxhighlight lang="gnuplot">
## BTff.gp 11/27/16 aev
## Plotting 6 Brownian tree pictures.
Line 1,466 ⟶ 1,969:
BT1gp.png, BT2gp.png, BT3gp.png, BT41gp.png, BT43gp.png, BT43gp.png.
</pre>
 
=={{header|Go}}==
[[file:GoTree.png|right|thumb|Output png]]
Line 1,472 ⟶ 1,974:
 
Using standard image library:
<syntaxhighlight lang="go">package main
 
import (
Line 1,558 ⟶ 2,060:
}</syntaxhighlight>
Nearly the same, version below works with code from the bitmap task:
<syntaxhighlight lang="go">package main
 
// Files required to build supporting package raster are found in:
Line 1,637 ⟶ 2,139:
return false
}</syntaxhighlight>
 
=={{header|Haskell}}==
 
The modules <code>[[Bitmap#Haskell|Bitmap]]</code>, <code>[[Bitmap/Write a PPM file#Haskell|Bitmap.Netpbm]]</code>, and <code>[[Bitmap/Histogram#Haskell|Bitmap.BW]]</code> are on Rosetta Code. The commented-out type signatures require [http://hackage.haskell.org/trac/haskell-prime/wiki/ScopedTypeVariables scoped type variables] in order to function.
 
<syntaxhighlight lang="haskell">import Control.Monad
import Control.Monad.ST
import Data.STRef
Line 1,688 ⟶ 2,189:
off = black
on = white</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
[[File:Brownian_tree_unicon.png|400px|thumb|right|400x400 PA=70% SA=50% D=8%]]
In this version the seed is randomly set within an inner area and particles are injected in an outer ring.
 
<syntaxhighlight lang=Icon"icon">link graphics,printf
 
procedure main() # brownian tree
Line 1,763 ⟶ 2,263:
[http://www.cs.arizona.edu/icon/library/src/procs/graphics.icn graphics.icn provides graphics]
[http://www.cs.arizona.edu/icon/library/src/procs/printf.icn printf.icn provides printf]
 
=={{header|J}}==
 
<syntaxhighlight lang="j">brtr=:4 :0
seed=. ?x
clip=. 0 >. (<:x) <."1 ]
Line 1,788 ⟶ 2,287:
Example use:
 
<syntaxhighlight lang="j"> require'viewmat'
viewmat 480 640 brtr 30000</syntaxhighlight>
 
Note that building a brownian tree like this takes a while and would be more interesting if this were animated.
 
=={{header|Java}}==
{{libheader|Swing}} {{libheader|AWT}}
<syntaxhighlight lang="java">import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.*;
Line 1,870 ⟶ 2,368:
This is an alternate version which is a port of most of the code here.
This code does not use a GUI and saves the output to image.png.
<syntaxhighlight lang=Java"java">import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
Line 1,960 ⟶ 2,458:
}
}</syntaxhighlight>
 
=={{header|JavaScript}}==
===Using canvas===
[http://switchb.org/kpreid/2010/brownian-tree/ Live version] <!-- If changing this example, add note this link is outdated -->
<syntaxhighlight lang="javascript">function brownian(canvasId, messageId) {
var canvas = document.getElementById(canvasId);
var ctx = canvas.getContext("2d");
Line 2,094 ⟶ 2,591:
}</syntaxhighlight>
 
<syntaxhighlight lang="html"><html>
<head>
<script src="brownian.js"></script>
Line 2,103 ⟶ 2,600:
</body>
</html></syntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
This solution puts the seed in the center of the canvas. Motes are generated randomly in space and do a simple drunkard's walk until they hit the tree or leave the canvas (unless the sides are made <tt>side</tt>). The Motes are colorized according to their &theta; in polar coordinates.
 
<syntaxhighlight lang="julia">using Images, FileIO
 
function main(h::Integer, w::Integer, side::Bool=false)
Line 2,150 ⟶ 2,646:
save("data/browniantree_noside.jpg", imgnoside)
save("data/browniantree_wtside.jpg", imgwtside)</syntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|Java}}
<syntaxhighlight lang="scala">// version 1.1.2
 
import java.awt.Graphics
Line 2,217 ⟶ 2,712:
Thread(b).start()
}</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">'[RC]Brownian motion tree
nomainwin
dim screen(600,600)
Line 2,302 ⟶ 2,796:
close #1
end</syntaxhighlight>
 
=={{header|Locomotive Basic}}==
{{trans|ZX Spectrum Basic}}
This program is ideally run in [https://benchmarko.github.io/CPCBasic/cpcbasic.html CPCBasic] and should finish after about 20 to 25 minutes (Chrome, desktop CPU). At normal CPC speed, it would probably take several days to run when set to 10000 particles.
<syntaxhighlight lang="locobasic">10 MODE 1:DEFINT a-z:RANDOMIZE TIME:np=10000
20 INK 0,0:INK 1,26:BORDER 0
30 PLOT 320,200
Line 2,322 ⟶ 2,815:
1020 y=RND*400
1030 RETURN</syntaxhighlight>
 
=={{header|Lua}}==
The output is stored in as a ppm-image. The source code of these output-functions is located at
Line 2,328 ⟶ 2,820:
[[Grayscale image#Lua]],
[[Basic bitmap storage#Lua]].
<syntaxhighlight lang="lua">function SetSeed( f )
for i = 1, #f[1] do -- the whole boundary of the scene is used as the seed
f[1][i] = 1
Line 2,395 ⟶ 2,887:
end
Write_PPM( "brownian_tree.ppm", ConvertToColorImage(f) )</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
There is a [http://demonstrations.wolfram.com/DiffusionLimitedAggregation/ prettier version] at the Mathematica demo site. Its source code is also available there but it is not mine.
 
Loose {{trans|D}}
<syntaxhighlight lang=Mathematica"mathematica">canvasdim = 1000;
n = 0.35*canvasdim^2;
canvas = ConstantArray[0, {canvasdim, canvasdim}];
Line 2,430 ⟶ 2,921:
 
[[File:BrownianTree.png]]
 
=={{header|Nim}}==
{{libheader|imageman}}
 
<syntaxhighlight lang=Nim"nim">import random
import imageman
 
Line 2,477 ⟶ 2,967:
# Save into a PNG file.
image.savePNG("brownian.png", compression = 9)</syntaxhighlight>
 
=={{header|OCaml}}==
{{trans|D}}
 
<syntaxhighlight lang="ocaml">let world_width = 400
let world_height = 400
let num_particles = 20_000
Line 2,534 ⟶ 3,023:
<pre>$ ocamlopt -o brownian_tree.opt brownian_tree.ml
$ ./brownian_tree.opt | display -</pre>
 
=={{header|Octave}}==
{{trans|C}}
 
<syntaxhighlight lang="octave">function r = browniantree(xsize, ysize = xsize, numparticle = 1000)
r = zeros(xsize, ysize, "uint8");
r(unidrnd(xsize), unidrnd(ysize)) = 1;
Line 2,565 ⟶ 3,053:
r( r > 0 ) = 255;
jpgwrite("browniantree.jpg", r, 100); % image package</syntaxhighlight>
 
=={{header|PARI/GP}}==
All versions #1 - #4 are based on using 4 small plotting helper functions, which are allowing to unify
Line 2,573 ⟶ 3,060:
 
===Plotting helper functions===
<syntaxhighlight lang="parigp">
\\ 2 old plotting helper functions 3/2/16 aev
\\ insm(): Check if x,y are inside matrix mat (+/- p deep).
Line 2,607 ⟶ 3,094:
[[File:BTAH1.png|right|thumb|Output BTAH1.png]]
 
<syntaxhighlight lang="parigp">
\\ Brownian tree v.#1. Translated from AutoHotkey
\\ 3/8/2016, upgraded 11/27/16 aev
Line 2,653 ⟶ 3,140:
[[File:BTOC1.png|right|thumb|Output BTOC1.png]]
 
<syntaxhighlight lang="parigp">
\\ Brownian tree v.#2. Translated from Octave
\\ 3/8/2016, upgraded 11/27/16 aev
Line 2,696 ⟶ 3,183:
[[File:BTSE1.png|right|thumb|Output BTSE1.png]]
 
<syntaxhighlight lang="parigp">
\\ Brownian tree v.#3. Translated from Seed7
\\ 3/8/2016, upgraded 11/27/16 aev
Line 2,743 ⟶ 3,230:
[[File:BTPB3.png|right|thumb|Output BTPB3.png]]
 
<syntaxhighlight lang="parigp">
\\ Brownian tree v.#4. Translated from PureBasic
\\ 3/8/2016, upgraded 11/27/16 aev
Line 2,814 ⟶ 3,301:
*** Plotting from: c:\pariData\BTPB3.dat - 3641 DOTS
</pre>
 
=={{header|Perl}}==
[[File:brownian-00.png|thumb]][[File:brownian-05.png|thumb]][[File:brownian-11.png|thumb]]
Line 2,820 ⟶ 3,306:
 
Code runs until the tree reached specified radius. Output is written to "test.eps" of wherever the current directory is.
<syntaxhighlight lang="perl">subuse PI() { atan2(1,1) * 4 } # The, er, pistrict;
use warnings;
sub STEP() { .5 } # How far does the particle move each step. Affects
 
# both speed and accuracy greatly
use constant PI => 2*atan2(1,0); # π
sub STOP_RADIUS() { 100 } # When the tree reaches this far from center, end
use constant STEP => 0.5; # How far particle moves each step. Affects both speed and accuracy greatly
use constant STOP_RADIUS => 100; # When the tree reaches this far from center, end
 
# At each step, move this much towards center. Bigger numbers help the speed because
# particles are less likely to wander off, but greatly affects tree shape.
# Should be between 0 and 1 ish. Set to 0 for pain.
subuse constant ATTRACT() {=> 0.2 };
 
my @particles = map([ map([], 0 .. 2 * STOP_RADIUS) ], 0 .. 2 * STOP_RADIUS);
push @{ $particles[STOP_RADIUS][STOP_RADIUS] }, [0, 0];
my($r_start, $max_dist) = (3, 0);
 
my $r_start = 3;
my $max_dist = 0;
 
sub dist2 {
no warnings 'uninitialized';
my ($dx, $dy) = ($_[0][0] - $_[1][0], $_[0][1] - $_[1][1]);
$dx * $dx + $dy * $dy
Line 2,920 ⟶ 3,407:
 
my $count;
PARTICLE: while (1) {
my $a = rand(2 * PI);
my $p = [ $r_start * cos($a), $r_start * sin($a) ];
while (my $m = move( $p)) {
if ($m == 1) { next }
elsif ($m == 2) { $count++; last; }
elsif ($m == 3) { last PARTICLE }
else { last }
}
print STDERR "$count $max_dist/@{[int($r_start)]}/@{[STOP_RADIUS]}\r" unless $count% 7;
Line 2,934 ⟶ 3,421:
sub write_eps {
my $size = 128;
my $p = $size / (STOP_RADIUS * 1.05);
my $b = STOP_RADIUS * $p;
if ($p < 1) {
$size = STOP_RADIUS * 1.05;
$bp = STOP_RADIUS1;
$pb = 1STOP_RADIUS;
}
 
my $hp = $p / 2;
 
open OUT, "'>"', "'test.eps"';
print OUT <<~"HEAD";
 
# print EPS to standard%!PS-Adobe-3.0 outEPSF-3.0
%%BoundingBox: 0 0 @{[$size*2, $size*2]}
print OUT <<"HEAD";
$size $size translate
%!PS-Adobe-3.0 EPSF-3.0
/l{ rlineto }def
%%BoundingBox: 0 0 @{[$size*2, $size*2]}
/c{ $hp 0 360 arc fill }def
$size $size translate
-$size -$size moveto
/l{ rlineto }def
$size 2 mul 0 l
/c{ $hp 0 360 arc fill }def
-$size - 0 $size moveto2 mul l
-$size 2 mul 0 l
closepath
0 $size 2 mul l
0 setgray fill
-$size 2 mul 0 l
0 setlinewidth .1 setgray 0 0 $b 0 360 arc stroke
closepath
.8 setgray /TimesRoman findfont 16 scalefont setfont
0 setgray fill
-$size 10 add $size -16 add moveto
0 setlinewidth .1 setgray 0 0 $b 0 360 arc stroke
(Step = @{[STEP]} Attract = @{[ATTRACT]}) show
.8 setgray /TimesRoman findfont 16 scalefont setfont
0 1 0 setrgbcolor newpath
-$size 10 add $size -16 add moveto
HEAD
(Step = @{[STEP]} Attract = @{[ATTRACT]}) show
0 1 0 setrgbcolor newpath
HEAD
 
for (@particles) {
Line 2,975 ⟶ 3,459:
}
 
write_eps();</syntaxhighlight>
 
=={{header|Phix}}==
As-is, runs in about 2s, but can be very slow when bigger or (even worse) resize-able.
{{libheader|Phix/pGUI}}
<!--<syntaxhighlight lang=Phix"phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\BrownianTree.exw</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 3,044 ⟶ 3,528:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
 
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp"picolisp">(load "@lib/simul.l")
 
(de brownianTree (File Size Cnt)
Line 3,068 ⟶ 3,551:
<pre>(brownianTree "img.pbm" 300 9000)
(call 'display "img.pbm")</pre>
 
=={{header|Processing}}==
<syntaxhighlight lang="java">boolean SIDESTICK = false;
boolean[][] isTaken;
 
Line 3,114 ⟶ 3,596:
{{trans|Processing}}
 
<syntaxhighlight lang="python">SIDESTICK = False
 
def setup() :
Line 3,145 ⟶ 3,627:
if frameCount > width * height:
noLoop()</syntaxhighlight>
 
=={{header|PureBasic}}==
<syntaxhighlight lang=PureBasic"purebasic">#Window1 = 0
#Image1 = 0
#ImgGadget = 0
Line 3,186 ⟶ 3,667:
Until Event = #PB_Event_CloseWindow
EndIf</syntaxhighlight>[[File:BrownianTree.pb.png]]
 
=={{header|Python}}==
{{libheader|pygame}}
<syntaxhighlight lang="python">import pygame, sys, os
from pygame.locals import *
from random import randint
Line 3,290 ⟶ 3,770:
input(pygame.event.get())
pygame.display.flip()</syntaxhighlight>
 
=={{header|R}}==
All versions #1 - #4 are based on using 2 small plotting helper functions, which are allowing to unify
Line 3,313 ⟶ 3,792:
file could be very slow too. Actually, plotv2() shows almost "pure" plotting time.
 
<syntaxhighlight lang="r">
# plotmat(): Simple plotting using a square matrix mat (filled with 0/1). v. 8/31/16
# Where: mat - matrix; fn - file name; clr - color; ttl - plot title;
Line 3,361 ⟶ 3,840:
 
====Version #1.====
<syntaxhighlight lang="r">
# Generate and plot Brownian tree. Version #1.
# 7/27/16 aev
Line 3,408 ⟶ 3,887:
 
====Version #2.====
<syntaxhighlight lang="r">
# Generate and plot Brownian tree. Version #2.
# 7/27/16 aev
Line 3,467 ⟶ 3,946:
 
====Version #3.====
<syntaxhighlight lang="r">
# Generate and plot Brownian tree. Version #3.
# 7/27/16 aev
Line 3,521 ⟶ 4,000:
 
====Version #4.====
<syntaxhighlight lang="r">
# Generate and plot Brownian tree. Version #4.
# 7/27/16 aev
Line 3,575 ⟶ 4,054:
*** END: Mon Sep 05 11:50:47 2016
</pre>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">#lang racket
(require 2htdp/image)
 
Line 3,701 ⟶ 4,179:
img
(save-image img "brownian-tree.png")</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
Line 3,711 ⟶ 4,188:
{{works with|Rakudo|2015.12}}
 
<syntaxhighlight lang="raku" line>constant size = 100;
constant particlenum = 1_000;
 
Line 3,778 ⟶ 4,255:
 
display;</syntaxhighlight>
 
=={{header|REXX}}==
A large part of the REXX program's prologue was to handle the various options. <br>
Line 3,786 ⟶ 4,262:
 
Program note: &nbsp; to keep things simple, the (system) command to clear the screen was hard-coded as &nbsp; '''CLS'''.
<syntaxhighlight lang="rexx">/*REXX program animates and displays Brownian motion of dust in a field (with one seed).*/
mote = '·' /*character for a loose mote (of dust).*/
hole = ' ' /* " " an empty spot in field.*/
Line 3,984 ⟶ 4,460:
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Brownian tree
 
Line 4,089 ⟶ 4,564:
 
[https://www.dropbox.com/s/a22tu6wf0ibu502/BrownianTree.jpg?dl=0 Brownian tree]
 
=={{header|Ruby}}==
{{libheader|RMagick}}
<syntaxhighlight lang="ruby">require 'rubygems'
require 'RMagick'
 
Line 4,148 ⟶ 4,622:
draw.draw img
img.write "brownian_tree.bmp"</syntaxhighlight>
 
=={{header|Run BASIC}}==
[[File:BrownianTreeKokenge.png|thumb|right|]]
<syntaxhighlight lang="runbasic">numParticles = 3000
dim canvas(201,201)
graphic #g, 200,200
Line 4,172 ⟶ 4,645:
render #g
#g "flush"</syntaxhighlight>
 
=={{header|Rust}}==
{{trans|D}}
{{libheader|rand}}
{{libheader|image}}
<syntaxhighlight lang="rust">
extern crate image;
extern crate rand;
Line 4,284 ⟶ 4,756:
For a 512 x 512 field and 100k motes, run time is around 200 s on ~2019 hardware (Ryzen 5 3600X).
<center>[[File:Rust-Brownian-512-20k.png]]</center>
 
=={{header|Scala}}==
===Java Swing Interoperability===
<syntaxhighlight lang=Scala"scala">import java.awt.Graphics
import java.awt.image.BufferedImage
 
Line 4,337 ⟶ 4,808:
new Thread(new BrownianTree).start()
}</syntaxhighlight>
 
=={{header|Scheme}}==
{{works with|Guile}}
<syntaxhighlight lang="scheme">; Save bitmap to external file
(define (save-pbm bitmap filename)
(define f (open-output-file filename))
Line 4,449 ⟶ 4,919:
(save-pbm bitmap "brownian-tree.pbm")</syntaxhighlight>
[[File:Scheme-guile-brownian-tree-large.png]]
 
=={{header|Seed7}}==
[[File:browniantree.png|300px|thumb|right|Simple brownian tree produced with Seed7 program]]
The program below generates a small brownian tree. You can watch how it grows.
 
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "draw.s7i";
include "keybd.s7i";
Line 4,490 ⟶ 4,959:
world[py][px] := 1;
rect(SCALE * pred(px), SCALE * pred(py), SCALE, SCALE, white);
DRAW_FLUSHflushGraphic;
bumped := TRUE;
else
Line 4,498 ⟶ 4,967:
until bumped;
end for;
end func;
const proc: main is func
begin
screen(SIZE * SCALE, SIZE * SCALE);
KEYBOARD := GRAPH_KEYBOARD;
genBrownianTree(SIZE, 20000);
readln(KEYBOARD);
end func;</syntaxhighlight>
 
Line 4,512 ⟶ 4,973:
=={{header|SequenceL}}==
'''SequenceL Code:'''<br>
<syntaxhighlight lang="sequencel">import <Utilities/Random.sl>;
import <Utilities/Sequence.sl>;
 
Line 4,562 ⟶ 5,023:
'''C++ Driver Code:'''<br>
{{libheader|CImg}}
<syntaxhighlight lang="c">#include <time.h>
#include <cstdlib>
#include "CImg.h"
Line 4,609 ⟶ 5,070:
{{out}}
[http://i.imgur.com/OrB9tLI.gifv Output Video]
 
=={{header|Sidef}}==
{{trans|Raku}}
<syntaxhighlight lang="ruby">const size = 100
const mid = size>>1
const particlenum = 1000
Line 4,731 ⟶ 5,191:
</pre>
=={{header|Simula}}==
<syntaxhighlight lang="simula">BEGIN
INTEGER NUM_PARTICLES;
INTEGER LINES, COLUMNS;
Line 4,849 ⟶ 5,309:
................................................................................
</pre>
 
=={{header|Sinclair ZX81 BASIC}}==
Requires at least 2k of RAM. If you have more, you can plot it on a larger grid—up to and including full-screen, provided you don't mind spending literally hours watching the first few dots maunder about without hitting anything.
<syntaxhighlight lang="basic"> 10 DIM A$(20,20)
20 LET A$(10,10)="1"
30 FOR Y=42 TO 23 STEP -1
Line 4,878 ⟶ 5,337:
{{out}}
Screenshot [http://www.edmundgriffiths.com/zx81browniantree.jpg here].
 
=={{header|Tcl}}==
{{libheader|Tk}}
<syntaxhighlight lang="tcl">package require Tcl 8.5
package require Tk
 
Line 4,933 ⟶ 5,391:
makeBrownianTree 1000
brownianTree write tree.ppm</syntaxhighlight>
 
=={{header|TI-83 BASIC}}==
<syntaxhighlight lang="ti83b">:StoreGDB 0
:ClrDraw
:FnOff
Line 4,962 ⟶ 5,419:
:Pause
:RecallGDB 0</syntaxhighlight>
 
=={{header|Uiua}}==
Uiua Pad will show well-shaped arrays as images directly. If running locally you can uncomment the final few lines to save it as a file instead. (Running local is ~10 times faster too.)
 
The main move loop passes round a pair of points: here and previous position, so when we hit a set cell we can just back up one.
 
<syntaxhighlight lang="Uiua">
S ← 80
# Create SxS grid, and set the centre point as seed.
⍜⊡(+1)↯2⌊÷2S ↯ S_S 0
 
RandInt ← ⌊×⚂
RandPoint ← ([⍥(RandInt S)2])
# Update the pair to be a new adjacent [[Here] [Last]]
Move ← ⊟∵(-1+⌊RandInt 3).⊢
In ← /××⊃(≥0)(<S) # Is this point in bounds?
# Given a grid return a free point pair and that grid.
SeedPair ← ⊟.⍢(RandPoint ◌)(=1⊡) RandPoint
# Find next adjacent position, or new seed if out of bounds.
Next ← ⟨SeedPair ◌|∘⟩:⟜(In ⊢)Move
# Start from a new Seed Pair and move until you hit the tree. Add the prior pos to the tree.
JoinTree ← ⍜⊡(+1)◌°⊟⍢Next (=0⊡⊢) SeedPair
# Do it multiple times.
⍜now⍥JoinTree500
 
# ◌
# &ime "png"
# &fwa "BrownianTree.png"
</syntaxhighlight>
 
Or if you like your code terse :-)
 
<syntaxhighlight lang="Uiua">
S ← 80
⍜⊡(+1)↯2⌊÷2S↯S_S0
Rp ← (⊟⍥(⌊×⚂S)2)
Sd ← ⊟.⍢(Rp◌)(=1⊡) Rp
Nx ← ⟨Sd◌|∘⟩:⟜(/××⊃(≥0)(<S)⊢)⊟∵(-1+⌊×⚂3).⊢
⍜now⍥(⍜⊡(+1)◌°⊟⍢Nx(=0⊡⊢)Sd)500
</syntaxhighlight>
{{out}}
[[File:UiuaBrownianTree.png|thumb|center||Sample with higher values than provided code]]
 
=={{header|Visual Basic .NET}}==
Windows Forms Application.
 
<syntaxhighlight lang="vbnet">
Imports System.Drawing.Imaging
 
Line 5,099 ⟶ 5,598:
{{out|Final output}}
[[File:SH_BrownianTree.jpg]]
 
=={{header|Wren}}==
{{libheader|DOME}}
{{trans|Go}}
As you'd expect, not very fast so have halved Go's parameters to draw the tree in around 45 seconds.
<syntaxhighlight lang=ecmascript"wren">import "graphics" for Canvas, Color
import "dome" for Window
import "random" for Random
Line 5,198 ⟶ 5,696:
=={{header|XPL0}}==
[[File:BrownXPL0.gif|right]]
<syntaxhighlight lang=XPL0"xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
def W=128, H=W; \width and height of field
int X, Y;
Line 5,216 ⟶ 5,714:
];
]</syntaxhighlight>
 
=={{header|zkl}}==
This grows rather slowly, so I've added a circle for barnacles to attach to. It looks like tendrils growing from the center to the circle and vice versa. The tree type is similar to that shown in the XPLO and Visual Basic .NET solutions.
Line 5,223 ⟶ 5,720:
Uses the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl
[[File:Brownian.zkl.jpg|250px|thumb|right]]
<syntaxhighlight lang="zkl">w:=h:=400; numParticles:=20_000;
bitmap:=PPM(w+2,h+2,0); // add borders as clip regions
 
Line 5,256 ⟶ 5,753:
}
bitmap.writeJPGFile("brownianTree.zkl.jpg"); // the final image</syntaxhighlight>
 
=={{header|ZX Spectrum Basic}}==
{{trans|Run BASIC}}
Very, very slow on a ZX Spectrum (even emulate and at maximum speed). Best use SpecBAS, changing the value of the variable np to 6000.
<syntaxhighlight lang="zxbasic">10 LET np=1000
20 PAPER 0: INK 4: CLS
30 PLOT 128,88
Line 5,277 ⟶ 5,773:
1030 RETURN
</syntaxhighlight>
 
[[Category:Geometry]]
62

edits