我一直在尝试解决代码2021的降临,在第六天,我尝试了这个解决方案,但结果每次都不一样。似乎是什么问题?有任何内存泄漏与Map?
输入文件可以在here中找到问题的详细信息可以在here中读取
对于第一部分,它是直接在数组上循环的,但是随着天数的增加,种群呈指数增长,时间复杂度也以类似的方式增长。
在go版本go1.19.3中,我尝试过以下方法:
package main
import (
"fmt"
"os"
"strconv"
"strings"
)
func getInput() []int {
var parsedData []int
rawData, _ := os.ReadFile("input.txt")
data := strings.Split(string(rawData), ",")
for _, strNum := range data {
num, _ := strconv.Atoi(strNum)
parsedData = append(parsedData, num)
}
return parsedData
}
func main() {
data := getInput()
var total int64
// create a map t0 hold the number of fish with the same timer
fishWithSameTimer := make(map[int]int64)
for _, timer := range data {
if _, ok := fishWithSameTimer[timer]; ok {
fishWithSameTimer[timer] += 1
} else {
fishWithSameTimer[timer] = 1
}
}
const days int = 18
currDay := 1
for currDay <= days {
tempFishTimerData := make(map[int]int64)
for timer, numOfFishes := range fishWithSameTimer {
if timer == 0 {
tempFishTimerData[8] = numOfFishes
tempFishTimerData[6] = numOfFishes
}else{
tempFishTimerData[timer - 1] += numOfFishes
}
}
fishWithSameTimer = tempFishTimerData
fmt.Println("Day:", currDay, fishWithSameTimer)
currDay++
}
fmt.Println(fishWithSameTimer)
for _, num := range fishWithSameTimer {
total += num
}
fmt.Println(total)
}
有人能帮忙吗?
1条答案
按热度按时间yx2lnoni1#
我希望这段代码可以完成这个工作,请添加输入文件阅读部分,并将输出切片打印为逗号分隔的字符串。您还可以验证输入是否都是0到8之间的数字。
输出:
[6 0 6 4 5 6 0 1 1 2 6 0 1 1 1 2 2 3 3 4 6 7 8 8 8 8]