From 241b0b80875a1428b3d0c98ab83405fd2667f23d Mon Sep 17 00:00:00 2001 From: Christian Segundo Date: Mon, 2 Dec 2024 03:17:12 +0100 Subject: add day 1 --- 1/1.sh | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 1/1.sh (limited to '1/1.sh') diff --git a/1/1.sh b/1/1.sh new file mode 100644 index 0000000..a9ca200 --- /dev/null +++ b/1/1.sh @@ -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 <./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 -- cgit v1.2.3