Convert seconds to compound duration: Difference between revisions
Content deleted Content added
SqrtNegInf (talk | contribs) →{{header|Perl}}: added alternate method |
|||
Line 2,303: | Line 2,303: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
===Direct calculation=== |
|||
⚫ | |||
<lang perl>use strict; |
|||
use warnings; |
|||
⚫ | |||
my $sec = shift; |
my $sec = shift; |
||
no warnings 'numeric'; |
no warnings 'numeric'; |
||
Line 2,313: | Line 2,317: | ||
int($sec/60) % 60 . " min", |
int($sec/60) % 60 . " min", |
||
int($sec) % 60 . " sec"; |
int($sec) % 60 . " sec"; |
||
} |
|||
⚫ | |||
⚫ | |||
Demonstration: |
|||
⚫ | |||
printf "%7d sec = %s\n", $_, compound_duration($_) |
printf "%7d sec = %s\n", $_, compound_duration($_) |
||
}</lang> |
}</lang> |
||
{{out}} |
|||
⚫ | |||
86400 sec = 1 d |
|||
6000000 sec = 9 wk, 6 d, 10 hr, 40 min</pre> |
|||
===Using polymod=== |
|||
More general approach for mixed-radix conversions. |
|||
<lang perl>use strict; |
|||
use warnings; |
|||
use Math::AnyNum 'polymod'; |
|||
sub compound_duration { |
|||
my $seconds = shift; |
|||
my @terms; |
|||
my @durations = reverse polymod($seconds, 60, 60, 24, 7); |
|||
my @timespans = <wk d hr min sec>; |
|||
while (my $d = shift @durations, my $t = shift @timespans) { |
|||
push @terms, "$d $t" if $d |
|||
} |
|||
join ', ', @terms |
|||
} |
|||
for (<7259 86400 6000000 3380521>) { |
|||
printf "%7d sec = %s\n", $_, compound_duration($_) |
|||
⚫ | |||
{{out}} |
{{out}} |
||
<pre> 7259 sec = 2 hr, 59 sec |
|||
<pre> |
|||
⚫ | |||
86400 sec = 1 d |
86400 sec = 1 d |
||
6000000 sec = 9 wk, 6 d, 10 hr, 40 min |
6000000 sec = 9 wk, 6 d, 10 hr, 40 min |
||
3380521 sec = 5 wk, 4 d, 3 hr, 2 min, 1 sec</pre> |
|||
</pre> |
|||
=={{header|Perl 6}}== |
=={{header|Perl 6}}== |