Compare commits

...

1 Commits

Author SHA1 Message Date
Simon Ziegler
f7949a3594 day 08 part2 2025-12-11 14:21:09 +01:00

View File

@@ -9,29 +9,31 @@ import (
"git.z1glr.de/advent-of-code-2025/pkg/aoc"
)
type Point struct {
type Node struct {
X, Y, Z int
Parent *Point
root *Node
Size int
id int
ID int
}
func (p *Point) DistanceTo(p2 *Point) float64 {
func (p *Node) DistanceTo(p2 *Node) float64 {
return math.Sqrt(float64((p.X-p2.X)*(p.X-p2.X) + (p.Y-p2.Y)*(p.Y-p2.Y) + (p.Z-p2.Z)*(p.Z-p2.Z)))
}
func (p *Point) GetRoot() *Point {
if p.Parent == nil || p.Parent == p {
func (p *Node) GetRoot() *Node {
if p.root == nil {
return p
} else {
return p.Parent.GetRoot()
root := p.root.GetRoot()
p.root = root
return root
}
}
func PointFromString(s string) Point {
func PointFromString(s string) Node {
parts := strings.Split(s, ",")
return Point{
return Node{
X: aoc.ParseInt(parts[0]),
Y: aoc.ParseInt(parts[1]),
Z: aoc.ParseInt(parts[2]),
@@ -41,30 +43,32 @@ func PointFromString(s string) Point {
type Connection struct {
Length float64
P1, P2 *Point
P1, P2 *Node
}
func do(test bool) (int, int) {
rows := aoc.ReadFileRows(test)
points := make([]Point, len(rows))
points := make([]Node, len(rows))
for ii, rr := range rows {
points[ii] = PointFromString(rr)
points[ii].id = ii
points[ii].ID = ii + 1
}
connections := []Connection{}
for ii := range points {
for jj := range points[ii+1:] {
for ii := range points[:len(points)-1] {
for jj := ii + 1; jj < len(points); jj++ {
// for jj := range points[ii+1:] {
p1 := &points[ii]
p2 := &points[jj]
// p2 := &points[ii+1+jj]
connections = append(connections, Connection{
Length: p1.DistanceTo(p2),
P1: &points[ii],
P2: &points[ii+1+jj],
P1: p1,
P2: p2,
})
}
}
@@ -72,44 +76,31 @@ func do(test bool) (int, int) {
// sort distances by length
sort.Slice(connections, func(i, j int) bool { return connections[i].Length < connections[j].Length })
for ii := range connections[:10] {
if test {
connections = connections[:10]
} else {
connections = connections[:1000]
}
for ii := range connections {
cc := &connections[ii]
// if both have no parent, make the first one as the parent
if cc.P1.Parent == nil && cc.P2.Parent == nil {
cc.P1.Parent = cc.P1
cc.P2.Parent = cc.P1
cc.P1.Size++
root1 := cc.P1.GetRoot()
root2 := cc.P2.GetRoot()
// if the second one has no parent, connect it to the first one
} else if cc.P2.Parent == nil {
cc.P2.Parent = cc.P1
if root1 != root2 {
root2.root = root1
cc.P1.GetRoot().Size++
} else if cc.P1.Parent == nil {
cc.P1.Parent = cc.P2
cc.P2.GetRoot().Size++
// both have a parent -> make the parent of p2's root p1
} else {
p2Root := cc.P2.GetRoot()
p2OldSize := p2Root.Size
cc.P2.GetRoot().Parent = cc.P1.GetRoot()
cc.P1.GetRoot().Size += p2OldSize
root1.Size += root2.Size
}
}
roots := []*Point{}
roots := []*Node{}
for ii := range points {
pp := &points[ii]
if pp.GetRoot() == pp {
roots = append(roots, pp)
fmt.Println(pp.Size)
}
}