-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathKahn.test.js
More file actions
55 lines (46 loc) · 1.15 KB
/
Kahn.test.js
File metadata and controls
55 lines (46 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { KahnsAlgorithm } from '../Kahn.js'
// Check if a given order is a valid topological sort
function isValidTopologicalOrder(order, numNodes, edges) {
if (order.length !== numNodes) return false
const position = new Map()
order.forEach((node, idx) => position.set(node, idx))
for (const [u, v] of edges) {
// u must come before v in topo order
if (position.get(u) > position.get(v)) return false
}
return true
}
test('Test Case 1', () => {
const numNodes = 6
const edges = [
[5, 2],
[5, 0],
[4, 0],
[4, 1],
[2, 3],
[3, 1]
]
const topoOrder = KahnsAlgorithm(numNodes, edges)
expect(isValidTopologicalOrder(topoOrder, numNodes, edges)).toBe(true)
})
test('Test Case 2', () => {
const numNodes = 4
const edges = [
[0, 1],
[1, 2],
[2, 3]
]
const topoOrder = KahnsAlgorithm(numNodes, edges)
// Only one valid order exists
expect(topoOrder).toStrictEqual([0, 1, 2, 3])
})
test('Test Case 3 (Cycle Detection)', () => {
const numNodes = 3
const edges = [
[0, 1],
[1, 2],
[2, 0]
]
const topoOrder = KahnsAlgorithm(numNodes, edges)
expect(topoOrder).toStrictEqual([])
})