performance improvements; no more string conversions or lookups in the map
This commit is contained in:
parent
9d406c2d22
commit
353d5e92c9
31
15/main.go
31
15/main.go
@ -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
|
||||||
}
|
}
|
||||||
|
|
||||||
for {
|
|
||||||
i := len(numbers) - 1
|
i := len(numbers) - 1
|
||||||
lastNumber := numbers[i]
|
lastNumber, _ := strconv.Atoi(numbers[i])
|
||||||
if len(numbers) == 30000000 {
|
for {
|
||||||
fmt.Println(numbers[30000000-1])
|
if seen[lastNumber] == 30000000-1 {
|
||||||
|
fmt.Println(lastNumber)
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user