]> git.sommitrealweird.co.uk Git - advent-of-code-2021.git/blob - day06/lanternfish2.sh
924ac463179e8fc8555465adfdd636e8e05c773d
[advent-of-code-2021.git] / day06 / lanternfish2.sh
1 #!/bin/bash
2
3 set -u
4 set -e
5
6 declare -a fish
7
8 filename="${1:-example.txt}"
9
10 exec 3<"$filename"
11
12 OLDIFS="$IFS"
13 IFS=","
14 read -u 3 -a fish
15 IFS="$OLDIFS"
16
17 buckets=(0 0 0 0 0 0 0 0 0)
18
19 for f in "${fish[@]}"; do
20     ((buckets[$f]+=1))
21 done
22
23 for (( d=1; d<=256; d++ )); do
24     orig_zeros=${buckets[0]}
25     for (( i=1; i<=8; i++ )); do
26         temp=${buckets[$i]}
27         ((buckets[$((i-1))]+=$temp)) || true
28         buckets[$i]=0
29     done
30     ((buckets[8]+=$orig_zeros)) || true
31     ((buckets[6]+=$orig_zeros)) || true
32     ((buckets[0]-=$orig_zeros)) || buckets[0]=0
33 done
34
35 count=0
36 for (( i=0; i<=8; i++ )); do
37     ((count+=${buckets[$i]}))
38 done
39
40 echo "After 256 days there are $count fish"