DAY 15 - GoLang을 통한 코드 2020 출현

8226 단어 goadventofcode
DAY15:


그래서 어제 Advent Of Code를 마무리해야겠다고 생각했는데 오늘의 문제는 그냥 클릭했습니다. 나는 그것이 지난 며칠 후에 더 쉬울 예정이라고 가정하고 있습니다.

2부에서 정확히 0줄의 변경이 필요했다는 것이 이상했습니다. 마지막 턴을 변경하기만 하면 됩니다. 시간이 조금 더 걸렸습니다. 내 시간은 약 7.6초

package days

import (
    "fmt"

    inputs "../inputs"
)

// https://adventofcode.com/2020/day/15
// Fifteen : advent of code, day Fifteen part1 and 2
func Fifteen() {
    inputSlice := inputs.Day15

    // k: number spoken | v: {num of times spoken, last time spoken}
    spoken := make(map[int][]int)

    for i, num := range inputSlice {
        spoken[num] = []int{1, i, i}
    }

    fmt.Print("(Part 1) - 2020th number spoken: ")
    fmt.Println(getLastNumberSpoken(spoken, 2020))
    fmt.Print("(Part 1) - 2020th number spoken: ")
    fmt.Println(getLastNumberSpoken(spoken, 30000000))
}

func getLastNumberSpoken(spoken map[int][]int, last int) int {
    nextNum := 0
    var lastNum int
    var lastTurn int
    for _, v := range spoken {
        if v[1] > lastTurn {
            lastTurn = v[1]
            lastNum = v[0]
        }
    }

    for i := len(spoken); i < last; i++ {
        if _, ok := spoken[lastNum]; ok {
            if spoken[lastNum][0] == 1 {
                nextNum = 0
            } else {
                nextNum = spoken[lastNum][1] - spoken[lastNum][2]
            }
        }

        if _, ok := spoken[nextNum]; ok {
            spoken[nextNum][0]++
            spoken[nextNum][2] = spoken[nextNum][1]
            spoken[nextNum][1] = i
            lastNum = nextNum
        } else {
            spoken[nextNum] = []int{1, i, i}
            lastNum = nextNum
        }
    }

    return nextNum
}



Link to Github source file

좋은 웹페이지 즐겨찾기