-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday13-1.go
108 lines (99 loc) · 1.96 KB
/
day13-1.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
package main
import (
"fmt"
"log"
"slices"
)
type day13Map [][]byte
func day13part1(filename string) (string, error) {
maps, err := day13ReadMaps(filename)
if err != nil {
return "", err
}
var cols, rows int
for i, m := range maps {
day13PrintMap(m)
if row, ok := m.findRowReflection(); ok {
log.Print(i, " Row ", row)
rows += 100 * row[0]
continue
}
if column, ok := m.findColumnReflection(); ok {
log.Print(i, " Column ", column)
cols += column[0]
continue
}
}
return fmt.Sprint(cols + rows), nil
}
func day13PrintMap(u day13Map) {
for _, vy := range u {
for _, vx := range vy {
fmt.Print(string(vx))
}
fmt.Println()
}
}
func day13ReadMaps(filename string) ([]day13Map, error) {
var maps []day13Map
var m day13Map
if err := forLineError(filename, func(line string) error {
if len(line) == 0 {
maps = append(maps, m)
m = make(day13Map, 0)
return nil
}
m = append(m, []byte(line))
return nil
}); err != nil {
return maps, err
}
maps = append(maps, m)
return maps, nil
}
// Returns 0-based index of row and true if reflected.
func (m day13Map) findRowReflection() ([]int, bool) {
var rows []int
row := 1
for row < len(m) {
res := true
for b, t := row-1, row; b >= 0 && t < len(m); b, t = b-1, t+1 {
res = res && slices.Equal(m[b], m[t])
if !res {
break
}
}
if res {
rows = append(rows, row)
}
row += 1
}
return rows, len(rows) > 0
}
// Returns 0-based index of column and true if reflected.
func (m day13Map) findColumnReflection() ([]int, bool) {
var cols []int
column := 1
for column < len(m[0]) {
res := true
for l, r := column-1, column; l >= 0 && r < len(m[0]); l, r = l-1, r+1 {
res = res && m.colsEqual(l, r)
if !res {
break
}
}
if res {
cols = append(cols, column)
}
column += 1
}
return cols, len(cols) > 0
}
func (m day13Map) colsEqual(l, r int) bool {
for y := 0; y < len(m); y++ {
if m[y][l] != m[y][r] {
return false
}
}
return true
}