advent-of-code

advent of code attempts
git clone git://bvnf.space/advent-of-code.git
Log | Files | Refs

count_2.sh (776B)


      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
#!/bin/sh

[ "$#" = 1 ] || {
    printf "usage: %s inputfile\n" "$0" >&2
    exit 1
}
update () {
    if [ "$cur" -gt "$max1" ]; then
        max3=$max2
        max2=$max1
        max1="$cur"
    elif [ "$cur" -gt "$max2" ]; then
        max3=$max2
        max2="$cur"
    elif [ "$cur" -gt "$max3" ]; then
        max3="$cur"
    fi
}

max1=0
max2=0
max3=0
cur=0
while read -r line; do
    case "$line" in '')
        update
        cur=0
    ;;
    [0-9]*)
        printf "%d\n" "$line" >/dev/null 2>&1 || {
            printf "%s is not a number\n" "$line" >&2
            exit 1
        }
        cur=$((cur + line))
    ;;
    *)
        printf "%s is not a number\n" "$line" >&2
        exit 1
    ;;
    esac
done < "$1"
update

printf "%d\n" "$((max1 + max2 + max3))"