blob: 97fcd9c1d8c79e4107721d0bfb754436a3a0815b (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
|