aoc/5/2/solution.sh

96 lines
2.5 KiB
Bash
Executable File

#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
if [[ "${TRACE-0}" == "1" ]]; then
set -o xtrace
fi
cd "$(dirname "$0")"
INPUT_FILE="$1"
get_seed_pairs ()
{
IFS=" " read -r -a seeds <<< "$(grep seeds "${INPUT_FILE}" | cut -d ' ' -f 2-)"
seed_count="${#seeds[@]}"
pairs=$((seed_count/2))
for ((i=0; i<pairs; i++)); do
j=$((i*2))
k=$((i*2+1))
seed_pairs[${seeds[${j}]}]="${seeds[${k}]}"
done
}
gen_map ()
{
# Generates files for given index of map in input file.
local paragraph map_name map_content
paragraph=$(($1+1)) # number of paragraph in input file
map_name=$(awk -v RS= "{if(NR == ${paragraph}) print}" "${INPUT_FILE}" | head -n 1 | cut -d ' ' -f 1)
map_content=$(awk -v RS= "{if(NR == ${paragraph}) print}" "${INPUT_FILE}"| tail -n +2)
echo "${map_content}" > "${map_name}.map"
maps+=("${map_name}.map")
}
map_seed ()
{
# Usage: map_seed MAP_FILE SEED_NUMBER
# Prints the mapping of the seed number in the give map.
local map seed dest_start source_start length diff
map="$1"
seed="$2"
while read -r line; do
dest_start=$(cut -d ' ' -f 1 <<< "${line}")
source_start=$(cut -d ' ' -f 2 <<< "${line}")
length=$(cut -d ' ' -f 3 <<< "${line}")
if [[ ${seed} -ge ${source_start} && ${seed} -le $((source_start+length-1)) ]]; then
diff=$((seed-source_start))
echo -n $((dest_start+diff))
return
fi
done < "${map}"
echo -n "${seed}" # no mapping
}
main ()
{
declare -A seed_pairs=()
declare -a maps=()
local map_count destination lowest length seed
get_seed_pairs
map_count=$(awk -v RS= 'END {print NR}' "${INPUT_FILE}")
map_count=$((map_count-1)) # one of the paragraphs in the file is seeds
for ((i=1; i<=map_count; i++)); do
gen_map "${i}"
done
lowest=''
for s in "${!seed_pairs[@]}"; do
length=${seed_pairs[${s}]}
echo "running from start ${s} length ${length}"
for ((z=0; z<length; z++)); do
y=$((s+z))
destination=''
for map in "${maps[@]}"; do
if [[ -z ${destination} ]]; then
destination=$(map_seed "${map}" "${y}")
else
destination=$(map_seed "${map}" "${destination}")
fi
done
if [[ -z ${lowest} ]]; then
lowest="${destination}"
elif [[ ${destination} -lt ${lowest} ]]; then
lowest="${destination}"
fi
echo "iteration ${z} seed ${y} destination ${destination}"
done
echo "interim lowest: ${lowest}"
done
echo "${lowest}"
rm -f ./*.map
}
main