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
index 3050832c18aa82f27d8289f5baa34164d2edfd6f..c81682ce3ed9bbeb4683e006fc408f87c9fc683e 100755 (executable)
@@ -7,6 +7,9 @@ declare -a fish
 
 filename="${1:-example.txt}"
 
+iter_1=80
+iter_2=256
+
 exec 3<"$filename"
 
 OLDIFS="$IFS"
@@ -14,16 +17,34 @@ IFS=","
 read -u 3 -a fish
 IFS="$OLDIFS"
 
-for (( d=1; d<=80; d++ )); do
-    start_fish_count=${#fish[@]}
-    for (( i=0; i<$start_fish_count; i++ )); do
-        if [ ${fish[$i]} -eq 0 ]; then
-            fish+=(8)
-            fish[$i]=6
-        else
-            ((fish[$i]-=1)) || fish[$i]=0
-        fi
+buckets=(0 0 0 0 0 0 0 0 0)
+
+get_count() {
+    local count=0
+
+    for (( i=0; i<=8; i++ )); do
+        ((count+=${buckets[$i]}))
     done
+
+    echo "$count"
+}
+
+for f in "${fish[@]}"; do
+    ((buckets[$f]+=1))
+done
+
+for (( d=1; d<=$iter_2; d++ )); do
+    orig_zeros=${buckets[0]}
+    for (( i=1; i<=8; i++ )); do
+        temp=${buckets[$i]}
+        ((buckets[$((i-1))]+=$temp)) || true
+        buckets[$i]=0
+    done
+    ((buckets[8]+=$orig_zeros)) || true
+    ((buckets[6]+=$orig_zeros)) || true
+    ((buckets[0]-=$orig_zeros)) || buckets[0]=0
+
+    [ $d -eq $iter_1 ] && echo "After $iter_1 days there are $(get_count) fish"
 done
 
-echo "After 80 days there are ${#fish[@]} fish"
+echo "After $iter_2 days there are $(get_count) fish"