Advent-Of-Code-2024/day/02/part2.sh
Tom Bloor fa3a8afb29
win
2024-12-21 23:35:57 +00:00

115 lines
2.3 KiB
Bash
Executable file

#! /bin/bash
#set -x
FILE_IN="${1}"
safe_count=0
function debug_echo() {
echo "$@" 1>&2
}
function check_is_safe() {
local is_up_down="${1}"
local first_val="${2}"
local second_val="${3}"
local fun_is_safe=1
prev_diff=$((first_val - second_val))
debug_echo "diff ${prev_diff}"
if [[ "${prev_diff}" -gt 0 ]]; then
debug_echo "going up"
if [[ "${is_up_down}" -le 0 ]]; then
debug_echo "wrong direction"
fun_is_safe=0
fi
else
debug_echo "going down"
if [[ "${is_up_down}" -ge 0 ]]; then
debug_echo "wrong direction"
fun_is_safe=0
fi
fi
if [[ "${prev_diff#-}" -le 0 ]] || [[ "${prev_diff#-}" -ge 4 ]]; then
debug_echo "outside range"
fun_is_safe=0
fi
if [[ "${fun_is_safe}" -ne 0 ]]; then
debug_echo "safe"
else
debug_echo "unsafe"
fi
echo "${fun_is_safe}"
}
function check_list() {
local line_split=("$@")
# start with the first val
prev_val="${line_split[0]}"
local is_safe=1
# if positive, going up, if negative, going down!
is_up_down="$((line_split[1] - line_split[0]))"
if [[ "${is_up_down}" -ge 0 ]]; then
debug_echo "Initially going up"
else
debug_echo "Initially going down"
fi
for idx in "${!line_split[@]}"; do
[[ "${idx}" -eq 0 ]] && continue
debug_echo "index $idx"
v="${line_split[${idx}]}"
debug_echo "checking [${v}] against previous [${prev_val}]"
test_is_safe=$(check_is_safe "${is_up_down}" "${v}" "${prev_val}")
debug_echo "safe val ${test_is_safe}"
if [[ "${test_is_safe}" -eq 0 ]]; then
# normally we fail this set
is_safe=0
fi
# we skip the re-assign once to 'skip' a number
prev_val=$v
done
echo "${is_safe}"
}
while read -r l; do
echo "reading new line [$l]"
IFS=" "
read -ra line_split <<< "${l}"
unset IFS
is_safe=$(check_list "${line_split[@]}")
if [[ "${is_safe}" -eq 0 ]]; then
for idx in "${!line_split[@]}"; do
# remove each item from the set and try again
new_line_split=("${line_split[@]:0:${idx}}" "${line_split[@]:$((idx + 1))}")
echo "${new_line_split[@]}"
is_retry_safe=$(check_list "${new_line_split[@]}")
if [[ "${is_retry_safe}" -gt 0 ]]; then
is_safe=1
break
fi
done
fi
safe_count=$((safe_count + is_safe))
done <"$FILE_IN"
echo "final safe count ${safe_count}"