-
Notifications
You must be signed in to change notification settings - Fork 0
/
floyd.js
215 lines (180 loc) · 5.8 KB
/
floyd.js
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/**
* @module floyd
*/
var _ = require('underscore');
var defaultOptions = {
outEdgePropertyName: 'out',
inEdgePropertyName: 'in',
normalizePath: false,
};
var exports = {
floyd: floyd,
detectCycles: detectCycles,
normalizePath: normalizePath,
_defaultOptions: _.clone(defaultOptions),
version: require('./package.json').version
};
/**
* The Floyd algorithm.
* @param {Path} path - A vector of nodes.
* @param {Number} start - The starting node.
* @param {Options} options
* @returns {Cycle} An object describing a detected cycle.
*/
function floyd(path, start, _options) {
var options = _.defaults(_options || {}, defaultOptions);
if (options.normalizePath) {
path = normalizePath(path, options);
}
var nextAll = nextFn(path, options);
var start = start === undefined ? 0 : start;
// First step
var tortoises = nextAll([start]);
var hares = nextAll(nextAll([start]));
// Ensure both pointers are inside cycle, by stepping
// the hares twice as fast through it.
while (_.intersection(tortoises, hares).length === 0) {
// If the trailing pointer has no out nodes, we've
// gotten through the entire graph.
if (tortoises.length === 0) {
return null;
}
tortoises = nextAll(tortoises);
hares = nextAll(nextAll(hares));
}
// Knowing the leading pointer is somewhere in the cycle
// we return the trailing pointer to start, and move both
// pointers forward until they meet. Due to the initial
// case of the leading pointer having twice the velocity
// of the trailing one, they will meet again at the cycle's
// starting point.
var mu = 0;
var tortoises = [start];
while (_.intersection(tortoises, hares).length === 0) {
tortoises = nextAll(tortoises);
hares = nextAll(hares);
mu += 1;
}
// Walk along out edges from the pointer known to be
// inside the cycle, counting the steps until the leading
// pointer has gone all the way around.
var lambda = 1;
var tortoises = _.intersection(tortoises, hares);
var hares = nextAll(tortoises);
while (_.intersection(tortoises, hares).length === 0) {
hares = nextAll(hares);
lambda += 1;
}
return {
firstKey: tortoises[0],
stepsFromStart: mu,
length: lambda
};
}
/**
* Runs the floyd algorithm with each node in the array
* as the starting point, to ensure all potentially
* disconnected paths are checked.
*
* @param {Path} path - An array of nodes. Each node should have an 'out' property with an array.
* @param {Options} options
* @returns {Cycle[]} - A set of detected cycles.
*/
function detectCycles(path, options) {
var knownCycleKeys = [];
var cycles = _.map(path, function (edges, key) {
var _options = _.defaults(options || {}, {
excludeIndices: knownCycleKeys
});
var cycle = floyd(path, key, _options);
if (cycle) {
knownCycleKeys.push(cycle.firstKey);
}
return cycle;
});
return _.compact(cycles);
}
/**
* Turn in-edges into out-edges.
*
* @param path {Path} - An un-normalized path, potentially containing in-edge properties.
* @param options {Options}
* @returns {Path} - A normalized path, with only out-edges.
*/
function normalizePath(path, _options) {
var options = _.defaults(_options || {}, defaultOptions);
var normalizedPath = _.clone(path);
// Cycle through the nodes in the path to find
// in-node references.
path.forEach(function (node, nodeIndex) {
var inNodes = node[options.inEdgePropertyName] || [];
// Cycle through the nodes to discover out-nodes to add.
inNodes.forEach(function (inNodeIndex) {
var inNode = normalizedPath[inNodeIndex];
// The new set of out nodes is the union between the
// previous set and the currently processed node index.
inNode.out = _.union(inNode[options.outEdgePropertyName], [nodeIndex]);
});
// Clean up the in nodes.
delete normalizedPath[nodeIndex][options.inEdgePropertyName];
});
return normalizedPath;
}
/**
* Returns a set of next nodes, gathered from
* the out params of the given indices. If no
* out param is supplied, we assume the node itself
* is an array of out-node indices.
*
* @private
* @param path {Array} - The path from which to return out-nodes.
* @param outEdgePropertyName {String|null} -
*/
function nextFn(path, options) {
var outNodeIndicesForNodeIndex = function (index) {
var node = path[index];
if (_.isNumber(node)) {
return [node];
}
if (_.isArray(node)) {
return node;
}
return (node && node[options.outEdgePropertyName]) || [];
}
return function (indices) {
return _.chain(indices.map(outNodeIndicesForNodeIndex))
// Flatten the initially nested array.
.flatten()
// Include each next-node only once.
.uniq()
// Exclude indices we want to exclude.
.difference(options.excludeIndices)
// Unpack the chained value.
.value();
}
}
/**
* @typedef Node
* @type object
* @property {array} out - Defines out-edges to these path indices.
* @property {array} in - Defines in-edges from these path indices. Requires normalization.
*/
/**
* @typedef Path
* @type {Node[]|object}
*/
/**
* @typedef Cycle
* @type object
* @property {number} firstIndex
* @property {number} stepsFromStart
* @property {number} length
*/
/**
* @typedef Options
* @type object
* @property {string} [outEdgePropertyName='out']
* @property {string} [inEdgePropertyName='in']
* @property {boolean} [normalizePath=false]
*/
module.exports = exports;