Golang每次使用AOC 2021第6天问题的Map都给出不同的结果

4sup72z8  于 2023-02-20  发布在  Go
关注(0)|答案(1)|浏览(110)

我一直在尝试解决代码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)
}

有人能帮忙吗?

yx2lnoni

yx2lnoni1#

我希望这段代码可以完成这个工作,请添加输入文件阅读部分,并将输出切片打印为逗号分隔的字符串。您还可以验证输入是否都是0到8之间的数字。

package main

import "fmt"

func refreshTimer(x int) (int, bool) {
    if x == 0 {
        return 6, true
    } else {
        return x - 1, false
    }
}

func spawnFish(i []int) []int {
    var parentIntTimer []int
    var childIntTimer []int
    for _, d := range i {
        y, c := refreshTimer(d)
        parentIntTimer = append(parentIntTimer, y)
        if c {
            childIntTimer = append(childIntTimer, 8)
        }
    }
    return append(parentIntTimer, childIntTimer...)
}

func main() {
    initialFishes := []int{3, 4, 3, 1, 2}
    var spFishes []int
    noOfDays := 18
    for i := 1; i <= noOfDays; i++ {
        spFishes = spawnFish(initialFishes)
        initialFishes = spFishes
    }
    fmt.Println(spFishes)
}

输出:[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]

相关问题