]> git.sommitrealweird.co.uk Git - advent-of-code-2021.git/blob - day07/crabs.sh
Day 15 add description"
[advent-of-code-2021.git] / day07 / crabs.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 mid_point=$((${#crabs[@]} / 2))
17 mid_val=${crabs[$mid_point]}
18
19 fuel=0
20
21 for (( a=0; a<${#crabs[@]}; a++ )); do
22     diff=$((mid_val-${crabs[$a]}))
23     diff=${diff#-}
24     ((fuel+=$diff))
25 done
26
27 echo "Fuel needed: $fuel"