-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
75 lines (57 loc) · 1.32 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
package main
import (
"fmt"
"io"
"os"
"github.com/devries/advent_of_code_2021/utils"
)
func main() {
f, err := os.Open("../inputs/day05.txt")
utils.Check(err, "error opening input.txt")
defer f.Close()
r := solve(f)
fmt.Println(r)
}
func solve(r io.Reader) int {
lines := utils.ReadLines(r)
grid := make(map[utils.Point]int)
for _, ln := range lines {
p1, p2 := parseLine(ln)
// find difference and then direction between points
d := p2.Add(p1.Scale(-1))
ds := direction(d)
// Add the vents
// This is a do ... while loop, because that's just how I think
for p, ok := p1, true; ok; p, ok = p.Add(ds), p != p2 { // do ... while p != p2
grid[p] += 1
}
}
// Find all points in grid greater than 2
sum := 0
for _, v := range grid {
if v > 1 {
sum++
}
}
return sum
}
// Find the direction of a point that has 0 as one of its values
func direction(p utils.Point) utils.Point {
var magnitude int
if p.X == 0 {
magnitude = p.Y
} else {
magnitude = p.X
}
if magnitude < 0 {
magnitude = -magnitude
}
return utils.Point{X: p.X / magnitude, Y: p.Y / magnitude}
}
func parseLine(l string) (utils.Point, utils.Point) {
var p1 utils.Point
var p2 utils.Point
_, err := fmt.Sscanf(l, "%d,%d -> %d,%d", &p1.X, &p1.Y, &p2.X, &p2.Y)
utils.Check(err, "Error parsing line")
return p1, p2
}