Skip to content

Instantly share code, notes, and snippets.

@bogovicj
Last active December 16, 2024 22:38
Show Gist options
  • Save bogovicj/e1e2d7901dbb960ffdee1a6b39a91c73 to your computer and use it in GitHub Desktop.
Save bogovicj/e1e2d7901dbb960ffdee1a6b39a91c73 to your computer and use it in GitHub Desktop.
Advent of code 2024 part 6a (in bash
#!/bin/bash
function initialize() {
# Make sure the guard is oriented to the right
#
# I happen to know that the guard is oriented up for my input
# So the commands below do a clock-wise rotation
# (this would be easy enough to generalize)
tac $state > tmp
state="tmp"
transpose | sed 's/\^/>/' > states/t0000
state="states/t0000"
rm tmp
}
function transpose() {
# Transpose the map (rows become columns, columns become rows)
N=$(wc -L $state | awk '{print $1}')
for i in $(seq 1 $N); do
cut -c$i $state | tr '\n' 'M' | sed 's/M//g'; echo ""
done
}
function checkTurn() {
# Returns a non-empty output if the guard turns
grep '>#' $state
}
function checkDone() {
# Returns a non-empty output if the guard is about to exit the map
grep '>$' $state
}
function turn() {
# Make the guard turn right (by rotating the map counter clock wise)
# A counter clock wise rotation is the same a a transposition followed by a horizontal flip
transpose | tac >> $nextState
}
function step() {
# Make the guard take one step forward
sed -e 's/>./X>/g' $state > $nextState
}
function finish() {
# Last step, remove the guard from the map
sed -e 's/>/X/g' $state > $nextState
}
function count() {
# Count the visited locations (X's)
n=$(grep -on 'X' $state | wc -l)
}
state=$1 # current state
nt=$2 # max number of time steps
initialize
# Current and next time points
t=0
tn=$((t+1))
n=0
for t in $(seq 0 $nt);
do
echo "t: $t"
tn=$((t+1))
state=$(printf states/t%04d $t)
nextState=$(printf states/t%04d $tn)
if [[ ! -z $(checkDone) ]]; then
finish
echo " DONE"
break
elif [[ ! -z $(checkTurn) ]]; then
turn
else
step
fi
done
state=$nextState
count
echo ""
echo "FINAL COUNT: $n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment