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 pr开发者_Go百科ofiling later... Thanks for all your propositions!
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:
return ((a1 & ~a2) == 0)
If you could have those boolean arrays as integers instead, you could use bitwise operations:
boolean compare(int a1, int a2) {
return (a1 | a2) == a2;
}
I think that should work...
If you have int representation of the data, you may use bitwise operators:
boolean compare(int a, int b) {
int c = ~b ^ a;
return c == 0;
}
If any ocurrence of ¬b[i] ^ a[i] happens, c will not be zero.
I might sound kinda off point. However, there seem to be a java inbuilt way of doing this.
java.util.Arrays.equals(blnArray1,blnArray2)
Reference: http://www.java-examples.com/compare-two-java-boolean-arrays-example
It works for me.
精彩评论