Skip to content

Commit

Permalink
refactor to use strings.LastIndex
Browse files Browse the repository at this point in the history
  • Loading branch information
devries committed Dec 1, 2023
1 parent fcd1611 commit 55e5eb0
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 15 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,5 @@ opportunity to experiment a bit with code generation.
through the names and finding the indecies of each word or digit (if any)
using `strings.Index`. Once you find a match you have to look for more
matches starting at the next character after your previous search and I did
have some indexing issues which I had to debug.
have some indexing issues which I had to debug. I later realized I could use
`strings.LastIndex` to make this much easier.
24 changes: 10 additions & 14 deletions day01p2/solution.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,20 +41,16 @@ func Solve(r io.Reader) any {
maxpos := -1

for k, v := range matchmap {
for i := 0; i < len(ln); i++ {
p := strings.Index(ln[i:], k)
if p == -1 {
break
}
if p+i < minpos {
first = v
minpos = p + i
}
if p+i > maxpos {
last = v
maxpos = p + i
}
i += p
p := strings.Index(ln, k)
if p != -1 && p < minpos {
first = v
minpos = p
}

p = strings.LastIndex(ln, k)
if p != -1 && p > maxpos {
last = v
maxpos = p
}
}
sum += 10*first + last
Expand Down

0 comments on commit 55e5eb0

Please sign in to comment.