complete day 2, part 2

This commit is contained in:
ida schmidt 2024-12-02 20:00:32 +00:00
parent 45f584ea73
commit b24a27c72d

55
day2/part 2.sh Executable file
View file

@ -0,0 +1,55 @@
#!/usr/bin/env bash
test_report(){
# count numbers 1 through 3 in the list of differences
numerality=`echo ${report_diff[@]} \
| sed 's/-//g'| grep -w -o "[1-3]" | wc -l`
# test if each number is 1 through 3
if [ $numerality -eq $diff_length ]; then
# count minus signs
negativity=`echo ${report_diff[@]} \
| grep -o "-" | wc -l`
# we only want to see if all the signs are the same
if [ $negativity -eq 0 ] || [ $negativity -eq $diff_length ]; then
unset report_diff[@]
return 0
fi
fi
unset report_diff[@]
return 1
}
report_to_diff(){
declare -g -a report
# assign each number to an array element
report=( `echo $1` )
diff_length=$((${#report[@]}-1))
declare -g -a report_diff
# find differences between levels in report
for i in `seq 1 $diff_length`; do
report_diff+="`bc <<<${report[$i]}-${report[$i-1]}` "
done
}
problem_dampener(){
levels=$((`echo $REPLY | grep -o ' ' | wc -l`+1))
# try each report with a level removed, until we find one that's safe
for level in `seq 1 $levels`; do
dampened_report="`echo $REPLY | cut --complement -d ' ' -f $level`"
report_to_diff "$dampened_report"
if test_report; then
return 0
fi
done
return 1
}
while read; do
report_to_diff "$REPLY"
if test_report; then
(( safe++ ))
elif problem_dampener; then
(( safe++ ))
fi
done < <(cat input)
echo $safe