|
1 | 1 | const { kahnTopologicalSort } = require('../KahnsAlgorithm');
|
2 | 2 |
|
3 |
| -describe("Kahn's Algorithm - Topological Sort", () => { |
4 |
| - test('returns a valid topological order for a DAG', () => { |
| 3 | +describe("Kahn's Algorithm", () => { |
| 4 | + test('DAG returns valid topological order', () => { |
5 | 5 | const V = 6;
|
6 |
| - const edges = [ |
7 |
| - [5, 2], |
8 |
| - [5, 0], |
9 |
| - [4, 0], |
10 |
| - [4, 1], |
11 |
| - [2, 3], |
12 |
| - [3, 1], |
13 |
| - ]; |
14 |
| - |
| 6 | + const edges = [[5,2],[5,0],[4,0],[4,1],[2,3],[3,1]]; |
15 | 7 | const order = kahnTopologicalSort(V, edges);
|
16 | 8 | expect(order.length).toBe(V);
|
17 |
| - |
18 |
| - // verify topological property |
19 |
| - const pos = new Array(V); |
| 9 | + const pos = Array(V); |
20 | 10 | for (let i = 0; i < order.length; i++) pos[order[i]] = i;
|
21 |
| - |
22 |
| - for (const [u, v] of edges) { |
23 |
| - expect(pos[u]).toBeLessThan(pos[v]); |
24 |
| - } |
| 11 | + for (const [u,v] of edges) expect(pos[u]).toBeLessThan(pos[v]); |
25 | 12 | });
|
26 | 13 |
|
27 |
| - test('returns empty array when graph contains a cycle', () => { |
| 14 | + test('Cycle returns empty array', () => { |
28 | 15 | const V = 3;
|
29 |
| - const edges = [ |
30 |
| - [0, 1], |
31 |
| - [1, 2], |
32 |
| - [2, 0] // cycle |
33 |
| - ]; |
34 |
| - const order = kahnTopologicalSort(V, edges); |
35 |
| - expect(order).toEqual([]); |
| 16 | + const edges = [[0,1],[1,2],[2,0]]; |
| 17 | + expect(kahnTopologicalSort(V, edges)).toEqual([]); |
36 | 18 | });
|
37 | 19 |
|
38 |
| - test('handles isolated nodes', () => { |
| 20 | + test('Includes isolated nodes', () => { |
39 | 21 | const V = 4;
|
40 |
| - const edges = [ |
41 |
| - [0, 1], |
42 |
| - [2, 3] |
43 |
| - ]; |
| 22 | + const edges = [[0,1],[2,3]]; |
44 | 23 | const order = kahnTopologicalSort(V, edges);
|
45 |
| - expect(order.length).toBe(4); |
46 |
| - |
47 |
| - const pos = new Array(V); |
| 24 | + expect(order.length).toBe(V); |
| 25 | + const pos = Array(V); |
48 | 26 | for (let i = 0; i < order.length; i++) pos[order[i]] = i;
|
49 |
| - for (const [u, v] of edges) { |
50 |
| - expect(pos[u]).toBeLessThan(pos[v]); |
51 |
| - } |
| 27 | + for (const [u,v] of edges) expect(pos[u]).toBeLessThan(pos[v]); |
52 | 28 | });
|
53 | 29 | });
|
0 commit comments