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

113 lines
2.5 KiB
Bash
Raw Normal View History

2024-12-15 15:50:45 +08:00
#!/usr/bin/env bash
MAP_FILE=input-map
DIRECTIONS_FILE=input-movements
MAP_WIDTH=$(( $( head -1 "$MAP_FILE" | wc -c ) -1 ))
#MAP_HEIGHT=$( < "$MAP_FILE" wc -l )
# Load map
read -r -a MAP_ARRAY <<< "$( < "$MAP_FILE" paste -s -d "" | sed -E 's/(.)(.)/\1 \2 /g' )"
printf "%s " "${MAP_ARRAY[@]}" | fold -w $(( MAP_WIDTH * 2 ))
printf "\n"
MAP_LEN=${#MAP_ARRAY[@]}
# Count boxes
BOX_COUNT=0
for (( i=0; i<MAP_LEN; i++ ))
do
if [[ ${MAP_ARRAY[i]} == "O" ]]
then
(( BOX_COUNT++ ))
fi
done
printf "Box count: %s\n" "$BOX_COUNT"
# Get robot position
for (( i=0; i<MAP_LEN; i++ ))
do
if [[ ${MAP_ARRAY[i]} == "@" ]]
then
ROBOT_POSITION=$i
break
fi
done
printf "Robot position : %s\n" "$ROBOT_POSITION"
# Hardcode direction values
UP=$(( - MAP_WIDTH ))
DOWN=$MAP_WIDTH
LEFT=-1
RIGHT=1
# Iterate through directions
while read -r DIRECTION
do
# Interpret directions
if [[ $DIRECTION == "^" ]]
then
DIRECTION_VALUE=$UP
elif [[ $DIRECTION == "v" ]]
then
DIRECTION_VALUE=$DOWN
elif [[ $DIRECTION == "<" ]]
then
DIRECTION_VALUE=$LEFT
elif [[ $DIRECTION == ">" ]]
then
DIRECTION_VALUE=$RIGHT
fi
NEXT_POSITION=$(( ROBOT_POSITION + DIRECTION_VALUE ))
if [[ ${MAP_ARRAY[$NEXT_POSITION]} == "O" ]] # Box in front
then
END_POSITION=$(( NEXT_POSITION + DIRECTION_VALUE ))
while [[ ${MAP_ARRAY[$END_POSITION]} == "O" ]]
do
(( END_POSITION+=DIRECTION_VALUE ))
done
if [[ ${MAP_ARRAY[$END_POSITION]} == '#' ]]
then
: # Boxes are stacked up against wall
elif [[ ${MAP_ARRAY[$END_POSITION]} == "." ]]
then
# Move the box
MAP_ARRAY[END_POSITION]=O
MAP_ARRAY[NEXT_POSITION]=.
# Move the robot
MAP_ARRAY[ROBOT_POSITION]=.
ROBOT_POSITION=$NEXT_POSITION
MAP_ARRAY[ROBOT_POSITION]=@
fi
elif [[ ${MAP_ARRAY[$NEXT_POSITION]} == "#" ]] # Wall in front, do nothing
then
continue
elif [[ ${MAP_ARRAY[$NEXT_POSITION]} == "." ]] # Empty space, move forward
then
# Move the robot
MAP_ARRAY[ROBOT_POSITION]=.
ROBOT_POSITION=$NEXT_POSITION
MAP_ARRAY[ROBOT_POSITION]=@
fi
done <<< "$( < "$DIRECTIONS_FILE" sed -E 's/(.)(.)/\1 \2 /g' | tr ' ' '\n' )"
printf "%s " "${MAP_ARRAY[@]}" | fold -w $(( MAP_WIDTH * 2 ))
printf "\n"
# Calculate GPS values for boxes
SUM=0
BOX_COUNT=0
for (( i=0; i<MAP_LEN; i++ ))
do
if [[ ${MAP_ARRAY[i]} == "O" ]]
then
(( BOX_COUNT++ ))
(( SUM+=( (i / MAP_WIDTH) * 100 ) )) # Add Y axis
(( SUM+=( i % MAP_WIDTH ) )) # Add x axis
fi
done
printf "Sum: %s\n" "$SUM"
printf "Box count: %s\n" "$BOX_COUNT"