2 declare -A grid next
# use namerefs and function to toggle between them
7 if [[ $cell == '#' ]]; then
13 done < <(printf $line |
sed 's/\(.\)/\1\n/g')
17 # count [name] # set $count to the number of cells turned on in ${grid[*]}
19 declare -n g
=${1-grid}
22 while [[ $i -lt $h ]]; do
24 while [[ $j -lt $w ]]; do
25 count
=$
((count
+ g
[$i.
$j]))
31 if [[ ! $part1 ]]; then
35 grid
[$
((h-1
)).$
((w-1
))]=1
38 echo "initial $w*$h grid contains ${#grid[*]} cells, $count on"
39 # generate old new # compute the next generation in new reading from old
41 declare -n old
=$1 new
=$2
43 while [[ $i -lt $h ]]; do
45 while [[ $j -lt $w ]]; do
46 neighbors
=$
((old
[$
((i-1
)).$
((j-1
))] +
47 old
[$
((i-1
)).$
((j
))] +
48 old
[$
((i-1
)).$
((j
+1))] +
49 old
[$
((i
)).$
((j-1
))] +
50 old
[$
((i
)).$
((j
+1))] +
51 old
[$
((i
+1)).$
((j-1
))] +
52 old
[$
((i
+1)).$
((j
))] +
53 old
[$
((i
+1)).$
((j
+1))]))
54 new
[$i.
$j]=$
((neighbors
== 3 ||
(neighbors
== 2 && old
[$i.
$j])))
55 # echo "cell $i.$j has $neighbors on, new state ${new[$i.$j]}"
60 if [[ ! $part1 ]]; then
64 new
[$
((h-1
)).$
((w-1
))]=1
68 while [[ $iter -lt $iters ]]; do
69 echo "computing generation $iter"
70 if ((iter
%2)); then # odd iteration
82 echo "final grid has $count cells on"