aoc/5/2/solution.sh

98 lines
2.4 KiB
Bash
Raw Normal View History

2023-12-06 14:00:03 +01:00
#!/usr/bin/env bash
2023-12-06 18:06:47 +01:00
# INCOMPLETE
2023-12-06 14:00:03 +01:00
set -o errexit
set -o nounset
set -o pipefail
if [[ "${TRACE-0}" == "1" ]]; then
set -o xtrace
fi
INPUT_FILE="$1"
2023-12-06 18:06:47 +01:00
gen_maps ()
2023-12-06 14:00:03 +01:00
{
2023-12-06 18:06:47 +01:00
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}")
2023-12-06 14:00:03 +01:00
done
}
2023-12-06 18:06:47 +01:00
gen_seed_pairs ()
2023-12-06 14:00:03 +01:00
{
2023-12-06 18:06:47 +01:00
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
2023-12-06 14:00:03 +01:00
}
2023-12-06 18:06:47 +01:00
get_lowest ()
2023-12-06 14:00:03 +01:00
{
2023-12-06 18:06:47 +01:00
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[@]}")
2023-12-06 14:00:03 +01:00
}
main ()
{
declare -a maps=()
2023-12-06 18:06:47 +01:00
declare -a seed_pairs=() # start,end
gen_maps
gen_seed_pairs
get_lowest
echo "${#seed_pairs[@]}"
for i in "${seed_pairs[@]}"; do
echo "$i"
2023-12-06 14:00:03 +01:00
done
2023-12-06 18:06:47 +01:00
# 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
2023-12-06 14:00:03 +01:00
}
main