-
-
Notifications
You must be signed in to change notification settings - Fork 92
/
static-interval-tree.js
387 lines (306 loc) · 8.89 KB
/
static-interval-tree.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
/*
* Mnemonist StaticIntervalTree
* =============================
*
* JavaScript implementation of a static interval tree. This tree is static in
* that you are required to know all its items beforehand and to built it
* from an iterable.
*
* This implementation represents the interval tree as an augmented balanced
* binary search tree. It works by sorting the intervals by startpoint first
* then proceeds building the augmented balanced BST bottom-up from the
* sorted list.
*
* Note that this implementation considers every given intervals as closed for
* simplicity's sake.
*
* For more information: https://en.wikipedia.org/wiki/Interval_tree
*/
var iterables = require('./utils/iterables.js'),
typed = require('./utils/typed-arrays.js');
var FixedStack = require('./fixed-stack.js');
// TODO: pass index to getters
// TODO: custom comparison
// TODO: possibility to pass offset buffer
// TODO: intervals() => Symbol.iterator
// TODO: dfs()
/**
* Helpers.
*/
/**
* Recursive function building the BST from the sorted list of interval
* indices.
*
* @param {array} intervals - Array of intervals to index.
* @param {function} endGetter - Getter function for end of intervals.
* @param {array} sortedIndices - Sorted indices of the intervals.
* @param {array} tree - BST memory.
* @param {array} augmentations - Array of node augmentations.
* @param {number} i - BST index of current node.
* @param {number} low - Dichotomy low index.
* @param {number} high - Dichotomy high index.
* @return {number} - Created node augmentation value.
*/
function buildBST(
intervals,
endGetter,
sortedIndices,
tree,
augmentations,
i,
low,
high
) {
var mid = (low + (high - low) / 2) | 0,
midMinusOne = ~-mid,
midPlusOne = -~mid;
var current = sortedIndices[mid];
tree[i] = current + 1;
var end = endGetter ? endGetter(intervals[current]) : intervals[current][1];
var left = i * 2 + 1,
right = i * 2 + 2;
var leftEnd = -Infinity,
rightEnd = -Infinity;
if (low <= midMinusOne) {
leftEnd = buildBST(
intervals,
endGetter,
sortedIndices,
tree,
augmentations,
left,
low,
midMinusOne
);
}
if (midPlusOne <= high) {
rightEnd = buildBST(
intervals,
endGetter,
sortedIndices,
tree,
augmentations,
right,
midPlusOne,
high
);
}
var augmentation = Math.max(end, leftEnd, rightEnd);
var augmentationPointer = current;
if (augmentation === leftEnd)
augmentationPointer = augmentations[tree[left] - 1];
else if (augmentation === rightEnd)
augmentationPointer = augmentations[tree[right] - 1];
augmentations[current] = augmentationPointer;
return augmentation;
}
/**
* StaticIntervalTree.
*
* @constructor
* @param {array} intervals - Array of intervals to index.
* @param {array<function>} getters - Optional getters.
*/
function StaticIntervalTree(intervals, getters) {
// Properties
this.size = intervals.length;
this.intervals = intervals;
var startGetter = null,
endGetter = null;
if (Array.isArray(getters)) {
startGetter = getters[0];
endGetter = getters[1];
}
// Building the indices array
var length = intervals.length;
var IndicesArray = typed.getPointerArray(length + 1);
var indices = new IndicesArray(length);
var i;
for (i = 1; i < length; i++)
indices[i] = i;
// Sorting indices array
// TODO: check if some version of radix sort can outperform this part
indices.sort(function(a, b) {
a = intervals[a];
b = intervals[b];
if (startGetter) {
a = startGetter(a);
b = startGetter(b);
}
else {
a = a[0];
b = b[0];
}
if (a < b)
return -1;
if (a > b)
return 1;
// TODO: use getters
// TODO: this ordering has the following invariant: if query interval
// contains [nodeStart, max], then whole right subtree can be collected
// a = a[1];
// b = b[1];
// if (a < b)
// return 1;
// if (a > b)
// return -1;
return 0;
});
// Building the binary tree
var height = Math.ceil(Math.log2(length + 1)),
treeSize = Math.pow(2, height) - 1;
var tree = new IndicesArray(treeSize);
var augmentations = new IndicesArray(length);
buildBST(
intervals,
endGetter,
indices,
tree,
augmentations,
0,
0,
length - 1
);
// Dropping indices
indices = null;
// Storing necessary information
this.height = height;
this.tree = tree;
this.augmentations = augmentations;
this.startGetter = startGetter;
this.endGetter = endGetter;
// Initializing DFS stack
this.stack = new FixedStack(IndicesArray, this.height);
}
/**
* Method returning a list of intervals containing the given point.
*
* @param {any} point - Target point.
* @return {array}
*/
StaticIntervalTree.prototype.intervalsContainingPoint = function(point) {
var matches = [];
var stack = this.stack;
stack.clear();
stack.push(0);
var l = this.tree.length;
var bstIndex,
intervalIndex,
interval,
maxInterval,
start,
end,
max,
left,
right;
while (stack.size) {
bstIndex = stack.pop();
intervalIndex = this.tree[bstIndex] - 1;
interval = this.intervals[intervalIndex];
maxInterval = this.intervals[this.augmentations[intervalIndex]];
max = this.endGetter ? this.endGetter(maxInterval) : maxInterval[1];
// No possible match, point is farther right than the max end value
if (point > max)
continue;
// Searching left
left = bstIndex * 2 + 1;
if (left < l && this.tree[left] !== 0)
stack.push(left);
start = this.startGetter ? this.startGetter(interval) : interval[0];
end = this.endGetter ? this.endGetter(interval) : interval[1];
// Checking current node
if (point >= start && point <= end)
matches.push(interval);
// If the point is to the left of the start of the current interval,
// then it cannot be in the right child
if (point < start)
continue;
// Searching right
right = bstIndex * 2 + 2;
if (right < l && this.tree[right] !== 0)
stack.push(right);
}
return matches;
};
/**
* Method returning a list of intervals overlapping the given interval.
*
* @param {any} interval - Target interval.
* @return {array}
*/
StaticIntervalTree.prototype.intervalsOverlappingInterval = function(interval) {
var intervalStart = this.startGetter ? this.startGetter(interval) : interval[0],
intervalEnd = this.endGetter ? this.endGetter(interval) : interval[1];
var matches = [];
var stack = this.stack;
stack.clear();
stack.push(0);
var l = this.tree.length;
var bstIndex,
intervalIndex,
currentInterval,
maxInterval,
start,
end,
max,
left,
right;
while (stack.size) {
bstIndex = stack.pop();
intervalIndex = this.tree[bstIndex] - 1;
currentInterval = this.intervals[intervalIndex];
maxInterval = this.intervals[this.augmentations[intervalIndex]];
max = this.endGetter ? this.endGetter(maxInterval) : maxInterval[1];
// No possible match, start is farther right than the max end value
if (intervalStart > max)
continue;
// Searching left
left = bstIndex * 2 + 1;
if (left < l && this.tree[left] !== 0)
stack.push(left);
start = this.startGetter ? this.startGetter(currentInterval) : currentInterval[0];
end = this.endGetter ? this.endGetter(currentInterval) : currentInterval[1];
// Checking current node
if (intervalEnd >= start && intervalStart <= end)
matches.push(currentInterval);
// If the end is to the left of the start of the current interval,
// then it cannot be in the right child
if (intervalEnd < start)
continue;
// Searching right
right = bstIndex * 2 + 2;
if (right < l && this.tree[right] !== 0)
stack.push(right);
}
return matches;
};
/**
* Convenience known methods.
*/
StaticIntervalTree.prototype.inspect = function() {
var proxy = this.intervals.slice();
// Trick so that node displays the name of the constructor
Object.defineProperty(proxy, 'constructor', {
value: StaticIntervalTree,
enumerable: false
});
return proxy;
};
if (typeof Symbol !== 'undefined')
StaticIntervalTree.prototype[Symbol.for('nodejs.util.inspect.custom')] = StaticIntervalTree.prototype.inspect;
/**
* Static @.from function taking an arbitrary iterable & converting it into
* a structure.
*
* @param {Iterable} iterable - Target iterable.
* @return {StaticIntervalTree}
*/
StaticIntervalTree.from = function(iterable, getters) {
if (iterables.isArrayLike(iterable))
return new StaticIntervalTree(iterable, getters);
return new StaticIntervalTree(Array.from(iterable), getters);
};
/**
* Exporting.
*/
module.exports = StaticIntervalTree;