This commit is contained in:
Gregory 2022-02-15 01:00:39 +02:00
parent 72dc38807d
commit db7295bcd9
3 changed files with 112 additions and 0 deletions

88
d5/d5.go Normal file
View file

@ -0,0 +1,88 @@
package d5
import (
"math"
"strconv"
"strings"
)
type point struct {
x int
y int
}
type segment struct {
a point
b point
}
func createSegments(lines []string) []segment {
segments := make([]segment, len(lines))
for i, line := range lines {
points := strings.Split(line, " -> ")
start := strings.Split(points[0], ",")
end := strings.Split(points[1], ",")
x1, _ := strconv.Atoi(start[0])
y1, _ := strconv.Atoi(start[1])
x2, _ := strconv.Atoi(end[0])
y2, _ := strconv.Atoi(end[1])
segments[i] = segment{point{x1, y1}, point{x2, y2}}
}
return segments
}
func generatePoints(segments []segment) []point {
points := []point{}
for _, segment := range segments {
if segment.a.x == segment.b.x {
min := int(math.Min(float64(segment.a.y), float64(segment.b.y)))
max := int(math.Max(float64(segment.a.y), float64(segment.b.y)))
for i := min; i <= max; i++ {
points = append(points, point{segment.a.x, i})
}
}
if segment.a.y == segment.b.y {
min := int(math.Min(float64(segment.a.x), float64(segment.b.x)))
max := int(math.Max(float64(segment.a.x), float64(segment.b.x)))
for i := min; i <= max; i++ {
points = append(points, point{i, segment.a.y})
}
}
}
return points
}
func findIntersections(points []point) map[point]int {
intersections := map[point]int{}
for _, a := range points {
intersections[a]++
}
return intersections
}
func countIntersections(intersections map[point]int) int {
count := 0
for _, crosses := range intersections {
if crosses > 1 {
count++
}
}
return count
}
func D5(input string) int {
lines := strings.Split(strings.TrimSpace(input), "\n")
segments := createSegments(lines)
points := generatePoints(segments)
intersections := findIntersections(points)
return countIntersections(intersections)
}

22
d5/d5_test.go Normal file
View file

@ -0,0 +1,22 @@
package d5
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestD5(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, 5, D5(input))
}

View file

@ -11,6 +11,7 @@ import (
"github.com/fotonmoton/aoc2021/d2" "github.com/fotonmoton/aoc2021/d2"
"github.com/fotonmoton/aoc2021/d3" "github.com/fotonmoton/aoc2021/d3"
"github.com/fotonmoton/aoc2021/d4" "github.com/fotonmoton/aoc2021/d4"
"github.com/fotonmoton/aoc2021/d5"
) )
func main() { func main() {
@ -31,4 +32,5 @@ func main() {
fmt.Printf("day 3 part 2: %v\n", d3.D3P2(client.Day(3))) fmt.Printf("day 3 part 2: %v\n", d3.D3P2(client.Day(3)))
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)))
} }