Brownian tree: Difference between revisions

added ocaml
(→‎Solutions: Added a Python solution)
(added ocaml)
Line 456:
</body>
</html></lang>
 
 
=={{header|OCaml}}==
{{trans|D}}
 
<lang ocaml>let world_width = 800
let world_height = 800
let num_particles = 10_000
let () =
assert(num_particles > 0);
assert(world_width * world_height > num_particles);
;;
let dla ~world =
(* particle values *)
let px = ref 0
and py = ref 0 in
(* put the tree seed *)
world.(world_height / 2).(world_width / 2) <- 1;
for i = 1 to num_particles do
(* set particle's initial position *)
px := Random.int world_width;
py := Random.int world_height;
try
while (true) do (* move particle *)
(* randomly choose a direction *)
let dx = (Random.int 3) - 1 (* offsets *)
and dy = (Random.int 3) - 1 in
if (dx + !px < 0 || dx + !px >= world_width ||
dy + !py < 0 || dy + !py >= world_height) then begin
(* plop the particle into some other random location *)
px := Random.int world_width;
py := Random.int world_height;
end
else if (world.(!py + dy).(!px + dx) <> 0) then begin
(* bumped into something, particle set *)
world.(!py).(!px) <- 1;
raise Exit;
end
else begin
py := !py + dy;
px := !px + dx;
end
done
with Exit -> ()
done
let to_pbm ~world =
print_endline "P1"; (* Type=Portable bitmap, Encoding=ASCII *)
Printf.printf "%d %d\n" world_width world_height;
Array.iter (fun line ->
Array.iter (fun pixel -> print_int pixel) line;
print_newline()
) world
let () =
Random.self_init();
let world = Array.make_matrix world_width world_height 0 in
dla ~world;
to_pbm ~world;
;;</lang>
 
 
=={{header|Octave}}==