Task1
We take the absolute value of the first elements of arrays after sorting them:
#!/usr/bin/env perl
use strict;
use warnings;
sub magic_number{
my @x = sort{$a <=> $b} @{$_[0]};
my @y = sort{$a <=> $b} @{$_[1]};
abs($x[0] - $y[0])
}
printf "%d\n",magic_number([3,7,5],[9,5,7]);
printf "%d\n",magic_number([1,2,1],[5,4,4]);
printf "%d\n",magic_number([2],[5]);
Task2
After sorting the array, we keep removing pairs of elements and push its reverse to the array that we want to return:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;
sub number_game{
my @arr = sort{$a <=> $b} @{$_[0]};
my @ret;
push @ret,reverse splice @arr,0,2 while(@arr);
@ret
}
print show number_game([2,5,3,4]);
print show number_game([9,4,1,3,6,4,6,1]);
print show number_game([1,2,2,3]);
No comments:
Post a Comment