Monday, May 27, 2024


Challenge Link


We return the index of the array with the largest sum:

#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(sum0);

sub maximum_ones{
  my $max = 0;
  map{my $c = sum0 @{$_[0]->[$_]}; $max = $_+1 if $c > $max} 0..$#{$_[0]};

printf "%d\n",maximum_ones([[0,1],[1,0]]);
printf "%d\n",maximum_ones([[0,0,0],[1,0,1]]);
printf "%d\n",maximum_ones([[0,0],[1,1],[0,0]]);


We first sort by the pop count of the items then if they were equal, by the elements themselves:

#!/usr/bin/env perl
use strict;
use warnings;
use ntheory qw(hammingweight);
use Data::Show;

sub sort_by_one_bits{
  sort{hammingweight($a) <=> hammingweight($b) || $a <=> $b} @{$_[0]}

print show sort_by_one_bits([0,1,2,3,4,5,6,7,8]);
print show sort_by_one_bits([1024,512,256,128,64]);

No comments:

Post a Comment