diff --git a/day8/main.go b/day8/main.go index 3d5f8bc..dce3cfa 100644 --- a/day8/main.go +++ b/day8/main.go @@ -41,6 +41,11 @@ func main() { slices.Sort(totals) slices.Reverse(totals) fmt.Printf("%v\n", totals[0]*totals[1]*totals[2]) + xx, err := p.wireAll() + if err != nil { + panic(err) + } + fmt.Printf("%d\n", xx) } func parsePlayground(lines []string) playground { @@ -103,6 +108,81 @@ func (p *playground) wireClosest(n uint64) (map[string]uint, error) { return circuits, nil } +func (p *playground) wireAll() (int, error) { + edges, err := p.distances.Edges() + if err != nil { + return 0, err + } + slices.SortFunc(edges, func(e1, e2 graph.Edge[string]) int { + return e1.Properties.Weight - e2.Properties.Weight + }) + circuitsInUse := 0 + nextCircuit := uint(1) + circuits := map[string]uint{} + for _, edge := range edges { + sourceCircuit := circuits[edge.Source] + targetCircuit := circuits[edge.Target] + if sourceCircuit == 0 && targetCircuit == 0 { + circuits[edge.Source] = nextCircuit + circuits[edge.Target] = nextCircuit + nextCircuit++ + circuitsInUse++ + continue + } + if sourceCircuit == 0 { + circuits[edge.Source] = targetCircuit + if circuitsInUse == 1 { + count, _ := p.distances.Order() + if count == len(circuits) { + v1, _ := p.distances.Vertex(edge.Source) + v2, _ := p.distances.Vertex(edge.Target) + return v1.x * v2.x, nil + } + } + continue + } + if targetCircuit == 0 { + circuits[edge.Target] = sourceCircuit + if circuitsInUse == 1 { + count, _ := p.distances.Order() + if count == len(circuits) { + v1, _ := p.distances.Vertex(edge.Source) + v2, _ := p.distances.Vertex(edge.Target) + return v1.x * v2.x, nil + } + } + continue + } + if sourceCircuit == targetCircuit { + if circuitsInUse == 1 { + count, _ := p.distances.Order() + if count == len(circuits) { + v1, _ := p.distances.Vertex(edge.Source) + v2, _ := p.distances.Vertex(edge.Target) + return v1.x * v2.x, nil + } + } + continue + } + for k, v := range circuits { + if v == targetCircuit { + circuits[k] = sourceCircuit + } + } + circuitsInUse-- + if circuitsInUse == 1 { + count, _ := p.distances.Order() + if count == len(circuits) { + v1, _ := p.distances.Vertex(edge.Source) + v2, _ := p.distances.Vertex(edge.Target) + return v1.x * v2.x, nil + } + } + } + v, _ := p.distances.Order() + return 0, fmt.Errorf("exhausted edges without reaching full connectivity %v", v) +} + type playground struct { boxes []box distances graph.Graph[string, box]