From 59bd648d130df8195f50377de49d6a676ed0ede7 Mon Sep 17 00:00:00 2001 From: "E. Choroba" Date: Mon, 27 May 2024 15:55:52 +0200 Subject: Optimise 270/2 --- challenge-270/e-choroba/perl/ch-2.pl | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/challenge-270/e-choroba/perl/ch-2.pl b/challenge-270/e-choroba/perl/ch-2.pl index 958d0938fa..0632f5713e 100755 --- a/challenge-270/e-choroba/perl/ch-2.pl +++ b/challenge-270/e-choroba/perl/ch-2.pl @@ -19,19 +19,17 @@ sub distribute_elements($x, $y, $ints) { || $seen{"@e"} > $price + $x; if (@$elements > 2 && 2 * $x > $y) { - for my $i (0 .. $#$elements - 1) { - for my $j ($i + 1 .. $#$elements) { - my @e = sort { $a <=> $b } $elements->[$i] + 1, - $elements->[$j] + 1, - @$elements[grep $_ != $i - && $_ != $j, - 0 .. $#$elements]; + for my $i (1, $#$elements) { + my @e = sort { $a <=> $b } $elements->[0] + 1, + $elements->[$i] + 1, + @$elements[grep $_ != 0 + && $_ != $i, + 0 .. $#$elements]; - $seen{"@e"} = $price + $y, - push @agenda, [$price + $y, \@e] - if ! exists $seen{"@e"} - || $seen{"@e"} > $price + $y; - } + $seen{"@e"} = $price + $y, + push @agenda, [$price + $y, \@e] + if ! exists $seen{"@e"} + || $seen{"@e"} > $price + $y; } } @@ -39,7 +37,7 @@ sub distribute_elements($x, $y, $ints) { } } -use Test::More tests => 2 + 14; +use Test::More tests => 2 + 17; is distribute_elements(3, 2, [4, 1]), 9, 'Example 1'; is distribute_elements(2, 1, [2, 3, 3, 3, 5]), 6, 'Example 2'; @@ -54,6 +52,9 @@ is distribute_elements(2, 3, [1, 1, 5]), 12, '2 3 [1 1 5]'; is distribute_elements(17, 1, [1, 9, 9]), 16, '17 1 [1 9 9]'; is distribute_elements(8, 9, [6, 6, 4, 2]), 34, '8 9 [6 6 4 2]'; is distribute_elements(6, 1, [2, 5, 5, 6]), 5, '6 1 [2 5 5 6]'; +is distribute_elements(9, 1, [1, 2, 3, 3, 7]), 12, '9 1 [1 2 3 3 7]'; +is distribute_elements(7, 3, [1, 4, 7, 7, 7]), 21, '7 3 [1 4 7 7 7]'; +is distribute_elements(9, 1, [7, 1, 1, 4, 8]), 12, '9 1 [7 1 1 4 8]'; is distribute_elements(1, 1, [1, 4, 3, 4, 5, 4, 2, 3, 7]), 15, '1 1 [1 4 3 4 5 4 2 3 7]'; is distribute_elements(4, 1, [1, 4, 1, 2, 5, 7, 1, 5]), 15, -- cgit