One-dimensional cellular automata: Difference between revisions

Content added Content deleted
m (Added to games cat)
Line 423: Line 423:
Generation 8: __##________________
Generation 8: __##________________
Generation 9: __##________________</pre>
Generation 9: __##________________</pre>

=={{header|OCaml}}==

<ocaml>let get g i =
try g.(i)
with _ -> 0

let next_cell g i =
match get g (i-1), get g (i), get g (i+1) with
| 0, 0, 0 -> 0
| 0, 0, 1 -> 0
| 0, 1, 0 -> 0
| 0, 1, 1 -> 1
| 1, 0, 0 -> 0
| 1, 0, 1 -> 1
| 1, 1, 0 -> 1
| 1, 1, 1 -> 0
| _ -> assert(false)

let next g =
let old_g = Array.copy g in
for i = 0 to pred(Array.length g) do
g.(i) <- (next_cell old_g i)
done

let print_g g =
for i = 0 to pred(Array.length g) do
if g.(i) = 0
then print_char '_'
else print_char '#'
done;
print_newline()
</ocaml>

put the code above in a file named "life.ml", and then use it in the ocaml toplevel like this:

<pre style="height:36ex;overflow:scroll">
#use "life.ml" ;;

let iter n g =
for i = 0 to n do
Printf.printf "Generation %d: " i; print_g g;
next g;
done
;;

let g_of_string str =
let f = (function '_' -> 0 | '#' -> 1 | _ -> assert false) in
Array.init (String.length str) (fun i -> f str.[i])
;;

# iter 9 (g_of_string "_###_##_#_#_#_#__#__") ;;
Generation 0: _###_##_#_#_#_#__#__
Generation 1: _#_#####_#_#_#______
Generation 2: __##___##_#_#_______
Generation 3: __##___###_#________
Generation 4: __##___#_##_________
Generation 5: __##____###_________
Generation 6: __##____#_#_________
Generation 7: __##_____#__________
Generation 8: __##________________
Generation 9: __##________________
- : unit = ()
</pre>


=={{header|Python}}==
=={{header|Python}}==