diff --git a/day/02/part2.sh b/day/02/part2.sh index 22ad5a6..ff768bd 100755 --- a/day/02/part2.sh +++ b/day/02/part2.sh @@ -49,6 +49,44 @@ function check_is_safe() { 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]" @@ -56,56 +94,22 @@ while read -r l; do read -ra line_split <<< "${l}" unset IFS - # start with the first val - prev_val="${line_split[0]}" + is_safe=$(check_list "${line_split[@]}") - is_safe=2 - - # if positive, going up, if negative, going down! - is_up_down="$((line_split[1] - line_split[0]))" - - safety_trigger=1 - - if [[ "${is_up_down}" -ge 0 ]]; then - echo "Initially going up" - else - echo "Initially going down" - fi - - for idx in "${!line_split[@]}"; do - [[ "${idx}" -eq 0 ]] && continue - echo "index $idx" - v="${line_split[${idx}]}" - 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=$((is_safe - 1)) - fi - - if [[ "${test_is_safe}" -eq 0 ]] && [[ "${safety_trigger}" -eq 1 ]]; then - # but we let 1 happen if the trigger hasnt... triggered - safety_trigger=0 - if [[ "${idx}" -eq 1 ]]; then - # we may have to re-calculate is_up_down! - is_up_down="$((line_split[2] - line_split[0]))" - echo "allowing flip up/down" + 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 - echo "-------------------" - echo "allowing 1 failure!" - echo "-------------------" - else - # we skip the re-assign once to 'skip' a number - prev_val=$v - fi - done - - if [[ "${is_safe}" -gt 0 ]]; then - safe_count=$((safe_count + 1)) + done fi + + safe_count=$((safe_count + is_safe)) done <"$FILE_IN" echo "final safe count ${safe_count}"