summaryrefslogtreecommitdiff
path: root/1/1.sh
diff options
context:
space:
mode:
authorChristian Segundo2024-12-02 03:17:12 +0100
committerChristian Segundo2024-12-02 03:17:12 +0100
commit241b0b80875a1428b3d0c98ab83405fd2667f23d (patch)
tree580eda6040b347bbaa744fff09066b8034089931 /1/1.sh
downloadadvent-of-code-2024-241b0b80875a1428b3d0c98ab83405fd2667f23d.tar.gz
add day 1
Diffstat (limited to '1/1.sh')
-rw-r--r--1/1.sh64
1 files changed, 64 insertions, 0 deletions
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