Optimize bash solution for day 2.

Now loops less (only n(n-1) / 2 times instead of n^2), doesn't call echo
spuriously, and doesn't use tail/head anymore. Results in 75% less
runtime, so I'll take it.
This commit is contained in:
2017-12-11 00:08:57 +01:00
parent b40e549245
commit b368355201

View File

@@ -4,13 +4,13 @@ sum1=0
sum2=0
while read -r line; do
sorted=$(echo "$line" | xargs -n 1 echo | sort -n)
((sum1 += $(echo "$sorted" | tail -n 1) - $(echo "$sorted" | head -n 1)))
sorted=$(tr '\t' '\n' <<< "$line" | sort -n)
((sum1 += ${sorted##*$'\n'} - ${sorted%%$'\n'*}))
for a in $sorted; do
for b in $sorted; do
if [[ $a -le $b ]]; then
continue
break
fi
if [[ $((a % b)) -eq 0 ]]; then