-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
151 lines (123 loc) · 2.48 KB
/
main.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
package main
import (
"fmt"
"io"
"os"
"strings"
"github.com/devries/advent_of_code_2021/utils"
"github.com/spf13/pflag"
)
func main() {
pflag.Parse()
f, err := os.Open("../inputs/day20.txt")
utils.Check(err, "error opening input")
defer f.Close()
r := solve(f, utils.Verbose)
fmt.Println(r)
}
func solve(r io.Reader, verbose bool) int {
lines := utils.ReadLines(r)
key, grid := parseInput(lines)
for i := 0; i < 50; i++ {
grid = step(key, grid)
if verbose {
fmt.Println(grid)
}
}
return grid.Count()
}
type Grid struct {
Xmin int
Xmax int
Ymin int
Ymax int
Data map[utils.Point]int
Fill int
}
func (g Grid) getPixelSquare(p utils.Point) int {
ret := 0
for k, v := range neighbors {
pt := p.Add(k)
var pval int
if pt.X < g.Xmin || pt.X > g.Xmax || pt.Y < g.Ymin || pt.Y > g.Ymax {
pval = g.Fill
} else {
pval = g.Data[pt]
}
ret |= pval << v
}
return ret
}
func (g Grid) String() string {
var sb strings.Builder
for j := g.Ymin; j <= g.Ymax; j++ {
for i := g.Xmin; i <= g.Xmax; i++ {
v := g.Data[utils.Point{X: i, Y: j}]
switch v {
case 0:
sb.WriteRune('.')
case 1:
sb.WriteRune('#')
}
}
sb.WriteRune('\n')
}
return sb.String()
}
func (g Grid) Count() int {
total := 0
for _, v := range g.Data {
total += v
}
return total
}
var neighbors = map[utils.Point]int{
{X: -1, Y: -1}: 8,
{X: 0, Y: -1}: 7,
{X: 1, Y: -1}: 6,
{X: -1, Y: 0}: 5,
{X: 0, Y: 0}: 4,
{X: 1, Y: 0}: 3,
{X: -1, Y: 1}: 2,
{X: 0, Y: 1}: 1,
{X: 1, Y: 1}: 0,
}
func parseInput(lines []string) ([]int, Grid) {
key := make([]int, 0)
for _, c := range lines[0] {
switch c {
case '.':
key = append(key, 0)
case '#':
key = append(key, 1)
}
}
ysize := len(lines) - 2
xsize := len(lines[2])
grid := Grid{0, xsize - 1, 0, ysize - 1, make(map[utils.Point]int), 0}
for j := 0; j < ysize; j++ {
for i, c := range lines[j+2] {
if c == '#' {
grid.Data[utils.Point{X: i, Y: j}] = 1
}
}
}
return key, grid
}
func step(key []int, grid Grid) Grid {
newGrid := Grid{grid.Xmin - 1, grid.Xmax + 1, grid.Ymin - 1, grid.Ymax + 1, make(map[utils.Point]int), 0}
// Handle fill
if grid.Fill == 0 && key[0] == 1 {
newGrid.Fill = 1
} else if grid.Fill == 1 && key[511] == 0 {
newGrid.Fill = 0
}
for j := grid.Ymin - 1; j <= grid.Ymax+1; j++ {
for i := grid.Xmin - 1; i <= grid.Xmax+1; i++ {
p := utils.Point{X: i, Y: j}
square := grid.getPixelSquare(p)
newGrid.Data[p] = key[square]
}
}
return newGrid
}