diff options
author | Christian Segundo | 2024-12-02 09:30:01 +0100 |
---|---|---|
committer | Christian Segundo | 2024-12-02 09:30:01 +0100 |
commit | 973ca9090337d17207e341b70119963022e2ddc9 (patch) | |
tree | d5c8eb20cc15fc124a3abcc3f859bc09b77879c1 /1.sh | |
parent | 241b0b80875a1428b3d0c98ab83405fd2667f23d (diff) | |
download | advent-of-code-2024-973ca9090337d17207e341b70119963022e2ddc9.tar.gz |
add day 2
Diffstat (limited to '1.sh')
-rw-r--r-- | 1.sh | 64 |
1 files changed, 64 insertions, 0 deletions
@@ -0,0 +1,64 @@ +#!/usr/bin/env bash + +function smallest { + local -n arr=$1 + smallest=${arr[0]} + for i in "${!arr[@]}"; do + [[ -n ${arr[i]} ]] || continue + [[ ${arr[i]} -lt $smallest ]] && smallest=${arr[i]} + done + echo "$smallest" +} + +function delete_a { + local value=$1 deleted=false new_arr=() + local -n arr=$2 + for i in "${arr[@]}"; do + [[ $deleted == true ]] && new_arr+=($i) && continue + [[ $i -ne $value ]] && new_arr+=($i) && continue + deleted=true + done + echo "${new_arr[@]}" +} + +function occurences { + local value=$1 count=0 + local -n arr=$2 + for i in "${arr[@]}"; do + [[ $i -eq $value ]] && count=$((count + 1)) + done + echo "$count" +} + +one=() +two=() +total_distance=0 +total_count=0 + +while read -r line; do + one+=("${line%% *}") + two+=("${line##* }") +done <./1-input.txt + +for i in $(seq 0 $((${#one[@]} - 1))); do + n="${one[i]}" + total_count=$((total_count + n * $(occurences "$n" two))) +done + +for i in $(seq 1 ${#one[@]}); do + smallest_one=$(smallest one) + smallest_two=$(smallest two) + one=($(delete_a $smallest_one one)) + two=($(delete_a $smallest_two two)) + distance=$((smallest_one - smallest_two)) + if [[ $distance -lt 0 ]]; then + distance=$((distance * -1)) + fi + total_distance=$((total_distance + distance)) +done + +echo "puzzle 1: $total_distance" +echo "puzzle 2: $total_count" + +# puzzle 1: 2285373 +# puzzle 2: 21142653 |