diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2023-03-06 01:43:46 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-03-06 01:43:46 +0000 |
| commit | e1fe819596030db724255aab25759c4d767d8b5f (patch) | |
| tree | a6715d3330f994fe8b429203a29e7cb72591c5cc | |
| parent | b8a8e4a6f319b191d5d38786fd7c55eda14a6575 (diff) | |
| parent | c6990b03994f8ca73bd047c2e1962bd3f595e330 (diff) | |
| download | perlweeklychallenge-club-e1fe819596030db724255aab25759c4d767d8b5f.tar.gz perlweeklychallenge-club-e1fe819596030db724255aab25759c4d767d8b5f.tar.bz2 perlweeklychallenge-club-e1fe819596030db724255aab25759c4d767d8b5f.zip | |
Merge pull request #7663 from kjetillll/challenge-206-kjetillll
Turns out, with hints from others, we don't need to brute force here
| -rw-r--r-- | challenge-206/kjetillll/perl/ch-2.pl | 36 |
1 files changed, 5 insertions, 31 deletions
diff --git a/challenge-206/kjetillll/perl/ch-2.pl b/challenge-206/kjetillll/perl/ch-2.pl index 0ec1e5e59e..96afc91618 100644 --- a/challenge-206/kjetillll/perl/ch-2.pl +++ b/challenge-206/kjetillll/perl/ch-2.pl @@ -1,37 +1,11 @@ #!/usr/bin/perl -use warnings; use strict; -#use Acme::Tools; +use warnings; use strict; use List::Util 'sum'; -my @array = @ARGV; #input from command line args -@array = (1,2,3,4) if not @array; #...or use test case +my @array = @ARGV; #use 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"; +print "Max sum: ", maxminsum(@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 -} +sub maxminsum { sum( (sort{$a<=>$b}@_)[map 2*$_,0..$#_/2] ) } |
