From 42cd185a7c28ef3ed8071e1c9a8fcc03b14f51ea Mon Sep 17 00:00:00 2001 From: drbaggy Date: Tue, 16 Feb 2021 12:45:26 +0000 Subject: one-liner down to 112 characters! 104 bytes of usefulness! by not checking bits we assume to be correct in regexp --- challenge-100/james-smith/perl/ch-1.pl | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/challenge-100/james-smith/perl/ch-1.pl b/challenge-100/james-smith/perl/ch-1.pl index 4d83710a33..b682620f73 100644 --- a/challenge-100/james-smith/perl/ch-1.pl +++ b/challenge-100/james-smith/perl/ch-1.pl @@ -33,12 +33,15 @@ is( fun_time( '12:00 pm' ), '12:00' ); done_testing(); ## 72 chars ############################################################ -#00000000111111111122222222223333333333444444444455555555556 -#23456789012345678901234567890123456789012345678901234567890 ## Just split so slightly more readable and fits on 60 char lines ## Not nasty hack - we pop rather than shift as it saves 2 bytes! -sub ft{pop=~s{(\d+):(\d+)\s*(\wm|)}{sprintf'%02d:%02d%s', +## We assume that the minute portion will be two digits after the +## ":" then we don't need to check it.... + +## 112 bytes total - 104 inside the curly braces.. + +sub ft{pop=~s{(\d+)(:..)\s*(.m|)}{sprintf'%02d%s%s', ($1%12||(12*!$3))+12*('pm'eq$3),$2,$3?'':$1<12?'am':'pm'}re} ## This is more readable version with notes... @@ -48,18 +51,21 @@ sub fun_time { ## in our golfdom.... s{ ## Split into 3 parts, $1 - hours, $2 - minutes & $3 - am/pm - (\d+) : (\d+) \s* ( \wm | ) + (\d+) (:..) \s* ( .m | ) ## We assume all strings are valid - so we don't have to anchor ## at both ends or worry what the 12hr clock sufficies are - ## am/pm & \wm is shorter than [ap]m + ## am/pm and .m is shorter than [ap]m + ## + ## We assume that the time will always have a : followed + ## 2 digits... ## - ## Note if we right (\wm)? the 3rd capture variable $3 is - ## sometimes undefined - better is to use ([ap]m|) which + ## Note if we right (.m)? the 3rd capture variable $3 is + ## sometimes undefined - better is to use (.m|) which ## matches the same way but $3 is now an empty string not ## undefined when we have a 24 hour clock time } { - sprintf '%02d:%02d%s', + sprintf '%02d%s%s', ( $1 % 12 || ( 12 * ! $3 ) ) + 12 * ( 'pm' eq $3 ), ## Get hour modulo 12.. ## From 24hr to 12hr clock we need to convert 00:?? to 12:?? -- cgit