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