|
| 1 | +import { GraphWeightedUndirectedAdjacencyList } from '../KruskalMST.js' |
| 2 | + |
| 3 | +function totalWeight(graph) { |
| 4 | + // connections: { u: { v: w, ... }, ... } |
| 5 | + let sum = 0 |
| 6 | + const seen = new Set() |
| 7 | + for (const u of Object.keys(graph.connections)) { |
| 8 | + for (const v of Object.keys(graph.connections[u])) { |
| 9 | + const key = u < v ? `${u}-${v}` : `${v}-${u}` |
| 10 | + if (!seen.has(key)) { |
| 11 | + seen.add(key) |
| 12 | + sum += graph.connections[u][v] |
| 13 | + } |
| 14 | + } |
| 15 | + } |
| 16 | + return sum |
| 17 | +} |
| 18 | + |
| 19 | +test('KruskalMST builds a minimum spanning tree', () => { |
| 20 | + const g = new GraphWeightedUndirectedAdjacencyList() |
| 21 | + // Graph: |
| 22 | + // 1-2(1), 2-3(2), 3-4(1), 3-5(100), 4-5(5) |
| 23 | + g.addEdge('1', '2', 1) |
| 24 | + g.addEdge('2', '3', 2) |
| 25 | + g.addEdge('3', '4', 1) |
| 26 | + g.addEdge('3', '5', 100) // heavy edge to be excluded |
| 27 | + g.addEdge('4', '5', 5) |
| 28 | + |
| 29 | + const mst = g.KruskalMST() |
| 30 | + |
| 31 | + // MST should have nodes: 1,2,3,4,5 |
| 32 | + expect(Object.keys(mst.connections).sort()).toEqual(['1', '2', '3', '4', '5']) |
| 33 | + |
| 34 | + // It should have exactly nodes-1 = 4 edges |
| 35 | + let edgeCount = 0 |
| 36 | + const seen = new Set() |
| 37 | + for (const u of Object.keys(mst.connections)) { |
| 38 | + for (const v of Object.keys(mst.connections[u])) { |
| 39 | + const key = u < v ? `${u}-${v}` : `${v}-${u}` |
| 40 | + if (!seen.has(key)) { |
| 41 | + seen.add(key) |
| 42 | + edgeCount++ |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + expect(edgeCount).toBe(4) |
| 47 | + |
| 48 | + // Total weight should be 1 (1-2) + 2 (2-3) + 1 (3-4) + 5 (4-5) = 9 |
| 49 | + // (Edge 3-5 with weight 100 must not be selected) |
| 50 | + expect(totalWeight(mst)).toBe(9) |
| 51 | + |
| 52 | + // Ensure excluded heavy edge is not present |
| 53 | + expect(mst.connections['3']['5']).toBeUndefined() |
| 54 | + expect(mst.connections['5']['3']).toBeUndefined() |
| 55 | +}) |
0 commit comments