Population count: Difference between revisions

m
→‎{{header|Perl}}: rearrange and de-clutter
(Add CLU)
m (→‎{{header|Perl}}: rearrange and de-clutter)
Line 2,980:
<lang perl>use strict;
use warnings;
use feature 'say';
 
sub population_count {
my $n = shift;
die "argument can't be negative" if $n < 0;
my $c;
for ($c = 0; $n; $n >>= 1) {
$c += $n & 1;
}
$c;
}
 
print join ' ', map { population_count(3**$_) } 0 .. 30 - 1;
print "\n";
sub evil {
my $i = 0;
sub { $i++ while population_count($i) % 2; $i++ }
}
 
sub odious {
my $i = 0;
Line 3,002 ⟶ 2,992:
}
 
sub population_count {
my ($evil, $odious) = (evil, odious);
my (@evil,$n = @odious)shift;
my $n = shiftc;
for (1 .. 30) {
for ($c = 0; $n; $n >>= 1) { $c += $n & 1 }
push @evil, $evil->();
my $c;
push @odious, $odious->();
}
 
printsay join ' ', map { population_count( 3**$_) } 0 .. 30 - 1;
printf "Evil : %s\n", join ' ', @evil;
 
printf "Odious: %s\n", join ' ', @odious;</lang>
my (@evil, @odious);
my ($evil, $odious) = (evil, odious);
push( @evil, $evil->() ), push @odious, $odious->() for 1 .. 30;
 
say "Evil @evil";
printfsay "Odious: %s\n", join ' ', @odious";</lang>
{{out}}
<pre>1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25
Evil : 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58
Odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59</pre>
 
 
A faster population count can be done with pack/unpack:
2,392

edits