[Buffalo-pm] Bit Counting

Quantum Mechanic quantum_mechanic_1964 at yahoo.com
Wed Oct 1 10:13:59 CDT 2003


I'm looking for an elegant way to generate a list of
numbers whose binary representation has a given number
of 1's. I also want to generate this list in numerical
order.

For example, with 4 bits on, less than 50:

15 1111
23 10111
27 11011
29 11101
30 11110
39 100111
43 101011
45 101101
46 101110

Now it's easy enough to check every number up to the
limit, but it seems there should be a more efficient
method. On the other hand, the overhead involved in
"skipping" some numbers may be more expensive than the
straightforward approach. 

Anyone have any insights into this?


Just for reference, here's some code to check every
number, and print out the decimal and binary:

#!/your/perl/here

$bit_count = shift;
$last_number = (shift or -1);

$x = 1;

while ( ( $last_number < 0 ) or ( $x <= $last_number )
)
{
  my $y = $x;  # copy $x into $y, and chew up $y as we
go
  
  my $bits;
  
  while ( $y )
  {
    $bits .= $y % 2;
    $y = $y >> 1;
  }
	
  if ( $bit_count == ( $bits =~ tr/1// ) )
  {
    # add underline for readability if needed
#   1 while ( $bits =~ s/([01]{4})([01])/$1_$2/ );
    $bits = reverse $bits;
    print "$x $bits\n";
  }
	
  $x++;
}
__END__

=====
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Quantum Mechanics: The dreams stuff is made of

__________________________________
Do you Yahoo!?
The New Yahoo! Shopping - with improved product search
http://shopping.yahoo.com



More information about the Buffalo-pm mailing list