Task1
We count the values in a hash, if there are any odd number counts, we return an empty array, else we pair up the elements:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw(all);
use Data::Show;
sub equal_pairs{
my %h;
$h{$_}++ foreach @{$_[0]};
(all{$_%2} values %h) ? () : map{my $k=$_;map{[$k,$k]}1..$h{$k}/2}keys %h;
}
print show equal_pairs([3,2,3,2,2,2]);
print show equal_pairs([1,2,3,4]);
Task2
We initialize two variables $i and $j to 0 and length of the string respectively, if the character in the string is equal to 'I' then we increment $i else we decrement $j, and lastly append the $i to the end of the result:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Show;
sub di_string_match{
my ($i,$j) = (0,length $_[0]);
(map{$_ eq 'I' ? $i++ : $j--}split '',$_[0]),$i;
}
print show di_string_match('IDID');
print show di_string_match('III');
print show di_string_match('DDI');
No comments:
Post a Comment