performance improvements; no more string conversions or lookups in the map

This commit is contained in:
David 2020-12-15 21:41:07 -05:00
parent 9d406c2d22
commit 353d5e92c9

View File

@ -4,6 +4,7 @@ import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
"time"
)
@ -55,32 +56,30 @@ func partTwo() {
// caching implementation. It's still slow, but it at least finishes...!
scanner.Scan()
numbers := strings.Split(scanner.Text(), ",")
seen := make(map[string]int)
seen := make(map[int]int)
// load in numbers
for i, v := range numbers[:len(numbers)-1] {
seen[v] = i
j, _ := strconv.Atoi(v)
seen[j] = i
}
for {
i := len(numbers) - 1
lastNumber := numbers[i]
if len(numbers) == 30000000 {
fmt.Println(numbers[30000000-1])
lastNumber, _ := strconv.Atoi(numbers[i])
for {
if seen[lastNumber] == 30000000-1 {
fmt.Println(lastNumber)
return
}
if v, ok := seen[lastNumber]; !ok {
// never seen that before
numbers = append(numbers, "0")
seen[lastNumber] = i
continue
} else {
if v, ok := seen[lastNumber]; ok {
// a number matched; insert the difference between the last number and when we last saw it
n := fmt.Sprintf("%d", i-v)
numbers = append(numbers, n)
seen[lastNumber] = i
continue
lastNumber = i - v
} else {
// never seen that before
seen[lastNumber] = i
lastNumber = 0
}
i = i + 1
}
}