Task1
We take $c columns from the array each $r time through the map:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;
sub twod_array{
my ($arr,$r,$c) = @_;
map{[splice @$arr,0,$c]} 1..$r
}
print show twod_array([1,2,3,4],2,2);
print show twod_array([1,2,3],1,3);
print show twod_array([1,2,3,4],4,1);
Task2
We find the sum of xoring each subset of the array:
#!/usr/bin/env perl
use strict;
use warnings;
use Algorithm::Combinatorics qw(subsets);
use List::Util qw(reduce);
sub total_xor{
my $it = subsets($_[0]);
my $sum = 0;
while(my $s = $it->next){
$sum += reduce {$a ^ $b} 0, @$s
}
$sum
}
printf "%d\n",total_xor([1,3]);
printf "%d\n",total_xor([5,1,6]);
printf "%d\n",total_xor([3,4,5,6,7,8]);
Data::Show is nice, but show is itself outputing to stderr; the prints aren't needed
ReplyDelete