(*:Title:  CellularAutomata *)

(*:Author: Wolfram Research, Inc. *)

(*:Copyright: Copyright 1992-1993, Wolfram Research, Inc. *)

(*:Package Version: 1.0 *)

(*:Mathematica Version: 2.0 *)

(*:Summary: 
	This package includes some functions for working with
	one-dimensional cellular automata.
*)

(*:Keywords: cells, automata
*)

(*:Discussion: *)

(*:Context: Examples`CellularAutomata` *)

(*:Source: *)

(*:History:
	Header information added August 1992, Jeff Adams, Wolfram Research, Inc.
*)

(*:Limitations: *)

BeginPackage["Examples`CellularAutomata`"]

UpdateCA::usage =
	"UpdateCA[list, rule] applies one time step of a CA rule to list.
	The CA rule is given as a list of replacements for neighborhoods,
	such as {{1,0,0}->1, {1,1,1}->1, {1,1,_}->0, {1,0,1}->1, 
	{0,a_,b_}:>Mod[a+b,2]}."

EvolveCA::usage =
	"EvolveCA[init, rule, t] evolves a CA for t time steps, giving a
	list of the configurations produced."

ShowCA::usage =
	"ShowCA[list] displays a cellular automaton evolution history
	graphically."

NumberedRule::usage =
	"NumberedRule[n] gives a rule table for a k=2, r=1 rule specified
	by the integer n."

CenterSpot::usage =
	"CenterSpot[list, n] generates a list of n zeros, with the
	elements of list in the middle."

Begin["`Private`"]

UpdateCA[list_List, rule_] :=
	Module[ { t }, 
		t = Join[ {Last[list]}, list, {First[list]} ] ;
		t = Partition[t, 3, 1] ;
		Map[Replace[#, rule]&, t]
	]

Pad[list_List, n_Integer] :=
	If[Length[list] < n, Join[Table[0, {n-Length[list]}], list], list]
		
	
Neighborhoods[k_Integer:2, rr_Integer:3] :=
	Module[ { t },
		t = Range[k^rr - 1, 0, -1] ;
		Map[ Pad[ IntegerDigits[#, k], rr ] &, t ]
	]

EvolveCA[init_List, rule_, t_Integer] :=
	Module[{ drule = Dispatch[rule] }, 
		NestList[UpdateCA[#, drule]&, init, t]
	]

ShowCA[list_List] :=
	Show[Graphics[Raster[
		Reverse[  1 - list ] 
	]],AspectRatio -> 1]

NumberedRule[n_Integer, k_Integer:2, rr_Integer:3] :=
	Thread[ Neighborhoods[k, rr] -> Pad[IntegerDigits[n, k], k^rr] ]

CenterSpot[list_List, n_Integer] :=
	Module[ { i1 },
		i1 = Floor[ (n - Length[list])/ 2 ] ;
		Join[ Table[0, {i1}], 
			list,
		      Table[0, {n-i1-Length[list]}]
		]
	]

End[]

EndPackage[]

