]> git.sommitrealweird.co.uk Git - advent-of-code-2021.git/blob - day07/crabs2.sh
Day 14
[advent-of-code-2021.git] / day07 / crabs2.sh
1 #!/bin/bash
2
3 set -u
4
5 filename="${1:-example.txt}"
6
7 exec 3<"$filename"
8
9 OLDIFS="$IFS"
10 IFS=","
11 read -u 3 -a crabs
12
13 IFS=$'\n'
14 crabs=($(sort -n <<<"${crabs[*]}"))
15
16 count=$((${#crabs[@]}))
17 total=0
18 for elem in "${crabs[@]}"; do
19     ((total+=$elem))
20 done
21 mean=$((total / $count))
22
23 fuel=0
24
25 # Actual best position could be mean +- 1, so loop through them to check
26 for (( tempmean=$((mean-1)); tempmean<=$((mean+1)); tempmean++ )); do
27     new_fuel=0
28     for (( a=0; a<${#crabs[@]}; a++ )); do
29         diff=$((tempmean-${crabs[$a]}))
30         diff=${diff#-}
31         if [ $diff -gt 0 ]; then
32             for (( i=0; i<=$diff; i++ )); do
33                 ((new_fuel+=$i))
34             done
35         fi
36     done
37     if [ $fuel -eq 0 ] || [ $new_fuel -lt $fuel ]; then
38         fuel=$new_fuel
39         found_mean=$tempmean
40     fi
41 done
42
43 echo "Found mean: $found_mean"
44 echo "Fuel needed: $fuel"