Debian Codegraph @

src/com/google/javascript/jscomp/graph/StandardUnionFind.java

raw symbols SCIP
1 /*
2 * Copyright 2008 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package com.google.javascript.jscomp.graph;
17
18 import javax.annotation.Nullable;
19 import com.google.common.base.Objects;
20 import static com.google.common.base.Preconditions.checkArgument;
21 import com.google.common.base.Predicate;
22 import com.google.common.collect.ImmutableList;
23 import com.google.common.collect.ImmutableSet;
24
25 import static com.google.common.collect.Iterators.filter;
26 import com.google.common.collect.Maps;
27
28 import java.io.Serializable;
29 import java.util.AbstractSet;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.Iterator;
33 import java.util.Map;
34 import java.util.Set;
35
36 /**
37 * A Union-Find implementation.
38 *
39 * <p>This class implements Union-Find algorithm with rank and path
40 * compression.
41 *
42 * <p>See <a
43 * href="http://www.algorithmist.com/index.php?title=Union_Find&oldid=7575">
44 * algorithmist</a> for more detail.
45 *
46 * @param <E> element type
47 */
48 public class StandardUnionFind<E> implements Serializable, UnionFind<E> {
49
50 private static final long serialVersionUID = -1L;
51
52 /** All values with the same root node are in the same equivalence set. */
53 private final Map<E, Node<E>> elmap = Maps.newLinkedHashMap();
54
55 /** Creates an empty UnionFind structure. */
56 public StandardUnionFind() {
57 }
58
59 /**
60 * Creates an UnionFind structure being a copy of other structure.
61 * The created structure is optimal in a sense that the paths to
62 * the root from any element will have a length of at most 1.
63 *
64 * @param other structure to be copied
65 */
66 public StandardUnionFind(UnionFind<E> other) {
67 for (E elem : other.elements()) {
68 union(elem, other.find(elem));
69 }
70 }
71
72 @Override
73 public void add(E e) {
74 union(e, e);
75 }
76
77 @Override
78 public E union(E a, E b) {
79 Node<E> nodeA = findRootOrCreateNode(a);
80 Node<E> nodeB = findRootOrCreateNode(b);
81
82 if (nodeA == nodeB) {
83 return nodeA.element;
84 }
85 if (nodeA.rank > nodeB.rank) {
86 nodeB.parent = nodeA;
87 nodeA.size += nodeB.size;
88 return nodeA.element;
89 }
90 nodeA.parent = nodeB;
91 if (nodeA.rank == nodeB.rank) {
92 nodeB.rank++;
93 }
94 nodeB.size += nodeA.size;
95 return nodeB.element;
96 }
97
98 @Override
99 public E find(E e) {
100 checkArgument(elmap.containsKey(e), "Element does not exist: %s", e);
101 return findRoot(elmap.get(e)).element;
102 }
103
104 @Override
105 public boolean areEquivalent(E a, E b) {
106 E aRep = find(a);
107 E bRep = find(b);
108 return aRep == bRep;
109 }
110
111 @Override
112 public Set<E> elements() {
113 return Collections.unmodifiableSet(elmap.keySet());
114 }
115
116 @Override
117 public Collection<Set<E>> allEquivalenceClasses() {
118 Map<Node<E>, ImmutableSet.Builder<E>> groupsTmp = Maps.newHashMap();
119 for (Node<E> elem : elmap.values()) {
120 Node<E> root = findRoot(elem);
121 ImmutableSet.Builder<E> builder = groupsTmp.get(root);
122 if (builder == null) {
123 builder = ImmutableSet.builder();
124 groupsTmp.put(root, builder);
125 }
126 builder.add(elem.element);
127 }
128 ImmutableList.Builder<Set<E>> result = ImmutableList.builder();
129 for (ImmutableSet.Builder<E> group : groupsTmp.values()) {
130 result.add(group.build());
131 }
132 return result.build();
133 }
134
135 /**
136 * If e is already in a non-trivial equivalence class, that is, a class with
137 * more than two elements, then return the {@link Node} corresponding to the
138 * representative element. Otherwise, if e sits in an equivalence class by
139 * itself, then create a {@link Node}, put it into elmap and return it.
140 */
141 private Node<E> findRootOrCreateNode(E e) {
142 Node<E> node = elmap.get(e);
143 if (node != null) {
144 return findRoot(node);
145 }
146 node = new Node<E>(e);
147 elmap.put(e, node);
148 return node;
149 }
150
151 /**
152 * Given a {@link Node}, walk the parent field as far as possible, until
153 * reaching the root, which is the {@link Node} for the current
154 * representative of this equivalence class. To achieve low runtime
155 * complexity, also compress the path, by making each node a direct child of
156 * the root.
157 */
158 private Node<E> findRoot(Node<E> node) {
159 if (node.parent != node) {
160 node.parent = findRoot(node.parent);
161 }
162 return node.parent;
163 }
164
165 @Override
166 public Set<E> findAll(final E value) {
167 checkArgument(elmap.containsKey(value), "Element does not exist: " + value);
168
169 final Predicate<Object> isSameRoot = new Predicate<Object>() {
170
171 /** some node that's close to the root, or null */
172 Node<E> nodeForValue = elmap.get(value);
173
174 @Override
175 public boolean apply(@Nullable Object b) {
176 if (Objects.equal(value, b)) {
177 return true;
178 }
179 Node<E> nodeForB = elmap.get(b);
180 if (nodeForB == null) {
181 return false;
182 }
183 nodeForValue = findRoot(nodeForValue);
184 return findRoot(nodeForB) == nodeForValue;
185 }
186 };
187
188 return new AbstractSet<E>() {
189
190 @Override public boolean contains(Object o) {
191 return isSameRoot.apply(o);
192 }
193
194 @Override public Iterator<E> iterator() {
195 return filter(elmap.keySet().iterator(),
196 isSameRoot);
197 }
198
199 @Override public int size() {
200 return findRoot(elmap.get(value)).size;
201 }
202 };
203 }
204
205 /** The internal node representation. */
206 private static class Node<E> {
207 /** The parent node of this element. */
208 Node<E> parent;
209
210 /** The element represented by this node. */
211 final E element;
212
213 /** A bound on the depth of the subtree rooted to this node. */
214 int rank = 0;
215
216 /**
217 * If this node is the root of a tree, this is the number of elements in the
218 * tree. Otherwise, it's undefined.
219 */
220 int size = 1;
221
222 Node(E element) {
223 this.parent = this;
224 this.element = element;
225 }
226 }
227 }