-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
118 lines (94 loc) · 1.78 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
package main
import (
"fmt"
"io"
"os"
"path"
"regexp"
"strconv"
"strings"
)
func input() *os.File {
input, err := os.Open(path.Join("2021", "17", "input.txt"))
if err != nil {
panic(err)
}
return input
}
var targetAreaRegexp = regexp.MustCompile(`x=(-?\d+)\.\.(-?\d+).*y=(-?\d+)\.\.(-?\d+)`)
type targetArea struct {
x1, x2, y1, y2 int
}
func parse(r io.Reader) targetArea {
bytes, err := io.ReadAll(r)
if err != nil {
panic(err)
}
parts := targetAreaRegexp.FindStringSubmatch(string(bytes))
return targetArea{
x1: toInt(parts[1]),
x2: toInt(parts[2]),
y1: toInt(parts[3]),
y2: toInt(parts[4]),
}
}
func toInt(stringVal string) int {
intVal, err := strconv.Atoi(stringVal)
if err != nil {
panic(err)
}
return intVal
}
func solve(r io.Reader) {
target := parse(r)
intersections := 0
for dx := 0; dx <= target.x2; dx++ {
for dy := target.y1; dy <= -target.y1; dy++ {
p := &probe{
x: 0,
y: 0,
dx: dx,
dy: dy,
target: target,
}
if p.intersectsEventually() {
intersections += 1
}
}
}
fmt.Println(intersections)
}
type probe struct {
x, y, dx, dy int
target targetArea
}
func (p *probe) intersectsEventually() bool {
for {
if p.intersects() {
return true
}
p.simulate()
// fallen below/to the right of the target area
// assumes we're always going right and down
if p.x > p.target.x2 || p.y < p.target.y1 {
return false
}
}
}
func (p *probe) simulate() {
p.x += p.dx
p.y += p.dy
if p.dx > 0 {
p.dx -= 1
} else if p.dx < 0 {
p.dx += 1
}
p.dy -= 1
}
func (p *probe) intersects() bool {
return p.x >= p.target.x1 && p.x <= p.target.x2 && p.y >= p.target.y1 && p.y <= p.target.y2
}
func main() {
solve(strings.NewReader("target area: x=20..30, y=-10..-5"))
solve(input())
}