Well you are using Java, and you say that this is a set-intersection problem. So let's model the problem in a nice OO way.
public final class HexDigit
{
public static HexDigit[] parseDigits(int v)
{
HexDigit[] rval = new HexDigit[8];
int mask = 15;
for(int i = 0; i < 16; i++)
{
rval[i] = new HexDigit((byte) v&mask);
v = v >> 4;
}
return rval;
}
final static char[] hDigits =
{
'0' ,'1','2' ,'3','4' ,'5' ,
'6','7','8','9','a','b',
'c','d','e','f','g','h',
'i','j','k','l','m','n',
'o','p','q','r','s','t' ,
'u','v','w','x','y','z'
};
public HexDigit(byte v)
{
assert(v >=0 && v < 16, "values is outside of the appropriate range for an Hexadecimal Digit");
digit = v;
}
private byte digit;
public String toString()
{
return hDigits[digit];
}
public byte getValue()
{
return digit;
}
public int hashCode()
{
return digit;
}
public bool equals(Object o)
{
return (o instanceof HexDigit && ((HexDigit)o).digit == this.digit);
}
}
Now that we have a nice way to model our digits (and more imporantly it will play nice with a hashset
) let's solve our problem:
int a[] = your input array;
Set<HexDigit> intersection =null;
for(int i = 0; i < a.length; i++)
{
HexDigits[] digits = HexDigit.parseDigits(a[i]);
Set<HexDigit> digits = new HashSet<HexDigit>(digits);
if(intersection == null)//we are the first one
{
intersection = digits;
}
else
{
intersection.retainAll(digits);
}
}
//done!
At the end intersection
will contain only those digits that were in each word.