2018-12-13 05:51:19 +00:00
|
|
|
// Unused solution: still not fast enough
|
2018-12-13 05:27:02 +00:00
|
|
|
package day12
|
|
|
|
|
2018-12-13 05:51:19 +00:00
|
|
|
func FastGenerationRunner() func([]byte, map[string]byte, int) ([]byte, int) {
|
|
|
|
cache := make(map[string]string)
|
2018-12-13 05:27:02 +00:00
|
|
|
|
2018-12-13 05:51:19 +00:00
|
|
|
return func(current []byte, rules map[string]byte, rootIndex int) ([]byte, int) {
|
|
|
|
// check the cache
|
|
|
|
if cache[string(current)] != "" {
|
|
|
|
return []byte(cache[string(current)]), rootIndex
|
|
|
|
}
|
2018-12-13 05:27:02 +00:00
|
|
|
|
2018-12-13 05:51:19 +00:00
|
|
|
newGen := make([]byte, len(current), len(current)+4)
|
2018-12-13 05:27:02 +00:00
|
|
|
|
2018-12-13 05:51:19 +00:00
|
|
|
for i := 0; i < len(current); i++ {
|
|
|
|
newGen[i] = rules[getKey(current, i)]
|
|
|
|
}
|
2018-12-13 05:27:02 +00:00
|
|
|
|
2018-12-13 05:51:19 +00:00
|
|
|
result1 := rules[getKey(current, -2)]
|
|
|
|
result2 := rules[getKey(current, -1)]
|
|
|
|
if result1 == '#' || result2 == '#' {
|
|
|
|
newGen = append([]byte{result1, result2}, newGen...)
|
|
|
|
rootIndex += 2
|
|
|
|
}
|
|
|
|
|
|
|
|
result1 = rules[getKey(current, len(current))]
|
|
|
|
result2 = rules[getKey(current, len(current)+1)]
|
|
|
|
if result1 == '#' || result2 == '#' {
|
|
|
|
newGen = append(newGen, result1, result2)
|
|
|
|
}
|
|
|
|
|
|
|
|
// cache result
|
|
|
|
cache[string(current)] = string(newGen)
|
|
|
|
|
|
|
|
return newGen, rootIndex
|
|
|
|
}
|
2018-12-13 05:27:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|