I have an array of integers, where each integer value is a 'group membership' bitmask. For example, array(1, 4, 5) is interpreted as:
- The first element (1) is a member of Group 0 (i.e. 2**0)
- The second element (4) is a member of Group 2 (i.e. 2**2)
- The third element (5) is a member of Groups 0 and 2 (i.e. 2**0 + 2**2)
So, my question is, how can I efficiently count the number of members in each of the groups?
My starting point would be to do something like this:
$count = array();
for ($i=0; $i<64; $i++) {
$count[$i] = 0;
$comparator = 2**$i;
foreach ($array as $value) {
if ($comparator & $value) $count[$i]++;
}
}
That seems like a long winded way to go about things. If I have 1,000 elements in the array, I am doing 64 X 1000 iterations.
Is there an easier way to go about this? Using an advanced array technique, for example, or a php extension for bitwise operations?