]> git.sommitrealweird.co.uk Git - advent-of-code-2020.git/blob - day04/count_valid_passports.sh
Day 14 - implemented in bash, because, well, I could
[advent-of-code-2020.git] / day04 / count_valid_passports.sh
1 #!/bin/bash
2
3 declare -a data
4 cur_data=""
5 seperator=""
6 valid_count=0
7
8 required_fields=(byr iyr eyr hgt hcl ecl pid)
9 exec 3<input.txt
10
11 while read -u 3 line; do
12     if [ "$line" = "" ]; then
13         data+=("$cur_data")
14         seperator=""
15         cur_data=""
16         continue
17     fi
18     cur_data="${cur_data}${seperator}$line"
19     seperator=" "
20 done
21
22 # on the last line, if cur_data isn't empty, add that to the array
23 if [ "$cur_data" != "" ]; then
24     data+=("$cur_data")
25 fi
26
27 verify_data() {
28     local -n record=$1
29
30     for field in ${required_fields[@]}; do
31         if ! [ ${kvp[$field]+a} ]; then
32             exit 1
33         fi
34     done
35
36     exit 0
37 }
38
39 for (( i=0; i<${#data[@]}; i++ )); do
40     record="${data[$i]}"
41     declare -A kvp
42     for field in $record; do
43         key=${field%:*}
44         value=${field#*:}
45         kvp[$key]=$value
46     done
47     if ( verify_data kvp ); then
48         valid_count=$((valid_count+1))
49     fi
50     unset kvp
51 done
52
53 echo "$valid_count valid entries"