aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorStephen Lynn <bizlsg@localhost.localdomain>2023-12-27 07:06:24 +0800
committerStephen Lynn <bizlsg@localhost.localdomain>2023-12-27 07:06:24 +0800
commit09ffbd5e40441c537d3550f0040558e5756f9d79 (patch)
tree51d4aa68943ff870933044d68070fa207421c170
parent746cf884930fc15574fa75bd5377cb95ed85fc17 (diff)
downloadperlweeklychallenge-club-09ffbd5e40441c537d3550f0040558e5756f9d79.tar.gz
perlweeklychallenge-club-09ffbd5e40441c537d3550f0040558e5756f9d79.tar.bz2
perlweeklychallenge-club-09ffbd5e40441c537d3550f0040558e5756f9d79.zip
ch-2 improved
-rwxr-xr-xchallenge-249/steve-g-lynn/perl/ch-2.pl15
1 files changed, 8 insertions, 7 deletions
diff --git a/challenge-249/steve-g-lynn/perl/ch-2.pl b/challenge-249/steve-g-lynn/perl/ch-2.pl
index 5f64069776..37d26f55fd 100755
--- a/challenge-249/steve-g-lynn/perl/ch-2.pl
+++ b/challenge-249/steve-g-lynn/perl/ch-2.pl
@@ -6,20 +6,21 @@ local *DI_string_match = sub {
#-- return 0 (error) if input is not D or I only
($str =~ /^[DI]+$/) || (return 0);
- #-- create sorted array of indices from which to generate output
- my @tmp=(0 .. length($str));
+ #-- create mutable temp vars containing highest and lowest indices
+ my ($lowest,$highest)=(0, length($str));
#-- loop through $str indices,
- # if a position i is 'D' pop @tmp (highest item) and assign to retval[i]
- # if a position i is 'I' shift @tmp (lowest item) and assign to retval[i]
+ # if str[i] is 'D', assign highest in output[i] and decrement it
+ # if a position i is 'I', assign lowest in output[i] and increment it
my @retval = (); #-- return value
map {
- (substr($str,$_,1) eq 'D') && ($retval[$_] = pop @tmp);
- (substr($str,$_,1) eq 'I') && ($retval[$_] = shift @tmp);
+ (substr($str,$_,1) eq 'D') && ($retval[$_] = $highest--);
+ (substr($str,$_,1) eq 'I') && ($retval[$_] = $lowest++);
}
0 .. length($str)-1;
- $retval[length($str)] = shift @tmp; #-- last item left
+ ($lowest==$highest) || die "Something wrong ...$!";
+ $retval[length($str)] = $highest; #-- last item left
@retval;
};