Task1
we split the number into its digits and check if it is even:
#!/usr/bin/env perl
use strict;
use warnings;
sub count_even_digits_number{
scalar grep{(split'',$_)%2==0}@{$_[0]}
}
printf "%d\n",count_even_digits_number([10,1,111,24,1000]);
printf "%d\n",count_even_digits_number([111,1,11111]);
printf "%d\n",count_even_digits_number([2,8,1024,256]);
Task2
We get the popcount of each index and if it is equal to $k, we include the number at that index in the resultant array, else we skip it:
#!/usr/bin/env perl
use strict;
use warnings;
use ntheory qw(hammingweight);
use List::Util qw(sum0);
sub sum_of_values{
sum0 map{hammingweight$_==$_[1]?$_[0]->[$_]:()}0..$#{$_[0]}
}
printf "%d\n",sum_of_values([2,5,9,11,3],1);
printf "%d\n",sum_of_values([2,5,9,11,3],2);
printf "%d\n",sum_of_values([2,5,9,11,3],0);
No comments:
Post a Comment