having new variable 'inter' in-between "reorder/antialias" and "hybrid" in order...
[IRC.git] / Robust / src / Util / UtilAlgorithms.java
1 package Util;
2 import java.util.*;
3
4 // this class has static methods that implement useful,
5 // non-trivially algorithms to prevent code duplication
6 // and reduce bugs
7
8 public class UtilAlgorithms {
9
10   // This method merge hashtable b into a, where the
11   // tables both have HashSets as the values.  If both
12   // tables have a common key, the new value is the
13   // union of the sets the key mapped to in each one.
14   // Note: the reason it must be a HashSet instead of
15   // a Set is that we want to clone sets of table b, so
16   // only a is modified.  Set does not provide clone().
17   static public void mergeHashtablesWithHashSetValues(Hashtable a,
18                                                       Hashtable b) {
19     Iterator itr = b.entrySet().iterator();
20     while( itr.hasNext() ) {
21       Map.Entry me  = (Map.Entry)itr.next();
22       Object key = (Object)    me.getKey();
23       HashSet s1  = (HashSet)   me.getValue();
24       HashSet s2  = (HashSet)   a.get(key);
25
26       if( s2 == null ) {
27         a.put(key, s1.clone() );
28       } else {
29         s2.addAll(s1);
30       }
31     }
32   }
33
34
35   // This method makes hashtable a the intersection of
36   // itself and hashtable b, where the new key set is the
37   // intersection.  The values are sets, so if a key is
38   // common its new value should be the intersection of
39   // the existing values in a and b.  If a new value is
40   // the empty set, then also remove that key.
41   static public void intersectHashtablesWithSetValues(Hashtable a,
42                                                       Hashtable b) {
43     Set keysToRemove = new HashSet();
44
45     Iterator mapItr = a.entrySet().iterator();
46     while( mapItr.hasNext() ) {
47       Map.Entry me    = (Map.Entry)mapItr.next();
48       Object akey  = (Object)    me.getKey();
49       Set avals = (Set)       me.getValue();
50       Set bvals = (Set)       b.get(akey);
51
52       if( bvals == null ) {
53         // if b doesn't have the key, mark it for
54         // safe removal after we traverse the map
55         keysToRemove.add(akey);
56
57       } else {
58         // otherwise we have the key, but pare
59         // down the value set, if needed, and if
60         // nothing is left, remove the key, too
61         avals.retainAll(bvals);
62         if( avals.isEmpty() ) {
63           keysToRemove.add(akey);
64         }
65       }
66     }
67
68     // then safely remove keys
69     Iterator keyItr = keysToRemove.iterator();
70     while( keyItr.hasNext() ) {
71       Object key = keyItr.next();
72       a.remove(key);
73     }
74   }
75
76 }