-
Notifications
You must be signed in to change notification settings - Fork 0
/
day18_part2.go
120 lines (105 loc) · 1.98 KB
/
day18_part2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package day18_part2
import "fmt"
type Grid struct {
W int
H int
Cells [][]int
}
func NewGrid(w int, h int) *Grid {
g := &Grid{
W: w,
H: h,
Cells: make([][]int, 0),
}
for y := 0; y < h; y++ {
g.Cells = append(g.Cells, make([]int, w))
}
return g
}
func getAnswer(lines []string, steps int) int {
w := len(lines[0])
h := len(lines)
grid := NewGrid(w, h)
grid.fill(lines)
for i := 0; i < steps; i++ {
grid.play()
}
//grid.Print()
return grid.countLightsOn()
}
func (g *Grid) fill(lines []string) {
for y, line := range lines {
for x, ch := range line {
if ch == '#' {
g.Cells[y][x] = 1
}
}
}
}
func (g *Grid) getNeighbors(sy int, sx int) int {
total := 0
for y := -1; y <= 1; y++ {
for x := -1; x <= 1; x++ {
rx := sx + x
ry := sy + y
if rx < 0 || ry < 0 || rx >= g.W || ry >= g.H || rx == sx && ry == sy {
continue
}
if g.Cells[ry][rx] == 1 {
total++
}
}
}
return total
}
func (g *Grid) play() {
newCells := make([][]int, 0)
for y := 0; y < g.H; y++ {
newCells = append(newCells, make([]int, g.W))
}
g.Cells[0][0] = 1
g.Cells[0][g.W-1] = 1
g.Cells[g.H-1][0] = 1
g.Cells[g.H-1][g.W-1] = 1
for y := 0; y < g.H; y++ {
for x := 0; x < g.W; x++ {
neighbors := g.getNeighbors(y, x)
switch {
case g.Cells[y][x] == 1 && (neighbors == 2 || neighbors == 3):
newCells[y][x] = 1
case g.Cells[y][x] == 0 && neighbors == 3:
newCells[y][x] = 1
default:
newCells[y][x] = 0
}
}
}
g.Cells = newCells
g.Cells[0][0] = 1
g.Cells[0][g.W-1] = 1
g.Cells[g.H-1][0] = 1
g.Cells[g.H-1][g.W-1] = 1
}
func (g *Grid) Print() {
for y := 0; y < g.H; y++ {
for x := 0; x < g.W; x++ {
if g.Cells[y][x] == 1 {
fmt.Printf("\033[33m#\033[0m")
} else {
fmt.Printf("\033[37m.\033[0m")
}
}
fmt.Printf("\n")
}
}
func (g *Grid) countLightsOn() int {
total := 0
for y := 0; y < g.H; y++ {
for x := 0; x < g.W; x++ {
if g.Cells[y][x] == 1 {
total++
}
}
}
return total
}