-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path18.go
110 lines (98 loc) · 1.93 KB
/
18.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
package main
import (
"bufio"
"fmt"
"log"
"os"
)
const gridSize = 100
type tuple struct {
x int
y int
}
func getOptions(xy tuple) []tuple {
var options []tuple
for x := xy.x - 1; x <= xy.x+1; x++ {
for y := xy.y - 1; y <= xy.y+1; y++ {
if 0 <= x && x < gridSize && 0 <= y && y < gridSize && !(x == xy.x && y == xy.y) {
options = append(options, tuple{x, y})
}
}
}
return options
}
func format(text string) [gridSize]int {
res := [gridSize]int{}
for i, v := range text {
if v == '#' {
res[i] = 1
} else {
res[i] = 0
}
}
return res
}
func solve(grid [gridSize][gridSize]int, lightCorners bool) int {
if lightCorners {
grid[0][0] = 1
grid[0][gridSize-1] = 1
grid[gridSize-1][0] = 1
grid[gridSize-1][gridSize-1] = 1
}
newGrid := grid
for i := 0; i < 100; i++ {
for x := 0; x < gridSize; x++ {
for y := 0; y < gridSize; y++ {
options := getOptions(tuple{x, y})
surroundOn := 0
for _, v := range options {
if grid[v.x][v.y] == 1 {
surroundOn++
}
}
if grid[x][y] == 0 {
if surroundOn == 3 {
newGrid[x][y] = 1
}
} else {
if !(surroundOn == 2 || surroundOn == 3) {
newGrid[x][y] = 0
}
}
}
}
if lightCorners {
newGrid[0][0] = 1
newGrid[0][gridSize-1] = 1
newGrid[gridSize-1][0] = 1
newGrid[gridSize-1][gridSize-1] = 1
}
grid = newGrid
}
lit := 0
for x := 0; x < gridSize; x++ {
for y := 0; y < gridSize; y++ {
if grid[x][y] == 1 {
lit++
}
}
}
return lit
}
func main() {
file, err := os.Open("input/18.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
var grid [gridSize][gridSize]int
scanner := bufio.NewScanner(file)
i := 0
for scanner.Scan() {
row := format(scanner.Text())
grid[i] = row
i++
}
fmt.Println(solve(grid, false))
fmt.Println(solve(grid, true))
}