-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex1.js
More file actions
50 lines (38 loc) · 1.16 KB
/
ex1.js
File metadata and controls
50 lines (38 loc) · 1.16 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
'use strict';
/*
Problem:
Implement `detectReferenceCycle(graph)`.
Input:
- `graph` is an adjacency list object where keys are node ids and values are
arrays of outgoing references.
Example:
{
A: ['B'],
B: ['C'],
C: ['A']
}
Output:
- Return `true` if the graph contains any reference cycle.
- Return `false` otherwise.
Why this exercise matters:
- Pure reference counting cannot reclaim unreachable cycles.
- Tracing collectors must detect reachability globally.
Starter code is intentionally incorrect. It assumes inbound-count patterns are
sufficient to detect cycles.
*/
function detectReferenceCycle(graph) {
if (!graph || typeof graph !== 'object' || Array.isArray(graph)) {
throw new TypeError('graph must be an adjacency-list object');
}
const inboundCount = {};
for (const node of Object.keys(graph)) {
if (!Array.isArray(graph[node])) {
throw new TypeError('each adjacency list must be an array');
}
for (const neighbor of graph[node]) {
inboundCount[neighbor] = (inboundCount[neighbor] || 0) + 1;
}
}
return Object.values(inboundCount).some((count) => count > 1);
}
module.exports = { detectReferenceCycle };