Search code examples
c#arraysalgorithmcollisionbitarray

Fastest way to check C# BitArray for non-zero value


I'm trying to rapidly detect collisions between BitArrays in C# (using the AND boolean operation), which results in a single BitArray representing the overlapping region.

Obviously, if the resulting array only consists of zeroes, there is no collision. What is the fastest way to check this? Simple iteration is too slow. I don't care where collisions are, or how many there are--only that there's a nonzero value somewhere in the array.

It seems like there should be some sort of fast case along the lines of "cast the entire bit array to an int value" (which specifically won't work because BitArrays are variable size), but I can't figure one out.


Solution

  • Do you need the resulting BitArray of the And() method? If not, you could just loop through the input arrays and return true on the first collision.

    bool collision(BitArray a1, BitArray a2) {
       if (a1 == null || a2 == null) throw new ArgumentException("arguments cannot be null");
       if (a1.Count != a2.Count) throw new ArgumentException("arrays don't have same length");
       for (int i = 0; i < a1.Count; i++)
           if (a1[i] && a2[i]) return true;
    
       return false;
    }
    

    This way you an prevent looping the Array twice -- ie. once for the And() and once for checking. In average you will traverse only half of the array once, thus speed things up to 4 times.

    Another way is. like @itsme86 suggested use ints instead of BitArrays

    int a1, a2;
    bool collision = (a1 & a2) > 0;