Переглянути джерело

Adds calculation of hash for quickly checking Node equality

Caleb Fangmeier 6 роки тому
батько
коміт
a631ebb148
1 змінених файлів з 18 додано та 2 видалено
  1. 18 2
      src/com/pact/Node.java

+ 18 - 2
src/com/pact/Node.java

@@ -12,15 +12,26 @@ public class Node {
     HashSet<Node> linkNodes;
     Node linkNode;
 
+    int hash;
+
     public Node(Node p, String s) {
         this.linkNode = null;
         this.linkNodes = new HashSet<>();
         this.venn = s;
         this.parent = p;
+        this.hash = 0;
 
         this.children = new HashSet<>();
         if (s.length() > 1)
             setChildren(s);
+        if (children.isEmpty()) {
+            hash = (venn.hashCode()*1073676287) ^ (venn.hashCode()*97);
+        } else {
+            for (Node child : children) {
+                hash = hash ^ child.hash;
+            }
+            hash *= 33;
+        }
     }
 
     public Node(Node p, char s) {
@@ -87,11 +98,16 @@ public class Node {
     }
 
     public boolean equals(Object obj) {
-        if (!(obj instanceof Node)) return false;
+        if (this == obj) return true;  // Literally the same object
+        if (!(obj instanceof Node)) return false; // Wrong type
 
         Node node = (Node) obj;
-        String nodeVenn = node.getVenn();
+        if (hash != node.hash) return false; // equal object have equal hash codes
+
+        // If above checks fall through, we need to actually look at the structure
+        // Of the Node.
 
+        String nodeVenn = node.getVenn();
         // Case for leaf nodes
         if ((nodeVenn.length() == 1) && (this.venn.length() == 1)) {
             return nodeVenn.equals(this.venn);