diff options
Diffstat (limited to 'subprojects/viatra-runtime-rete/src/main/java/tools/refinery/viatra/runtime/rete/util/LexicographicComparator.java')
-rw-r--r-- | subprojects/viatra-runtime-rete/src/main/java/tools/refinery/viatra/runtime/rete/util/LexicographicComparator.java | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/subprojects/viatra-runtime-rete/src/main/java/tools/refinery/viatra/runtime/rete/util/LexicographicComparator.java b/subprojects/viatra-runtime-rete/src/main/java/tools/refinery/viatra/runtime/rete/util/LexicographicComparator.java new file mode 100644 index 00000000..0efc50af --- /dev/null +++ b/subprojects/viatra-runtime-rete/src/main/java/tools/refinery/viatra/runtime/rete/util/LexicographicComparator.java | |||
@@ -0,0 +1,58 @@ | |||
1 | /******************************************************************************* | ||
2 | * Copyright (c) 2010-2014, Bergmann Gabor, Istvan Rath and Daniel Varro | ||
3 | * This program and the accompanying materials are made available under the | ||
4 | * terms of the Eclipse Public License v. 2.0 which is available at | ||
5 | * http://www.eclipse.org/legal/epl-v20.html. | ||
6 | * | ||
7 | * SPDX-License-Identifier: EPL-2.0 | ||
8 | *******************************************************************************/ | ||
9 | package tools.refinery.viatra.runtime.rete.util; | ||
10 | |||
11 | import java.util.Comparator; | ||
12 | import java.util.Iterator; | ||
13 | |||
14 | /** | ||
15 | * A comparator that compares two iterables based on the lexicographic sorting induced by a comparator on elements. | ||
16 | * @author Bergmann Gabor | ||
17 | * | ||
18 | */ | ||
19 | public class LexicographicComparator<T> implements Comparator<Iterable<? extends T>> { | ||
20 | |||
21 | final Comparator<T> elementComparator; | ||
22 | |||
23 | public LexicographicComparator(Comparator<T> elementComparator) { | ||
24 | super(); | ||
25 | this.elementComparator = elementComparator; | ||
26 | } | ||
27 | |||
28 | @Override | ||
29 | public int compare(Iterable<? extends T> o1, Iterable<? extends T> o2) { | ||
30 | Iterator<? extends T> it1 = o1.iterator(); | ||
31 | Iterator<? extends T> it2 = o2.iterator(); | ||
32 | |||
33 | boolean has1, has2, bothHaveNext; | ||
34 | do { | ||
35 | has1 = it1.hasNext(); | ||
36 | has2 = it2.hasNext(); | ||
37 | bothHaveNext = has1 && has2; | ||
38 | if (bothHaveNext) { | ||
39 | T element1 = it1.next(); | ||
40 | T element2 = it2.next(); | ||
41 | int elementComparison = elementComparator.compare(element1, element2); | ||
42 | if (elementComparison != 0) | ||
43 | return elementComparison; | ||
44 | } | ||
45 | } while (bothHaveNext); | ||
46 | if (has1 && !has2) { | ||
47 | return +1; | ||
48 | } else if (!has1 && has2) { | ||
49 | return -1; | ||
50 | } else /*if (!has1 && !has2)*/ { | ||
51 | return 0; | ||
52 | } | ||
53 | } | ||
54 | |||
55 | |||
56 | |||
57 | |||
58 | } | ||