views:

54

answers:

3

How to write a function to determine the population count of a 16-bit integer using php or javascript. Population count is defined as the number of bits that are "turned on," or in others, it is the number of 1s in a binary representation of a number. For example, the binary number 0b0000 has a population count of 0 because there aren't any 1 bits. 0b0101 has a population count of 2, because 2 bits turned on; 0b1110 has a population count of 3. 0b1111111111111111 has a population count if 16 because there are sixteen 1 bits. Your function should accept an INTEGER argument and return an INTEGER containing its population count. Example:

f(0) = 0

f(1) = 1

f(2) = 1

f(3) = 2

f(4) = 1

f(5) = 2

+4  A: 

Using bitwise and and right shift

function count(n){
  c =0;
  while(n){
    c += n&1;
    n = n>>1;
  }
  return c;
}
stackunderflow
+1 for bitwise operators. They are underused.
Jason McCreary
Assuming this is JavaScript, I'd actually vote the other way. Bitwise operators can actually be *slower* in JavaScript because numbers are (IIRC) natively 64-bit floating-point; performing bitwise operations requires a conversion to 32-bit integer and then back. Moreover, this function is leaking the c variable to the global scope without the `var` keyword.
Ken
+3  A: 

The badass way?

    var x=0xfffe;
    x -= ((x >> 1) & 0x55555555);
    x = (((x >> 2) & 0x33333333) + (x & 0x33333333));
    x = (((x >> 4) + x) & 0x0f0f0f0f);
    x += (x >> 8);
    x += (x >> 16);
    alert(x & 0x0000003f); //15
spender
+1 This made me think... badass! LOL.
Jason McCreary
This is described in the book "Hacker's delight". Available together with other algorithms here: http://www.hackersdelight.org/HDcode/newCode/pop_arrayHS.c.txt
Emil H
Wow. I was thoroughly impressed.
steven_desu
I lifted it from here: http://aggregate.org/MAGIC/ my bible for this kind of stuff.
spender
+1  A: 

Not necessarily badass, but it works...

<?php
$number = 3;

echo "Number: " . $number . "\n";

$bin_number = decbin($number);
$population_count = 0;

echo "Binary String Conversion: " . $bin_number . "\n";

for ($i = strlen($bin_number) - 1; $i >= 0; --$i) {
  $population_count += $bin_number[$i];
}

echo "Population Count: " . $population_count . "\n";
?>
Jason McCreary
+1 for the worst possible solution. Don't try this at home, kids. :)
Emil H
@Emil, is that because it's PHP or uses strings? I'll give you the latter.
Jason McCreary
For using strings to do math. I still use PHP everyonce in a while myself, even though I've been trying harder and harder not to...
Emil H
@Emil, fair. I actually tried the bitwise operators, but **stackunderflow** beat me to it. So I provided something else. Thanks for calling me out ;)
Jason McCreary