I am using BitSet class in Java to deal with set of bits. When comparing two BitSet I need to make a clear distinction between the notion of subset and the notion of intersection.
Let's see an example with the AND operator to get the subset:
BitSet bits1 = new BitSet();
BitSet bits2 = new BitSet();
bits1.set(0,2,true); //110
bits2.set(1); //010
//010 is a SUBSET of 110
bits1.and(bits2); //bits1 became the result of the and operator
if(bits1.equals(bits2))
{
System.out.println(bits2 + " is a subset of " + bits1);
}
//PRINT
BitSet bits4 = new BitSet();
bits4.set(0,2,true); //110
BitSet bits3 = new BitSet();
bits3.set(1,3,true); //011
bits4.and(bits3);
//011 is NOT a subset of 110
if(bits4.equals(bits3))
{
System.out.println(bits4 + " is a subset of " + bits3);
}
//NO PRINT
The subset is pretty clear since I use the AND operator to verify is a BitSet is the subset of the another.
The same example with the built-in intersection operator:
BitSet bits1 = new BitSet();
BitSet bits2 = new BitSet();
bits1.set(0,2,true); //110
bits2.set(1); //010
//010 intersect 110, but is also a subset of 110
System.out.println("Intersection? " + bits2.intersects(bits1));
BitSet bits3 = new BitSet();
bits3.set(1,3,true); //011
//011 VS 110 intersection only
System.out.println("Intersection? " + bits3.intersects(bits1));
Here's my issue: the operator intersection detect both subset and intersection. My goal is to detect only the intersections excluding those ones that are also subset, like bits1 vs bits2 in the second example. So this operator is not suitable for my case because is too general. Is there a way to detect this property?
Take the cardinality of bits1 bits2 and bits1.and(bits2). If the and-cardinality is nonzero, the sets intersect. If it also equal to bits1 cardinality, then bits1 is a subset of bits2 and vice versa.
So using cardinality you can check the subset relationship as you want (but it doesn't seem much faster than the checks you already mentioned in your answer and can combine).