比较两个布尔数组的最有效方法是什么?
我有一个由 10 个布尔值组成的数组 a
(或者相当于数字 <1024 的二进制表示形式)。我想通过以下方式将此数组与一大组相同大小的布尔数组 b[i]
进行比较: 如果数组 a
的元素永远不是 true
,函数 compare(a,b[i])
应返回 true
code> 当b[i]
中相同位置的元素为false
时。
以java为例,
boolean compare(boolean a1, boolean a2){
for (int j = 0; j<10; j++)
if (a1[j] && !a2[j])
return false;
return true;
}
这个功能有没有更好的实现?如果将相应的二进制数视为整数 A1(和 A2)的素数分解的系数,则等效函数将是
boolean compare (int A1, int A2){
if (gcd(A1,A2)==A1)
return true;
else
return false;
}
,例如 (http://www.java-tips.org/java-se-tips/java.lang/finding-greatest-common-divisor-recursively.html)
int gcd(int a, int b) {
if (b==0)
return a;
else
return gcd(b, a % b);
}
但我不认为这更有效(但我可能是错的)。
有人有想法吗?欢迎所有建议!
编辑:我稍后会进行一些分析...感谢您的所有建议!
I have an array a
of 10 booleans (or equivalently the binary representation of a number < 1024). I want to compare this array to a large set of arrays b[i]
of booleans of the same size in the following way:
The function compare(a,b[i])
should return true
if the elements of the array a
are never true
when the element of at the same position in b[i]
is false
.
As an exemple in java
boolean compare(boolean a1, boolean a2){
for (int j = 0; j<10; j++)
if (a1[j] && !a2[j])
return false;
return true;
}
Is there a better implementation of this function? If one consider the corresponding binary number to be the coefficients of the prime decomposition of a integer A1 (and A2), an equivalent function would be
boolean compare (int A1, int A2){
if (gcd(A1,A2)==A1)
return true;
else
return false;
}
with for example, (http://www.java-tips.org/java-se-tips/java.lang/finding-greatest-common-divisor-recursively.html)
int gcd(int a, int b) {
if (b==0)
return a;
else
return gcd(b, a % b);
}
but I don't think that this is more efficient (but I may be wrong).
Does anyone has an idea ? All suggestions are welcome!
EDIT: I will go back with some profiling later... Thanks for all your propositions!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不确定
BitSet
更高效,但它应该出现在要分析的简短实现列表中。I'm not sure
BitSet
is more efficient, but it should be on the short list of implementations to profile.如果您可以使用整数而不是数组,为什么不直接:
If you can use integers instead of arrays, why not just:
如果您可以将这些布尔数组作为整数,则可以使用按位运算:
我认为这应该可行......
If you could have those boolean arrays as integers instead, you could use bitwise operations:
I think that should work...
如果您有数据的 int 表示,则可以使用按位运算符:
如果发生 Øb[i] ^ a[i] ,则 c 将不为零。
If you have int representation of the data, you may use bitwise operators:
If any ocurrence of ¬b[i] ^ a[i] happens, c will not be zero.
我可能听起来有点离题。然而,似乎有一种java内置的方法可以做到这一点。
参考: http://www.java-examples.com/compare -two-java-boolean-arrays-example
它对我有用。
I might sound kinda off point. However, there seem to be a java inbuilt way of doing this.
Reference: http://www.java-examples.com/compare-two-java-boolean-arrays-example
It works for me.