day 16, exercise 2 (bash version)

This commit is contained in:
2021-01-11 17:27:26 +01:00
parent ccfbf5322a
commit aff61f5e5c
4 changed files with 103 additions and 1 deletions

View File

@@ -20,7 +20,7 @@ ex1:
@#$(TIME) ex1-c 2020 < $(INPUT) 2>&1 @#$(TIME) ex1-c 2020 < $(INPUT) 2>&1
ex2: ex2:
@#$(TIME) ex1.bash 30000000 < $(INPUT) 2>&1 @$(TIME) ex2.bash < $(INPUT) 2>&1
@#$(TIME) ex1-c 30000000 < $(INPUT) 2>&1 @#$(TIME) ex1-c 30000000 < $(INPUT) 2>&1
clean: clean:

11
day16/TEST2.txt Normal file
View File

@@ -0,0 +1,11 @@
class: 0-1 or 4-19
row: 0-5 or 8-19
seat: 0-13 or 16-19
your ticket:
11,12,13
nearby tickets:
3,9,18
15,1,5
5,14,9

View File

@@ -20,6 +20,7 @@ while read -r line; do
elif [[ $line != "" ]]; then elif [[ $line != "" ]]; then
if ((state == 2)); then if ((state == 2)); then
for i in ${line//,/ }; do for i in ${line//,/ }; do
# shellcheck disable=SC2100
[[ ! -v valid[$i] ]] && res=res+i [[ ! -v valid[$i] ]] && res=res+i
done done
fi fi

90
day16/ex2.bash Executable file
View File

@@ -0,0 +1,90 @@
#!/bin/bash
#
# ex2.bash: Advent2020 game, day 16/game 2.
CMD=${0##*/}
shopt -s extglob
declare -a valid=() myticket=() keys=() values=() match=()
declare -A position=()
declare -i state=0 res=1 curkey=0 curticket=0
while read -r line; do
if [[ $line =~ ^([a-z ]+)\:\ ([0-9]+)-([0-9]+)([a-z ]+)([0-9]+)-([0-9]+)$ ]]; then
# valid ranges
keys[$curkey]="${BASH_REMATCH[1]}"
n1=$(seq -s" " "${BASH_REMATCH[2]}" "${BASH_REMATCH[3]}")
n2=$(seq -s" " "${BASH_REMATCH[5]}" "${BASH_REMATCH[6]}")
for i in $n1 $n2; do
valid[$i]=1
done
values[$curkey]="${n1[*]} ${n2[*]}"
((curkey++))
elif [[ $line =~ (your ticket:|nearby tickets) ]]; then
# next section
((state++))
elif [[ $line =~ [0-9,]+ ]]; then
# shellcheck disable=SC2206
numbers=( ${line//,/ } )
case $state in
1) # my ticket
# shellcheck disable=SC2206
myticket=( ${numbers[@]} )
# initialize possible matches array: all
for ((i=0; i<curkey; ++i)); do
for ((j=0; j<${#numbers[@]}; ++j)); do
match[$j]+=" $i "
done
done
;;
2) # other tickets
#printf "ticket %d\n" "$curticket"
for i in ${numbers[*]}; do
[[ ! -v valid[$i] ]] && continue 2
done
for ((j=0; j<curkey; ++j)); do
for ((i=0; i<${#numbers[@]}; ++i)); do
num=" ${numbers[$i]} "
[[ " ${values[$j]} " =~ $num ]] && continue
match[$j]=${match[$j]// $i /}
done
done
((curticket++))
;;
esac
fi
done
end=0
while ((end==0)); do
end=1
for ((i=0; i<${#match[@]}; ++i)); do
[[ -n ${position[$i]} ]] && continue
# shellcheck disable=SC2206
array=( ${match[$i]} )
if (( ${#array[@]} == 1 )); then
cur=${array[0]}
position[$i]=$cur
for ((j=0; j<${#match[@]}; ++j)); do
((j != i)) && match[$j]=${match[$j]// $cur /}
done
end=0
break
fi
done
done
for ((i=0; i<${#keys[@]}; ++i )); do
if [[ ${keys[$i]} =~ "departure" ]]; then
pos=${match[$i]}
(( res *= ${myticket[$pos]} ))
fi
done
printf "%s : res=%d\n" "$CMD" "$res"
exit 0