mirror of
https://github.com/bertptrs/adventofcode.git
synced 2025-12-25 21:00:31 +01:00
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:
@@ -4,13 +4,13 @@ sum1=0
|
|||||||
sum2=0
|
sum2=0
|
||||||
|
|
||||||
while read -r line; do
|
while read -r line; do
|
||||||
sorted=$(echo "$line" | xargs -n 1 echo | sort -n)
|
sorted=$(tr '\t' '\n' <<< "$line" | sort -n)
|
||||||
((sum1 += $(echo "$sorted" | tail -n 1) - $(echo "$sorted" | head -n 1)))
|
((sum1 += ${sorted##*$'\n'} - ${sorted%%$'\n'*}))
|
||||||
|
|
||||||
for a in $sorted; do
|
for a in $sorted; do
|
||||||
for b in $sorted; do
|
for b in $sorted; do
|
||||||
if [[ $a -le $b ]]; then
|
if [[ $a -le $b ]]; then
|
||||||
continue
|
break
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ $((a % b)) -eq 0 ]]; then
|
if [[ $((a % b)) -eq 0 ]]; then
|
||||||
|
|||||||
Reference in New Issue
Block a user