First attempt at a faster / more efficient implementation. This is orders of magnitude faster than the first, but still not nearly fast enough.
This commit is contained in:
parent
fbd7c8fb00
commit
5d4757d4cb
4 changed files with 102 additions and 0 deletions
56
2018/internal/day12/fastplants.go
Normal file
56
2018/internal/day12/fastplants.go
Normal file
|
@ -0,0 +1,56 @@
|
|||
package day12
|
||||
|
||||
func FastRunGeneration(plants []byte, rules map[string]byte, rootIndex int) ([]byte, int) {
|
||||
newGen := make([]byte, len(plants), len(plants)+4)
|
||||
|
||||
for i := 0; i < len(plants); i++ {
|
||||
newGen[i] = rules[getKey(plants, i)]
|
||||
}
|
||||
|
||||
result1 := rules[getKey(plants, -2)]
|
||||
result2 := rules[getKey(plants, -1)]
|
||||
if result1 == '#' || result2 == '#' {
|
||||
newGen = append([]byte{result1, result2}, newGen...)
|
||||
rootIndex += 2
|
||||
}
|
||||
|
||||
result1 = rules[getKey(plants, len(plants))]
|
||||
result2 = rules[getKey(plants, len(plants)+1)]
|
||||
if result1 == '#' || result2 == '#' {
|
||||
newGen = append(newGen, result1, result2)
|
||||
}
|
||||
|
||||
return newGen, rootIndex
|
||||
}
|
||||
|
||||
func getKey(plants []byte, i int) string {
|
||||
if i < 2 {
|
||||
key := ""
|
||||
for j := 0; j < 2-i; j++ {
|
||||
key += "."
|
||||
}
|
||||
key += string(plants[0 : i+2])
|
||||
return key
|
||||
}
|
||||
|
||||
if i > len(plants)-2 {
|
||||
key := string(plants[i-2 : len(plants)-1])
|
||||
for j := 0; j < len(plants)-1-i; j++ {
|
||||
key += "."
|
||||
}
|
||||
key += string(plants[0 : i+2])
|
||||
return key
|
||||
}
|
||||
|
||||
return string(plants[i-2 : i+2])
|
||||
}
|
||||
|
||||
func FastSumPlants(plants []byte, rootIndex int) int {
|
||||
sum := 0
|
||||
for index, value := range plants {
|
||||
if value == '#' {
|
||||
sum += index - rootIndex
|
||||
}
|
||||
}
|
||||
return sum
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue