From 7617d7ae990a491d00a88204910f44754ffd24c8 Mon Sep 17 00:00:00 2001 From: Gregory Date: Tue, 15 Feb 2022 21:20:24 +0200 Subject: [PATCH] d5p2 --- d5/d5.go | 43 +++++++++++++++++++++++++++++++++++++++++++ d5/d5_test.go | 15 +++++++++++++++ main.go | 1 + 3 files changed, 59 insertions(+) diff --git a/d5/d5.go b/d5/d5.go index 1bef7d0..8d4feb8 100644 --- a/d5/d5.go +++ b/d5/d5.go @@ -56,6 +56,41 @@ func generatePoints(segments []segment) []point { 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 { intersections := map[point]int{} @@ -86,3 +121,11 @@ func D5(input string) int { intersections := findIntersections(points) 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) +} diff --git a/d5/d5_test.go b/d5/d5_test.go index d377b15..27a10dd 100644 --- a/d5/d5_test.go +++ b/d5/d5_test.go @@ -20,3 +20,18 @@ func TestD5(t *testing.T) { 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)) +} diff --git a/main.go b/main.go index 5a35f50..9eaf7a2 100644 --- a/main.go +++ b/main.go @@ -33,4 +33,5 @@ func main() { 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 5: %v\n", d5.D5(client.Day(5))) + fmt.Printf("day 5 part 2: %v\n", d5.D5P2(client.Day(5))) }