aoc2015/day18/day.go
Stefan Harmuth 9e7e470498 day18
2020-12-29 14:32:06 +01:00

76 lines
1.5 KiB
Go

package day18
import (
"tools"
)
type coord struct {
x int
y int
}
func play(grid tools.ToggleGrid, stuckCorners bool) {
neighbours := make(map[coord]int)
for thisCoord := range grid.GetOnCoordinates() {
for cx := thisCoord.X - 1; cx <= thisCoord.X+1; cx++ {
for cy := thisCoord.Y - 1; cy <= thisCoord.Y+1; cy++ {
if cy == thisCoord.Y && cx == thisCoord.X {
continue
}
neighbours[coord{cx, cy}]++
}
}
}
for x := 0; x <= grid.MaxX; x++ {
for y := 0; y <= grid.MaxY; y++ {
if grid.State(x, y) {
if neighbours[coord{x, y}] != 2 && neighbours[coord{x, y}] != 3 {
if !stuckCorners || !grid.IsCorner(x, y) {
grid.Set(x, y, tools.Off)
}
}
} else if neighbours[coord{x, y}] == 3 {
grid.Set(x, y, tools.On)
}
}
}
}
func makeGridFromInput(input []string) tools.ToggleGrid {
grid := tools.NewToogleGrid()
for y, line := range input {
for x, c := range line {
if c == '#' {
grid.Set(x, y, tools.On)
}
}
}
return grid
}
func Part1(puzzle tools.AoCPuzzle) interface{} {
grid := makeGridFromInput(puzzle.GetInputArray())
for i := 0; i < 100; i++ {
play(grid, false)
}
return grid.GetOnCount()
}
func Part2(puzzle tools.AoCPuzzle) interface{} {
grid := makeGridFromInput(puzzle.GetInputArray())
grid.Set(0, 0, tools.On)
grid.Set(0, grid.MaxY, tools.On)
grid.Set(grid.MaxX, 0, tools.On)
grid.Set(grid.MaxX, grid.MaxY, tools.On)
for i := 0; i < 100; i++ {
play(grid, true)
}
return grid.GetOnCount()
}