Files
advent-of-code-2021/22/02.sh
2021-12-22 12:50:20 +01:00

107 lines
2.6 KiB
Bash
Executable File

#!/bin/bash
declare -A cores
while read line; do
if [[ ${line:0:2} == "on" ]]; then
new_value=1
else
new_value=0
fi
t=${line#*x=}
t=${t%%,*}
x_1=${t%\.\.*}
x_2=${t#*\.\.}
t=${line#*y=}
t=${t%%,*}
y_1=${t%\.\.*}
y_2=${t#*\.\.}
t=${line#*z=}
t=${t%%,*}
z_1=${t%\.\.*}
z_2=${t#*\.\.}
for core in ${!cores[@]}; do
coords=( ${core//,/ } )
if [ $x_1 -gt ${coords[0]} ]; then
overlap_x_1=$x_1
else
overlap_x_1=${coords[0]}
fi
if [ $x_2 -gt ${coords[1]} ]; then
overlap_x_2=${coords[1]}
else
overlap_x_2=$x_2
fi
if [ $y_1 -gt ${coords[2]} ]; then
overlap_y_1=$y_1
else
overlap_y_1=${coords[2]}
fi
if [ $y_2 -gt ${coords[3]} ]; then
overlap_y_2=${coords[3]}
else
overlap_y_2=$y_2
fi
if [ $z_1 -gt ${coords[4]} ]; then
overlap_z_1=$z_1
else
overlap_z_1=${coords[4]}
fi
if [ $z_2 -gt ${coords[5]} ]; then
overlap_z_2=${coords[5]}
else
overlap_z_2=$z_2
fi
if [ $overlap_x_2 -ge $overlap_x_1 ] && [ $overlap_y_2 -ge $overlap_y_1 ] \
&& [ $overlap_z_2 -ge $overlap_z_1 ]; then
if [ ${coords[0]} -lt $overlap_x_1 ]; then
cores[${coords[0]},$((overlap_x_1-1)),${coords[2]},${coords[3]},${coords[4]},${coords[5]}]=1
fi
if [ ${coords[1]} -gt $overlap_x_2 ]; then
cores[$((overlap_x_2+1)),${coords[1]},${coords[2]},${coords[3]},${coords[4]},${coords[5]}]=1
fi
if [ ${coords[2]} -lt $overlap_y_1 ]; then
cores[$overlap_x_1,$overlap_x_2,${coords[2]},$((overlap_y_1-1)),${coords[4]},${coords[5]}]=1
fi
if [ ${coords[3]} -gt $overlap_y_2 ]; then
cores[$overlap_x_1,$overlap_x_2,$((overlap_y_2+1)),${coords[3]},${coords[4]},${coords[5]}]=1
fi
if [ ${coords[4]} -lt $overlap_z_1 ]; then
cores[$overlap_x_1,$overlap_x_2,$overlap_y_1,$overlap_y_2,${coords[4]},$((overlap_z_1-1))]=1
fi
if [ ${coords[5]} -gt $overlap_z_2 ]; then
cores[$overlap_x_1,$overlap_x_2,$overlap_y_1,$overlap_y_2,$((overlap_z_2+1)),${coords[5]}]=1
fi
unset cores[$core]
fi
done
if [ $new_value -eq 1 ]; then
cores[$x_1,$x_2,$y_1,$y_2,$z_1,$z_2]=$new_value
fi
done
n_cores_on=0
for core in ${!cores[@]}; do
coords=( ${core//,/ } )
x=$((coords[1]-coords[0]))
if [ $x -lt 0 ]; then
x=${x#-}
fi
y=$((coords[3]-coords[2]))
if [ $y -lt 0 ]; then
y=${y#-}
fi
z=$((coords[5]-coords[4]))
if [ $z -lt 0 ]; then
z=${z#-}
fi
x=$((x+1))
y=$((y+1))
z=$((z+1))
n_cores_on=$((n_cores_on+x*y*z*${cores[$core]}))
done
echo $n_cores_on