From b3683552015a63d4be089d344c074ca885a1b53f Mon Sep 17 00:00:00 2001 From: Bert Peters Date: Mon, 11 Dec 2017 00:08:57 +0100 Subject: [PATCH] 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. --- 2017/day-02/solution.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/2017/day-02/solution.sh b/2017/day-02/solution.sh index 51517fd..ee62281 100755 --- a/2017/day-02/solution.sh +++ b/2017/day-02/solution.sh @@ -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