]> git.sommitrealweird.co.uk Git - advent-of-code-2020.git/blob - day06/get_yes_counts_2.sh
Day 8 2020
[advent-of-code-2020.git] / day06 / get_yes_counts_2.sh
1 #!/bin/bash
2
3 set -u
4 set -e
5
6 declare -a group_questions
7
8 parse_file() {
9     exec 3<input.txt
10     declare -A questions
11     people_in_group=0
12     while read -u 3 line; do
13         #remove new lines
14         line=${line//$'\r'//}
15         line=${line//$'\n'//}
16         if [ "$line" == "" ]; then
17             question_string=""
18             for key in "${!questions[@]}"; do
19                 if [ $people_in_group -eq ${questions[$key]} ]; then
20                     question_string+="${key}"
21                 fi
22             done
23             group_questions+=($question_string)
24             unset questions
25             declare -A questions
26             people_in_group=0
27             continue
28         fi
29         people_in_group=$((people_in_group+1))
30         # go through each character of line
31         for (( a=0; a<${#line}; a++ )); do
32             question=${line:$a:1}
33             if [ ${questions["$question"]+a} ]; then
34                 questions["$question"]=$((${questions["$question"]}+1))
35             else
36                 questions["$question"]=1
37             fi
38         done
39     done
40
41     # last line was hit, so we need to process that too
42     question_string=""
43     for key in "${!questions[@]}"; do
44         if [ $people_in_group -eq ${questions[$key]} ]; then
45             question_string+="${key}"
46         fi
47     done
48     group_questions+=($question_string)
49     unset questions
50 }
51
52 parse_file
53
54 sum_of_groups=0
55 for group in "${group_questions[@]}"; do
56     sum_of_groups=$((sum_of_groups+${#group}))
57 done
58
59 echo "Sum of groups: $sum_of_groups"