简体   繁体   English

检查 C# BitArray 非零值的最快方法

[英]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.我试图快速检测 C# 中 BitArray 之间的冲突(使用 AND boolean 操作),这导致单个 BitArray 表示重叠区域。

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.似乎应该有某种类似“将整个位数组转换为一个 int 值”的快速案例(具体来说是行不通的,因为 BitArray 的大小是可变的),但我想不出一个。

Do you need the resulting BitArray of the And() method? 您是否需要And()方法的结果BitArray? If not, you could just loop through the input arrays and return true on the first collision. 如果没有,您可以遍历输入数组并在第一次碰撞时返回true。

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. 一次用于And(),一次用于检查。 In average you will traverse only half of the array once, thus speed things up to 4 times. 平均而言,您将仅遍历数组的一半,因此速度最多可以提高4倍。

Another way is. 另一种方法是。 like @itsme86 suggested use ints instead of BitArrays 像@ itsme86建议使用int代替BitArrays

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

Just in case someone is still searching for a nice solution, since it's missing here:以防万一有人仍在寻找一个不错的解决方案,因为这里缺少它:

Bitarrays initialize with zeros, so you could simply compare a fresh BitArray (of the same length) with your AND-result of the two BitArrays (Note the ",". inverting the bool..:): Bitarrays 用零初始化,所以你可以简单地将一个新的 BitArray(相同长度)与你的两个 BitArrays 的 AND 结果进行比较(注意“,”。反转 bool .. :):

if (!new BitArray(bitCountOfResult).Equals(result)) {
    // We hit!
}

Fast and works for me.速度快,适合我。 Make sure to avoid the LINQ-approach, it's very slow.确保避免使用 LINQ 方法,它非常慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM