Skip to content

Commit 6b813be

Browse files
committed
18: Fix part 1 and improve speed
Part 1 was giving the wrong result because of globbing Rewritten to use bash regex instead of recursive grep -o (5-6x speedup) Part 2 made a fast one-liner
1 parent 020790f commit 6b813be

File tree

2 files changed

+13
-27
lines changed

2 files changed

+13
-27
lines changed

18.sh

Lines changed: 12 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#! /usr/bin/env bash
22
IFS=$'\n'
3-
set -f # globbing off
3+
set -o noglob
44
A=($(< ${1:-18.txt}))
55
c() {
66
local i sum=0 op='+'
@@ -11,34 +11,20 @@ c() {
1111
sum=$((sum$op$i))
1212
fi
1313
done
14-
#echo "c: ${@//[()]} = $sum " >&2
14+
#echo "c: ${*//[()]} = $sum " >&2
1515
echo ${sum}
1616
}
1717

18-
r() { # TODO: Try bash regex for speed
19-
local line="$1" k n total
20-
local inner=($(echo "$line"| grep -o "([^()]*)"))
21-
while [[ "${#inner[@]}" != 0 ]]; do
22-
for k in "${inner[@]}"; do
23-
n=$(c "$k")
24-
line="${line/$k/$n}"
25-
done
26-
line=$(r "$line")
27-
inner=($(echo "$line"| grep -o "([^()]*)"))
18+
IFS=$' \t\n'
19+
regex="\([^()]*\)"
20+
sum=""
21+
for line in "${A[@]}"; do
22+
while [[ "$line" =~ $regex ]]; do
23+
k=${BASH_REMATCH[0]}
24+
n=$(c "$k")
25+
line="${line/${k//\*/\\*}/$n}" # stupid globbing
2826
done
29-
total=$(c "$line")
30-
echo $total
31-
}
32-
B=()
33-
for i in "${A[@]}"; do
34-
B+=($(r "$i"))
27+
sum+=+$(c "$line")
3528
done
36-
sum=$(echo ${B[*]} | tr ' ' '+')
3729
echo "18A: $((sum))"
38-
sum=""
39-
for i in "${A[@]}"; do
40-
k="(${i//\*/)*(})"
41-
sum+="+$((k))"
42-
done
43-
IFS='+'
44-
echo "18B: $(($sum))"
30+
echo "18B: $(($(printf "+(%s)" "${A[@]//\*/)*(}")))"

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ Description of what I'm doing. Contains spoilers....
9191

9292
### 18.sh
9393
Have to turn glob off, or \* will be replaced with all files in directory.
94-
1. Recursive grep to find a brackets that don't contain inner brackets. Calculate those. Replace the whole bracket with calculated result. Repeat. Slow but works.
94+
1. Bash regex to find a bracket that doesn't contain inner brackets. Calculate that. Replace the whole bracket with result. Repeat until no brackets remain. Slow, but faster than grep -o.
9595
2. Just replace "\*" with ")\*(" to change the precedence. Add "(" and ")" to the ends to close off the brackets.
9696

9797
### 19.sh

0 commit comments

Comments
 (0)