-
Notifications
You must be signed in to change notification settings - Fork 0
/
day5_part1.go
125 lines (112 loc) · 2.29 KB
/
day5_part1.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
119
120
121
122
123
124
125
package day5_part1
import (
"fmt"
"strings"
"GoAdventOfCode/util"
)
type Point struct {
X int
Y int
}
type Segment struct {
P1 Point
P2 Point
}
func howManyPointsOverlap(lines []string) int {
mx := 0
my := 0
segments := make([]*Segment, 0)
for _, line := range lines {
p1, p2 := getPoints(line)
if p1.X == p2.X || p1.Y == p2.Y {
//fmt.Printf("i: %d, P1: %+v, p2: %+v\n", i, p1, p2)
mx = max(mx, p1.X)
mx = max(mx, p2.X)
my = max(my, p1.Y)
my = max(my, p2.Y)
s := Segment{
P1: p1,
P2: p2,
}
segments = append(segments, &s)
}
}
mx++
my++
diagram := createEmptyDiagram(mx, my)
for _, seg := range segments {
diagram = putSegmentOnDiagram(diagram, *seg)
}
//printDiagram(diagram)
return countOverlaps(diagram)
}
func getPoints(line string) (Point, Point) {
idx := strings.Index(line, "-")
part1 := strings.TrimSpace(line[0:idx])
part2 := strings.TrimSpace(line[idx+2:])
parts1 := strings.Split(part1, ",")
p1 := Point{
X: util.ConvertStringToInt(parts1[0]),
Y: util.ConvertStringToInt(parts1[1]),
}
parts2 := strings.Split(part2, ",")
p2 := Point{
X: util.ConvertStringToInt(parts2[0]),
Y: util.ConvertStringToInt(parts2[1]),
}
return p1, p2
}
func createEmptyDiagram(mx int, my int) [][]int {
diagram := make([][]int, 0)
for y := 0; y < my; y++ {
line := make([]int, mx)
diagram = append(diagram, line)
}
return diagram
}
func printDiagram(diagram [][]int) {
for y := 0; y < len(diagram); y++ {
line := diagram[y]
for x := 0; x < len(line); x++ {
fmt.Print("", diagram[y][x])
}
fmt.Println()
}
}
func putSegmentOnDiagram(diagram [][]int, seg Segment) [][]int {
if seg.P1.X == seg.P2.X {
if seg.P1.Y > seg.P2.Y {
for y := seg.P2.Y; y <= seg.P1.Y; y++ {
diagram[y][seg.P1.X]++
}
} else {
for y := seg.P1.Y; y <= seg.P2.Y; y++ {
diagram[y][seg.P1.X]++
}
}
}
if seg.P1.Y == seg.P2.Y {
if seg.P1.X > seg.P2.X {
for x := seg.P2.X; x <= seg.P1.X; x++ {
diagram[seg.P1.Y][x]++
}
} else {
for x := seg.P1.X; x <= seg.P2.X; x++ {
diagram[seg.P1.Y][x]++
}
}
}
return diagram
}
func countOverlaps(diagram [][]int) int {
overlap := 0
for y := 0; y < len(diagram); y++ {
line := diagram[y]
for x := 0; x < len(line); x++ {
if diagram[y][x] > 1 {
overlap++
}
}
}
return overlap
}