-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.sh
68 lines (52 loc) · 1.16 KB
/
main.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/env bash
# Enable bash "strict mode"
# http://redsymbol.net/articles/unofficial-bash-strict-mode/
set -euo pipefail
shopt -s inherit_errexit
IFS=$'\n\t'
calorie_totals() {
local -r input_file="$1"
local calorie_total=0
while read -r line; do
if [ "$line" = "" ]; then
echo "$calorie_total "
calorie_total=0
else
calorie_total=$((calorie_total + line))
fi
done <"$input_file"
}
part_one() {
local -r input_file="$1"
local best_total=0
for total in $(calorie_totals "$input_file"); do
if ((total > best_total)); then
best_total=$total
fi
done
echo "part one: $best_total"
}
part_two() {
local -r input_file="$1"
local sum=0
for total in $(calorie_totals "$input_file" | sort -n | tail -3); do
sum=$((sum + total))
done
echo "part two: $sum"
}
usage() {
cat >/dev/stderr <<-EOF
Usage: ${0} [INPUT]
Advent of Code 2022: part one
EOF
}
main() {
if [[ "$#" -lt 1 ]]; then
usage
exit 1
fi
local -r input_file="$1"
part_one "$input_file"
part_two "$input_file"
}
main "$@"