aboutsummaryrefslogtreecommitdiff
path: root/challenge-206
diff options
context:
space:
mode:
authorKjetil Skotheim <kjetil.skotheim@sikt.no>2023-03-05 13:14:49 +0100
committerKjetil Skotheim <kjetil.skotheim@sikt.no>2023-03-05 13:14:49 +0100
commitc6990b03994f8ca73bd047c2e1962bd3f595e330 (patch)
treeaaeedbaf35cf3d87db9e727d2be5ea679fc4601b /challenge-206
parent1608da594dbaaa0999a4d7ddf0ee52c2c62c3622 (diff)
downloadperlweeklychallenge-club-c6990b03994f8ca73bd047c2e1962bd3f595e330.tar.gz
perlweeklychallenge-club-c6990b03994f8ca73bd047c2e1962bd3f595e330.tar.bz2
perlweeklychallenge-club-c6990b03994f8ca73bd047c2e1962bd3f595e330.zip
Turns out, hints from others, we don't need to loop through every possible pairings permutation. Just need to sort the input numbers and sum up every evenly indexed (0-indexed array) number.
Diffstat (limited to 'challenge-206')
-rw-r--r--challenge-206/kjetillll/perl/ch-2.pl36
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] ) }