This commit is contained in:
Gregory 2022-02-15 21:20:24 +02:00
parent db7295bcd9
commit 7617d7ae99
3 changed files with 59 additions and 0 deletions

View file

@ -56,6 +56,41 @@ func generatePoints(segments []segment) []point {
return points return points
} }
func generatePointsWithDiagonals(segments []segment) []point {
points := []point{}
for _, segment := range segments {
startX := segment.a.x
startY := segment.a.y
endX := segment.b.x
endY := segment.b.y
dx := 1
dy := 1
if segment.a.x == segment.b.x {
dx = 0
} else if segment.a.x > segment.b.x {
dx = -1
}
if segment.a.y == segment.b.y {
dy = 0
} else if segment.a.y > segment.b.y {
dy = -1
}
points = append(points, point{startX, startY})
for startX != endX || startY != endY {
startX += dx
startY += dy
points = append(points, point{startX, startY})
}
}
return points
}
func findIntersections(points []point) map[point]int { func findIntersections(points []point) map[point]int {
intersections := map[point]int{} intersections := map[point]int{}
@ -86,3 +121,11 @@ func D5(input string) int {
intersections := findIntersections(points) intersections := findIntersections(points)
return countIntersections(intersections) return countIntersections(intersections)
} }
func D5P2(input string) int {
lines := strings.Split(strings.TrimSpace(input), "\n")
segments := createSegments(lines)
points := generatePointsWithDiagonals(segments)
intersections := findIntersections(points)
return countIntersections(intersections)
}

View file

@ -20,3 +20,18 @@ func TestD5(t *testing.T) {
assert.EqualValues(t, 5, D5(input)) assert.EqualValues(t, 5, D5(input))
} }
func TestD5P2(t *testing.T) {
input := `0,9 -> 5,9
8,0 -> 0,8
9,4 -> 3,4
2,2 -> 2,1
7,0 -> 7,4
6,4 -> 2,0
0,9 -> 2,9
3,4 -> 1,4
0,0 -> 8,8
5,5 -> 8,2`
assert.EqualValues(t, 12, D5P2(input))
}

View file

@ -33,4 +33,5 @@ func main() {
fmt.Printf("day 4: %v\n", d4.D4(client.Day(4))) fmt.Printf("day 4: %v\n", d4.D4(client.Day(4)))
fmt.Printf("day 4 part 2: %v\n", d4.D4P2(client.Day(4))) fmt.Printf("day 4 part 2: %v\n", d4.D4P2(client.Day(4)))
fmt.Printf("day 5: %v\n", d5.D5(client.Day(5))) fmt.Printf("day 5: %v\n", d5.D5(client.Day(5)))
fmt.Printf("day 5 part 2: %v\n", d5.D5P2(client.Day(5)))
} }