-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
106 lines (89 loc) · 1.72 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
package main
import (
"regexp"
"github.com/danvolchek/AdventOfCode/lib"
)
type action int
const (
on action = iota
off
toggle
)
type pos struct {
x, y int
}
func (p pos) Range(o pos, action func(p pos)) {
for x := p.x; x <= o.x; x += 1 {
for y := p.y; y <= o.y; y += 1 {
action(pos{x: x, y: y})
}
}
}
type instruction struct {
act action
start, end pos
}
var parseReg = regexp.MustCompile(`(.+) (\d+),(\d+) through (\d+),(\d+)`)
func parse(parts []string) instruction {
// line format: "(turn on|turn off|toggle) 123,456 through 789,100"
var act action
switch parts[0] {
case "turn on":
act = on
case "turn off":
act = off
case "toggle":
act = toggle
default:
panic(parts[0])
}
return instruction{
act: act,
start: pos{
x: lib.Atoi(parts[1]),
y: lib.Atoi(parts[2]),
},
end: pos{
x: lib.Atoi(parts[3]),
y: lib.Atoi(parts[4]),
},
}
}
func solve(instructions []instruction) int {
grid := make(map[pos]bool)
for _, instr := range instructions {
switch instr.act {
case on:
instr.start.Range(instr.end, func(p pos) {
grid[p] = true
})
case off:
instr.start.Range(instr.end, func(p pos) {
grid[p] = false
})
case toggle:
instr.start.Range(instr.end, func(p pos) {
grid[p] = !grid[p]
})
default:
panic(instr.act)
}
}
totalLit := 0
for _, isLit := range grid {
if isLit {
totalLit += 1
}
}
return totalLit
}
func main() {
solver := lib.Solver[[]instruction, int]{
ParseF: lib.ParseLine(lib.ParseRegexp(parseReg, parse)),
SolveF: solve,
}
solver.Expect("turn on 0,0 through 999,999", 1000000)
solver.Expect("toggle 0,0 through 999,0", 1000)
solver.Expect("turn on 499,499 through 500,500", 4)
solver.Verify(377891)
}