Skip to content

Commit 421e9bf

Browse files
committed
day4: solve second part
1 parent df7ba34 commit 421e9bf

File tree

1 file changed

+21
-13
lines changed

1 file changed

+21
-13
lines changed

day4/main.go

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import (
66
"os"
77
)
88

9-
const NEEDLE = "XMAS"
9+
const NEEDLE = "MAS"
1010

1111
type point struct {
1212
y int
@@ -35,16 +35,16 @@ func generateMatchPoints(at point, dy, dx int) []point {
3535
return result
3636
}
3737

38+
func transpose(p point, dy, dx int) point {
39+
return point{y: p.y + dy, x: p.x + dx}
40+
}
41+
3842
func matchPointGenerators() []func(point) []point {
3943
return []func(point) []point{
40-
func(p point) []point { return generateMatchPoints(p, -1, 0) },
41-
func(p point) []point { return generateMatchPoints(p, -1, -1) },
42-
func(p point) []point { return generateMatchPoints(p, 0, -1) },
43-
func(p point) []point { return generateMatchPoints(p, 1, -1) },
44-
func(p point) []point { return generateMatchPoints(p, 1, 0) },
45-
func(p point) []point { return generateMatchPoints(p, 1, 1) },
46-
func(p point) []point { return generateMatchPoints(p, 0, 1) },
47-
func(p point) []point { return generateMatchPoints(p, -1, 1) },
44+
func(p point) []point { return generateMatchPoints(transpose(p, -1, -1), 1, 1) },
45+
func(p point) []point { return generateMatchPoints(transpose(p, 1, 1), -1, -1) },
46+
func(p point) []point { return generateMatchPoints(transpose(p, -1, 1), 1, -1) },
47+
func(p point) []point { return generateMatchPoints(transpose(p, 1, -1), -1, 1) },
4848
}
4949
}
5050

@@ -64,13 +64,21 @@ func countMatchesFrom(source point, lines []string, matches [][]byte) int {
6464
if !isAMatch(matchPoints, lines) {
6565
continue
6666
}
67-
67+
matchCount++
68+
}
69+
if matchCount != 2 {
70+
return 0
71+
}
72+
for _, generator := range matchPointGenerators() {
73+
matchPoints := generator(source)
74+
if !isAMatch(matchPoints, lines) {
75+
continue
76+
}
6877
for i, p := range matchPoints {
6978
matches[p.y][p.x] = NEEDLE[i]
7079
}
71-
matchCount++
7280
}
73-
return matchCount
81+
return 1
7482
}
7583

7684
func main() {
@@ -98,8 +106,8 @@ func main() {
98106
}
99107
}
100108

101-
fmt.Fprintf(os.Stderr, "matches: %d\n", matchCount)
102109
for _, lineMatches := range matches {
103110
fmt.Printf("%s\n", string(lineMatches))
104111
}
112+
fmt.Fprintf(os.Stderr, "matches: %d\n", matchCount)
105113
}

0 commit comments

Comments
 (0)