-
Notifications
You must be signed in to change notification settings - Fork 0
/
day13.go
137 lines (126 loc) · 2.23 KB
/
day13.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
package main
import (
"fmt"
"io/ioutil"
"strconv"
"strings"
)
func readLinesFromFile(fname string) (result []string, err error) {
b, err := ioutil.ReadFile(fname)
if err != nil {
return nil, err
}
lines := strings.Split(string(b), "\n")
// filter out empty lines
result = make([]string, 0, len(lines))
for _, l := range lines {
if len(l) == 0 {
continue
}
result = append(result, l)
}
return result, nil
}
type point struct {
x, y int
}
func printSheet(sheet [][]int, countOnly bool) {
count := 0
for row := 0; row < len(sheet); row++ {
for col := 0; col < len(sheet[row]); col++ {
if sheet[row][col] > 0 {
if !countOnly {
fmt.Print("#")
}
count++
} else {
if !countOnly {
fmt.Print(".")
}
}
}
if !countOnly {
fmt.Println()
}
}
if countOnly {
fmt.Println(count)
}
fmt.Println()
}
func foldPaper(data []string, showFirst bool) {
maxX := 0
maxY := 0
folds := 0
points := make([]*point, 0)
for i, l := range data {
p := new(point)
pt := strings.Split(l, ",")
if len(pt) < 2 {
folds = i
break
}
p.x, _ = strconv.Atoi(pt[0])
if p.x >= maxX {
maxX = p.x
}
p.y, _ = strconv.Atoi(pt[1])
if p.y >= maxY {
maxY = p.y
}
points = append(points, p)
}
maxX++
maxY++
sheet := make([][]int, maxY)
for i := 0; i < maxY; i++ {
sheet[i] = make([]int, maxX)
}
for _, p := range points {
sheet[p.y][p.x] = 1
}
for f := folds; f < len(data); f++ {
f := strings.Fields(data[f])
fl := strings.Split(f[2], "=")
v, _ := strconv.Atoi(fl[1])
v++
if fl[0] == "y" {
for i, r := v, v-2; i < maxY; i++ {
for c := 0; c < maxX; c++ {
sheet[r][c] |= sheet[i][c]
}
r--
}
sheet = sheet[:v-1]
maxY = v - 1
} else {
for i, c := v, v-2; i < maxX; i++ {
for r := 0; r < maxY; r++ {
sheet[r][c] |= sheet[r][i]
}
c--
}
for r := 0; r < maxY; r++ {
sheet[r] = sheet[r][:v-1]
}
maxX = v - 1
}
if showFirst {
printSheet(sheet, true)
return
}
}
printSheet(sheet, false)
}
func day13part1(data []string) {
foldPaper(data, true)
}
func day13part2(data []string) {
foldPaper(data, false)
}
func main() {
data, _ := readLinesFromFile("day13.txt")
day13part1(data)
fmt.Println()
day13part2(data)
}