From 1608da594dbaaa0999a4d7ddf0ee52c2c62c3622 Mon Sep 17 00:00:00 2001 From: Kjetil Skotheim Date: Sun, 5 Mar 2023 03:02:28 +0100 Subject: https://theweeklychallenge.org/blog/perl-weekly-challenge-206/ --- challenge-206/kjetillll/perl/ch-1.pl | 20 +++++++++++++++++++ challenge-206/kjetillll/perl/ch-2.pl | 37 ++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 challenge-206/kjetillll/perl/ch-1.pl create mode 100644 challenge-206/kjetillll/perl/ch-2.pl diff --git a/challenge-206/kjetillll/perl/ch-1.pl b/challenge-206/kjetillll/perl/ch-1.pl new file mode 100644 index 0000000000..90c9e4e757 --- /dev/null +++ b/challenge-206/kjetillll/perl/ch-1.pl @@ -0,0 +1,20 @@ +#!/usr/bin/perl +use warnings; use strict; use List::Util 'reduce'; + +my @time = @ARGV; #input from command line args +@time = ("10:10", "09:30", "09:00", "09:55") if not @time; #...or use test case + +print "Input: @time\n"; +print "Interval in minutes: ", shortest_time(@time), "\n"; + +sub shortest_time { + ( + reduce { + my($last,$min) = ref$a ? @$a : ($a,undef); + my $diff = $b - $last; + [$b, !defined$min || $diff < $min ? $diff : $min] + } + map{ my($hh,$mm) = split/:/; $hh*60 + $mm } + sort @_ + )[0][1] +} diff --git a/challenge-206/kjetillll/perl/ch-2.pl b/challenge-206/kjetillll/perl/ch-2.pl new file mode 100644 index 0000000000..0ec1e5e59e --- /dev/null +++ b/challenge-206/kjetillll/perl/ch-2.pl @@ -0,0 +1,37 @@ +#!/usr/bin/perl +use warnings; use strict; +#use Acme::Tools; + +my @array = @ARGV; #input from command line args +@array = (1,2,3,4) if not @array; #...or use test case +#@array = (0,2,1,3) if not @array; #...or use test case + +print "Input: @array\n"; +print "Max sum: ", maxsum(@array), "\n"; + + +sub maxsum { + my $max; + for my $perm_array ( perm(@_) ){ + my $sum; + while(@$perm_array){ #loop the pairs ($a,$b) of current permutation + my($a,$b) = splice@$perm_array,0,2; + $sum += $a<$b ? $a : $b; + } + $max = $sum if !defined$max or $sum>$max; + } + $max +} + +sub perm { + my(@i,@r) = 0..$#_; + @_ || return; + while ( push @r, [@_[@i]] ) { + my $p = $#i || last; + --$p || last while $i[$p-1] > $i[$p]; + push @i, reverse splice @i, my$q=$p; + ++$q while $i[$p-1] > $i[$q]; + @i[$p-1,$q] = @i[$q,$p-1]; + } + @r +} -- cgit