aoc/5/2/solution.sh

98 lines
2.4 KiB
Bash
Executable File

#!/usr/bin/env bash
# INCOMPLETE
set -o errexit
set -o nounset
set -o pipefail
if [[ "${TRACE-0}" == "1" ]]; then
set -o xtrace
fi
INPUT_FILE="$1"
gen_maps ()
{
local map_count paragraph_num lines name
map_count=$(awk -v RS= 'END {print NR}' "${INPUT_FILE}")
map_count=$((map_count-1)) # one paragraph in file is seeds
for ((i=1; i<=map_count; i++)); do
paragraph_num=$((i+1)) # number of paragraph in input file
lines="$(awk -v RS= "{if(NR == ${paragraph_num}) print}" "${INPUT_FILE}"| tail -n +2)"
name="$(awk -v RS= "{if(NR == ${paragraph_num}) print}" "${INPUT_FILE}" | head -n 1 | cut -d ' ' -f 1 | tr - _)"
declare -n array="${name}"
while read -r line; do
array+=("${line}")
done <<< "${lines}"
maps+=("${name}")
done
}
gen_seed_pairs ()
{
local seed_count pair_count i_start i_length start length end
IFS=" " read -r -a seeds <<< "$(grep seeds "${INPUT_FILE}" | cut -d ' ' -f 2-)"
seed_count="${#seeds[@]}"
pair_count=$((seed_count/2))
for ((i=0; i<pair_count; i++)); do
i_start=$((i*2))
i_length=$((i*2+1))
start=${seeds[${i_start}]}
length=${seeds[${i_length}]}
end=$((start+length-1))
seed_pairs+=("${start},${end}")
done
}
get_lowest ()
{
local dest_start source_start length dest_end source_end
for n in "${maps[@]}"; do
declare -a new_pairs=()
declare -n map="${n}"
for line in "${map[@]}"; do
dest_start="$(cut -d ' ' -f 1 <<< "${line}")"
source_start="$(cut -d ' ' -f 2 <<< "${line}")"
length="$(cut -d ' ' -f 3 <<< "${line}")"
dest_end=$((dest_start+length-1))
source_end=$((source_start+length-1))
if [[ ${#new_pairs[@]} -eq 0 ]]; then
declare -n source_pairs="seed_pairs"
else
declare -n source_pairs="new_pairs"
fi
for ((i=0; i<${#source_pairs[@]}; i++)); do
interim_pairs+=(source)
seed_start="$(cut -d ',' -f 1 <<< "${source_pairs[${i}]}")"
seed_end="$(cut -d ',' -f 2 <<< "${source_pairs[${i}]}")"
done
done
done
declare -a new_pairs
seed_pairs=("${new_pairs[@]}")
}
main ()
{
declare -a maps=()
declare -a seed_pairs=() # start,end
gen_maps
gen_seed_pairs
get_lowest
echo "${#seed_pairs[@]}"
for i in "${seed_pairs[@]}"; do
echo "$i"
done
# for map in "${maps[@]}"; do
# declare -n array="${map}"
# echo "printing ${map} ${#array[@]}"
# for ((i=0; i<${#array[@]}; i++)); do
# echo "${array[${i}]}"
# done
# done
}
main