aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/store-query/src/main/java/tools/refinery/store/query/utils/OrderStatisticTree.java
blob: b568b99d950a7a5fae799ac922c2354fd22781dd (plain) (blame)
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
/*
 * Copyright (c) 2021 Rodion Efremov
 * Copyright (c) 2023 The Refinery Authors <https://refinery.tools/>
 *
 * SPDX-License-Identifier: MIT OR EPL-2.0
 */
package tools.refinery.store.query.utils;

import java.util.*;

/**
 * This class implements an order statistic tree which is based on AVL-trees.
 * <p>
 * This class was copied into <i>Refinery</i> from
 * <a href="https://github.com/coderodde/OrderStatisticTree/tree/546c343b9f5d868e394a079ff32691c9dbfd83e3">https://github.com/coderodde/OrderStatisticTree</a>
 * and is available under the
 * <a href="https://github.com/coderodde/OrderStatisticTree/blob/master/LICENSE">MIT License</a>.
 * We also incorporated changes by <a href="https://github.com/coderodde/OrderStatisticTree/issues/3">Eugene Schava</a>
 * and cleaned up some linter warnings.
 *
 * @param <T> the actual element type.
 * @author Rodion "rodde" Efremov
 * @version based on 1.6 (Feb 11, 2016)
 */
public class OrderStatisticTree<T extends Comparable<? super T>> implements Set<T> {

	@Override
	public Iterator<T> iterator() {
		return new TreeIterator();
	}

	private final class TreeIterator implements Iterator<T> {

		private Node<T> previousNode;
		private Node<T> nextNode;
		private int expectedModCount = modCount;

		TreeIterator() {
			if (root == null) {
				nextNode = null;
			} else {
				nextNode = minimumNode(root);
			}
		}

		@Override
		public boolean hasNext() {
			return nextNode != null;
		}

		@Override
		public T next() {
			if (nextNode == null) {
				throw new NoSuchElementException("Iteration exceeded.");
			}

			checkConcurrentModification();
			T datum = nextNode.key;
			previousNode = nextNode;
			nextNode = successorOf(nextNode);
			return datum;
		}

		@Override
		public void remove() {
			if (previousNode == null) {
				throw new IllegalStateException(
						nextNode == null ?
								"Not a single call to next(); nothing to remove." :
								"Removing the same element twice."
				);
			}

			checkConcurrentModification();

			Node<T> x = deleteNode(previousNode);
			fixAfterModification(x, false);

			if (x == nextNode) {
				nextNode = previousNode;
			}

			expectedModCount = ++modCount;
			size--;
			previousNode = null;
		}

		private void checkConcurrentModification() {
			if (expectedModCount != modCount) {
				throw new ConcurrentModificationException(
						"The set was modified while iterating.");
			}
		}

		private Node<T> successorOf(Node<T> node) {
			if (node.right != null) {
				node = node.right;

				while (node.left != null) {
					node = node.left;
				}

				return node;
			}

			Node<T> parent = node.parent;

			while (parent != null && parent.right == node) {
				node = parent;
				parent = parent.parent;
			}

			return parent;
		}
	}

	@Override
	public Object[] toArray() {
		Object[] array = new Object[size];
		Iterator<T> iterator = iterator();
		int index = 0;

		while (iterator.hasNext()) {
			array[index++] = iterator.next();
		}

		return array;
	}

	@Override
	public <U> U[] toArray(U[] a) {
		Iterator<T> iterator = iterator();

		if (size > a.length) {
			a = Arrays.copyOf(a, size);
		}

		int index = 0;

		for (; index < size; ++index) {
			@SuppressWarnings("unchecked")
			var convertedValue = (U) iterator.next();
			a[index] = convertedValue;
		}

		if (index < a.length) {
			a[index] = null;
		}

		return a;
	}

	@Override
	public boolean containsAll(Collection<?> c) {
		for (Object element : c) {
			if (!contains(element)) {
				return false;
			}
		}

		return true;
	}

	@Override
	public boolean addAll(Collection<? extends T> c) {
		boolean modified = false;

		for (T element : c) {
			if (add(element)) {
				modified = true;
			}
		}

		return modified;
	}

	@Override
	public boolean retainAll(Collection<?> c) {
		if (!c.getClass().equals(HashSet.class)) {
			c = new HashSet<>(c);
		}

		Iterator<T> iterator = iterator();
		boolean modified = false;

		while (iterator.hasNext()) {
			T element = iterator.next();

			if (!c.contains(element)) {
				iterator.remove();
				modified = true;
			}
		}

		return modified;
	}

	@Override
	public boolean removeAll(Collection<?> c) {
		boolean modified = false;

		for (Object element : c) {
			if (remove(element)) {
				modified = true;
			}
		}

		return modified;
	}

	private static final class Node<T> {
		T key;

		Node<T> parent;
		Node<T> left;
		Node<T> right;

		int height;
		int count;

		Node(T key) {
			this.key = key;
		}
	}

	private Node<T> root;
	private int size;
	private int modCount;

	@Override
	public boolean add(T element) {
		Objects.requireNonNull(element, "The input element is null.");

		if (root == null) {
			root = new Node<>(element);
			size = 1;
			modCount++;
			return true;
		}

		Node<T> parent = null;
		Node<T> node = root;
		int cmp;

		while (node != null) {
			cmp = element.compareTo(node.key);

			if (cmp == 0) {
				// The element is already in this tree.
				return false;
			}

			parent = node;

			if (cmp < 0) {
				node = node.left;
			} else {
				node = node.right;
			}
		}

		Node<T> newnode = new Node<>(element);

		if (element.compareTo(parent.key) < 0) {
			parent.left = newnode;
		} else {
			parent.right = newnode;
		}

		newnode.parent = parent;
		size++;
		modCount++;
		Node<T> hi = parent;
		Node<T> lo = newnode;

		while (hi != null) {
			if (hi.left == lo) {
				hi.count++;
			}

			lo = hi;
			hi = hi.parent;
		}

		fixAfterModification(newnode, true);
		return true;
	}

	@Override
	public boolean contains(Object o) {
		@SuppressWarnings("unchecked")
		T element = (T) o;
		Node<T> x = root;
		int cmp;

		while (x != null && (cmp = element.compareTo(x.key)) != 0) {
			if (cmp < 0) {
				x = x.left;
			} else {
				x = x.right;
			}
		}

		return x != null;
	}

	@Override
	public boolean remove(Object o) {
		@SuppressWarnings("unchecked")
		T element = (T) o;
		Node<T> x = root;
		int cmp;

		while (x != null && (cmp = element.compareTo(x.key)) != 0) {
			if (cmp < 0) {
				x = x.left;
			} else {
				x = x.right;
			}
		}

		if (x == null) {
			return false;
		}

		x = deleteNode(x);
		fixAfterModification(x, false);
		size--;
		modCount++;
		return true;
	}

	public T get(int index) {
		checkIndex(index);
		Node<T> node = root;

		while (true) {
			if (index > node.count) {
				index -= node.count + 1;
				node = node.right;
			} else if (index < node.count) {
				node = node.left;
			} else {
				return node.key;
			}
		}
	}

	public int indexOf(T element) {
		Node<T> node = root;

		if (root == null) {
			return -1;
		}

		int rank = root.count;
		int cmp;

		while (true) {
			if ((cmp = element.compareTo(node.key)) < 0) {
				if (node.left == null) {
					return -1;
				}

				rank -= (node.count - node.left.count);
				node = node.left;
			} else if (cmp > 0) {
				if (node.right == null) {
					return -1;
				}

				rank += 1 + node.right.count;
				node = node.right;
			} else {
				return rank;
			}
		}
	}

	@Override
	public int size() {
		return size;
	}

	@Override
	public boolean isEmpty() {
		return size == 0;
	}

	@Override
	public void clear() {
		modCount += size;
		root = null;
		size = 0;
	}


	private void checkIndex(int index) {
		if (index < 0) {
			throw new IndexOutOfBoundsException(
					"The input index is negative: " + index);
		}

		if (index >= size) {
			throw new IndexOutOfBoundsException(
					"The input index is too large: " + index +
							", the size of this tree is " + size);
		}
	}

	@SuppressWarnings("squid:S3776")
	private Node<T> deleteNode(Node<T> node) {
		if (node.left == null && node.right == null) {
			// 'node' has no children.
			Node<T> parent = node.parent;

			if (parent == null) {
				// 'node' is the root node of this tree.
				root = null;
				++modCount;
				return node;
			}

			Node<T> lo = node;
			Node<T> hi = parent;

			while (hi != null) {
				if (hi.left == lo) {
					hi.count--;
				}

				lo = hi;
				hi = hi.parent;
			}

			if (node == parent.left) {
				parent.left = null;
			} else {
				parent.right = null;
			}

			return node;
		}

		if (node.left != null && node.right != null) {
			// 'node' has both children.
			Node<T> successor = minimumNode(node.right);
			node.key = successor.key;
			Node<T> child = successor.right;
			Node<T> parent = successor.parent;

			if (parent.left == successor) {
				parent.left = child;
			} else {
				parent.right = child;
			}

			if (child != null) {
				child.parent = parent;
			}

			Node<T> lo = child;
			Node<T> hi = parent;

			while (hi != null) {
				if (hi.left == lo) {
					hi.count--;
				}

				lo = hi;
				hi = hi.parent;
			}

			return successor;
		}

		Node<T> child;

		// 'node' has only one child.
		if (node.left != null) {
			child = node.left;
		} else {
			child = node.right;
		}

		Node<T> parent = node.parent;
		child.parent = parent;

		if (parent == null) {
			root = child;
			return node;
		}

		if (node == parent.left) {
			parent.left = child;
		} else {
			parent.right = child;
		}

		Node<T> hi = parent;
		Node<T> lo = child;

		while (hi != null) {
			if (hi.left == lo) {
				hi.count--;
			}

			lo = hi;
			hi = hi.parent;
		}

		return node;

	}

	private Node<T> minimumNode(Node<T> node) {
		while (node.left != null) {
			node = node.left;
		}

		return node;
	}

	private int height(Node<T> node) {
		return node == null ? -1 : node.height;
	}

	private Node<T> leftRotate(Node<T> node1) {
		Node<T> node2 = node1.right;
		node2.parent = node1.parent;
		node1.parent = node2;
		node1.right = node2.left;
		node2.left = node1;

		if (node1.right != null) {
			node1.right.parent = node1;
		}

		node1.height = Math.max(height(node1.left), height(node1.right)) + 1;
		node2.height = Math.max(height(node2.left), height(node2.right)) + 1;
		node2.count += node1.count + 1;
		return node2;
	}

	private Node<T> rightRotate(Node<T> node1) {
		Node<T> node2 = node1.left;
		node2.parent = node1.parent;
		node1.parent = node2;
		node1.left = node2.right;
		node2.right = node1;

		if (node1.left != null) {
			node1.left.parent = node1;
		}

		node1.height = Math.max(height(node1.left), height(node1.right)) + 1;
		node2.height = Math.max(height(node2.left), height(node2.right)) + 1;
		node1.count -= node2.count + 1;
		return node2;
	}

	private Node<T> rightLeftRotate(Node<T> node1) {
		Node<T> node2 = node1.right;
		node1.right = rightRotate(node2);
		return leftRotate(node1);
	}

	private Node<T> leftRightRotate(Node<T> node1) {
		Node<T> node2 = node1.left;
		node1.left = leftRotate(node2);
		return rightRotate(node1);
	}

	// Fixing an insertion: use insertionMode = true.
	// Fixing a deletion: use insertionMode = false.
	@SuppressWarnings("squid:S3776")
	private void fixAfterModification(Node<T> node, boolean insertionMode) {
		Node<T> parent = node.parent;
		Node<T> grandParent;
		Node<T> subTree;

		while (parent != null) {
			if (height(parent.left) == height(parent.right) + 2) {
				grandParent = parent.parent;

				if (height(parent.left.left) >= height(parent.left.right)) {
					subTree = rightRotate(parent);
				} else {
					subTree = leftRightRotate(parent);
				}

				if (grandParent == null) {
					root = subTree;
				} else if (grandParent.left == parent) {
					grandParent.left = subTree;
				} else {
					grandParent.right = subTree;
				}

				if (grandParent != null) {
					grandParent.height = Math.max(
							height(grandParent.left),
							height(grandParent.right)) + 1;
				}

				if (insertionMode) {
					// Whenever fixing after insertion, at most one rotation is
					// required in order to maintain the balance.
					return;
				}
			} else if (height(parent.right) == height(parent.left) + 2) {
				grandParent = parent.parent;

				if (height(parent.right.right) >= height(parent.right.left)) {
					subTree = leftRotate(parent);
				} else {
					subTree = rightLeftRotate(parent);
				}

				if (grandParent == null) {
					root = subTree;
				} else if (grandParent.left == parent) {
					grandParent.left = subTree;
				} else {
					grandParent.right = subTree;
				}

				if (grandParent != null) {
					grandParent.height =
							Math.max(height(grandParent.left),
									height(grandParent.right)) + 1;
				}

				if (insertionMode) {
					return;
				}
			}

			parent.height = Math.max(height(parent.left),
					height(parent.right)) + 1;
			parent = parent.parent;
		}
	}

	boolean isHealthy() {
		if (root == null) {
			return true;
		}

		return !containsCycles()
				&& heightsAreCorrect()
				&& isBalanced()
				&& isWellIndexed();
	}

	private boolean containsCycles() {
		Set<Node<T>> visitedNodes = new HashSet<>();
		return containsCycles(root, visitedNodes);
	}

	private boolean containsCycles(Node<T> current, Set<Node<T>> visitedNodes) {
		if (current == null) {
			return false;
		}

		if (visitedNodes.contains(current)) {
			return true;
		}

		visitedNodes.add(current);

		return containsCycles(current.left, visitedNodes)
				|| containsCycles(current.right, visitedNodes);
	}

	private boolean heightsAreCorrect() {
		return getHeight(root) == root.height;
	}

	private int getHeight(Node<T> node) {
		if (node == null) {
			return -1;
		}

		int leftTreeHeight = getHeight(node.left);

		if (leftTreeHeight == Integer.MIN_VALUE) {
			return Integer.MIN_VALUE;
		}

		int rightTreeHeight = getHeight(node.right);

		if (rightTreeHeight == Integer.MIN_VALUE) {
			return Integer.MIN_VALUE;
		}

		if (node.height == Math.max(leftTreeHeight, rightTreeHeight) + 1) {
			return node.height;
		}

		return Integer.MIN_VALUE;
	}

	private boolean isBalanced() {
		return isBalanced(root);
	}

	private boolean isBalanced(Node<T> node) {
		if (node == null) {
			return true;
		}

		if (!isBalanced(node.left)) {
			return false;
		}

		if (!isBalanced(node.right)) {
			return false;
		}

		int leftHeight = height(node.left);
		int rightHeight = height(node.right);

		return Math.abs(leftHeight - rightHeight) < 2;
	}

	private boolean isWellIndexed() {
		return size == count(root);
	}

	private int count(Node<T> node) {
		if (node == null) {
			return 0;
		}

		int leftTreeSize = count(node.left);

		if (leftTreeSize == Integer.MIN_VALUE) {
			return Integer.MIN_VALUE;
		}

		if (node.count != leftTreeSize) {
			return Integer.MIN_VALUE;
		}

		int rightTreeSize = count(node.right);

		if (rightTreeSize == Integer.MIN_VALUE) {
			return Integer.MIN_VALUE;
		}

		return leftTreeSize + 1 + rightTreeSize;
	}
}