AoC2020/day15/day15.go
Karl Spickermann 1cccb7132d Day15
2020-12-15 16:43:32 +01:00

60 lines
1.2 KiB
Go

package main
import "fmt"
func main() {
fmt.Println(run([]int{5,1,9,18,13,8,0}, 2020))
fmt.Println(runPart2([]int{5,1,9,18,13,8,0}, 30000000))
}
func run(startingNumber []int, length int) int{
var band []int
band = append(band, startingNumber...)
for i := len(startingNumber); i < length; i++ {
currentNumber := band[i-1]
index := findIndex(currentNumber,band)
if index == -1 {
band = append(band, 0)
}else {
band = append(band, i-1-index)
}
}
return band[len(band)-1]
}
func runPart2(startingNumber []int, length int) int{
var band = make (map[int][]int)
for i, val := range startingNumber {
band[val] = []int{i,i}
}
lastNumber := startingNumber[len(startingNumber)-1]
for i := len(startingNumber); i < length; i++ {
currentNumber := lastNumber
indexes := band[currentNumber]
diffIndexes := indexes[1]-indexes[0]
if diffIndexes == 0 {
lastNumber = 0
band[0] = []int{band[0][1],i}
}else {
lastNumber = diffIndexes
if len(band[diffIndexes]) != 0 {
band[diffIndexes] = []int{band[diffIndexes][1],i}
}else {
band[diffIndexes] = []int{i,i}
}
}
}
return lastNumber
}
func findIndex(number int, band []int) int{
for i := len(band)-2; i >= 0; i-- {
if band[i] == number {
return i
}
}
return -1
}