Files
advent-of-code/2024/day-14/solution-1.sh

114 lines
2.7 KiB
Bash
Raw Normal View History

2024-12-14 17:29:07 +08:00
#!/usr/bin/env/bash
FILE=input
MAP_WIDTH=101
MAP_HEIGHT=103
MEDIAN_WIDTH=$(( MAP_WIDTH / 2 - 1 ))
if [[ $(( MAP_WIDTH % 2 )) -eq 1 ]]
then
(( MEDIAN_WIDTH++ ))
fi
MEDIAN_HEIGHT=$(( MAP_HEIGHT / 2 - 1 ))
if [[ $(( MAP_HEIGHT % 2 )) -eq 1 ]]
then
(( MEDIAN_HEIGHT++ ))
fi
printf "Median width: %s, median height: %s\n" "$MEDIAN_WIDTH" "$MEDIAN_HEIGHT"
# Load bot positions and velocities
read -r -a BOT_ARRAY <<< "$( grep -Eo '[-0-9]*' "$FILE" | paste -s -d " " )"
#printf "%s " "${BOT_ARRAY[@]}"
#printf "\n"
printf "Bot array size: %s\n" "${#BOT_ARRAY[@]}"
# Just move forward n seconds for every bot and save
# final positions
IFS=';'; read -r -a FINAL_ARRAY <<< "$(
SECONDS=100
for (( i=0; i<${#BOT_ARRAY[@]}; i+=4 ))
do
PX=${BOT_ARRAY[i]}
PY=${BOT_ARRAY[i+1]}
VX=${BOT_ARRAY[i+2]}
VY=${BOT_ARRAY[i+3]}
FINAL_X=$(( PX + ( VX * SECONDS ) ))
FINAL_Y=$(( PY + ( VY * SECONDS ) ))
printf "%s %s;" "$FINAL_X" "$FINAL_Y"
done <<< "${BOT_ARRAY[@]}"
)"
unset IFS
#printf "%s\n" "${FINAL_ARRAY[@]}" | head
printf "Final array size: %s\n" "${#FINAL_ARRAY[@]}"
# Get number of robots in each quadrant
Q1=0
Q2=0
Q3=0
Q4=0
ITER=9999
while read -r RAW_X RAW_Y
do
# Adjust positions to be on map
PX=$(( RAW_X % MAP_WIDTH ))
if [[ $PX -lt 0 ]]
then
PX=$(( MAP_WIDTH + PX ))
fi
PY=$(( RAW_Y % MAP_HEIGHT ))
if [[ $PY -lt 0 ]]
then
PY=$(( MAP_HEIGHT + PY ))
fi
# Check if negative positions, should not happen
if [[ $PX -lt 0 ]] || [[ $PY -lt 0 ]]
then
printf "Negative final position. PX: %s PY: %s\n" "$PX" "$PY"
fi
if [[ $PX -ge $MAP_WIDTH ]] || [[ $PY -ge $MAP_HEIGHT ]]
then
printf "Out of bounds. PX: %s PY: %s\n" "$PX" "$PY"
fi
printf "PX: %s PY: %s\n" "$PX" "$PY"
# Allocate robot to quadrant
if \
[[ $PX -ge 0 ]] && \
[[ $PX -lt $MEDIAN_WIDTH ]] && \
[[ $PY -ge 0 ]] && \
[[ $PY -lt $MEDIAN_HEIGHT ]] # Q1
then
(( Q1++ ))
elif \
[[ $PX -gt $MEDIAN_WIDTH ]] && \
[[ $PX -lt $MAP_WIDTH ]] && \
[[ $PY -ge 0 ]] && \
[[ $PY -lt $MEDIAN_HEIGHT ]] # Q2
then
(( Q2++ ))
elif \
[[ $PX -ge 0 ]] && \
[[ $PX -lt $MEDIAN_WIDTH ]] && \
[[ $PY -gt $MEDIAN_HEIGHT ]] && \
[[ $PY -lt $MAP_HEIGHT ]] # Q3
then
(( Q3++ ))
elif \
[[ $PX -gt $MEDIAN_WIDTH ]] && \
[[ $PX -lt $MAP_WIDTH ]] && \
[[ $PY -gt $MEDIAN_HEIGHT ]] && \
[[ $PY -lt $MAP_HEIGHT ]] # Q4
then
(( Q4++ ))
else
printf "Skipped in the median. PX: %s PY: %s\n" "$PX" "$PY"
fi
(( ITER-- ))
if [[ $ITER -eq 0 ]] ; then break ; fi
done <<< "$( printf "%s\n" "${FINAL_ARRAY[@]}" )"
# Calculate safety factor
SAFETY_FACTOR=$(( Q1 * Q2 * Q3 * Q4 ))
printf "Safety factor: %s\n" "$SAFETY_FACTOR"