Task1
We repeat each given character n times according to the given rules:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;
sub decode_string{
my (@s1,@s2);
my $num = 0;
my $res = '';
foreach my $c(split '',$_[0]){
if($c =~ /\d/) {
$num = $num * 10 + $c - '0'
} elsif($c eq '[') {
push @s1,$num;
push @s2,$res;
$num = 0;
$res = ''
} elsif($c eq ']') {
my $t = '';
for(my ($i,$n) = (0,pop @s1); $i < $n; ++$i) {
$t .= $res
}
$res = (pop @s2) . $t
} else {
$res .= $c
}
}
$res
}
is decode_string('2[3[a]]'),'aaaaaa','Example 1';
is decode_string('10[a]'),'aaaaaaaaaa','Example 2';
is decode_string('a2[b]c3[d]e'),'abbcddde','Example 3';
is decode_string('2[a2[b]c]'),'abbcabbc','Example 4';
is decode_string('1[a]2[b3[c]]'),'abcccbccc','Example 5';
done_testing();
Task2
We reorder characters until we find the smallest string:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 7;
sub order_characters{
my ($s,$k) = @_;
if ($k == 1) {
my $n = length($s);
my $doubled = $s . $s;
my $best = substr($doubled,0,$n);
foreach my $i(1..$n-1) {
my $candidate = substr($doubled,$i,$n);
$best = $candidate if $candidate lt $best
}
return $best
} else {
return join('',sort split '',$s)
}
}
is order_characters('dbca',1),'adbc','Example 1';
is order_characters('geeks',2),'eegks','Example 2';
is order_characters('cbaed',3),'abcde','Example 3';
is order_characters('fedcba',4),'abcdef','Example 4';
is order_characters('perl',1),'erlp','Example 5';
is order_characters('oloolooo',1),'looloooo','Example 6';
is order_characters('oloooolo',1),'looloooo','Example 7';
done_testing();
No comments:
Post a Comment