Make all scripts able to take a file name, merge parts 1 and 2 of lanternfish in...
[advent-of-code-2021.git] / day06 / lanternfish.sh
1 #!/bin/bash
2
3 set -u
4 set -e
5
6 declare -a fish
7
8 filename="${1:-example.txt}"
9
10 iter_1=80
11 iter_2=256
12
13 exec 3<"$filename"
14
15 OLDIFS="$IFS"
16 IFS=","
17 read -u 3 -a fish
18 IFS="$OLDIFS"
19
20 buckets=(0 0 0 0 0 0 0 0 0)
21
22 get_count() {
23     local count=0
24
25     for (( i=0; i<=8; i++ )); do
26         ((count+=${buckets[$i]}))
27     done
28
29     echo "$count"
30 }
31
32 for f in "${fish[@]}"; do
33     ((buckets[$f]+=1))
34 done
35
36 for (( d=1; d<=$iter_2; d++ )); do
37     orig_zeros=${buckets[0]}
38     for (( i=1; i<=8; i++ )); do
39         temp=${buckets[$i]}
40         ((buckets[$((i-1))]+=$temp)) || true
41         buckets[$i]=0
42     done
43     ((buckets[8]+=$orig_zeros)) || true
44     ((buckets[6]+=$orig_zeros)) || true
45     ((buckets[0]-=$orig_zeros)) || buckets[0]=0
46
47     [ $d -eq $iter_1 ] && echo "After $iter_1 days there are $(get_count) fish"
48 done
49
50 echo "After $iter_2 days there are $(get_count) fish"