aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorE. Choroba <choroba@matfyz.cz>2022-11-06 22:27:22 +0100
committerE. Choroba <choroba@matfyz.cz>2022-11-06 22:27:58 +0100
commit30291752320457e13fb1c747320be385c6521dab (patch)
treea2e737df709ff6ff3aee223e13d5d122ca14f151
parentcb621c6e9edd46c33940a8b02bd8577c4a8883d1 (diff)
downloadperlweeklychallenge-club-30291752320457e13fb1c747320be385c6521dab.tar.gz
perlweeklychallenge-club-30291752320457e13fb1c747320be385c6521dab.tar.bz2
perlweeklychallenge-club-30291752320457e13fb1c747320be385c6521dab.zip
Optimize 189/2 by E. Choroba, add a blog post link
-rw-r--r--challenge-189/e-choroba/blog.txt1
-rwxr-xr-xchallenge-189/e-choroba/perl/ch-2.pl13
2 files changed, 7 insertions, 7 deletions
diff --git a/challenge-189/e-choroba/blog.txt b/challenge-189/e-choroba/blog.txt
new file mode 100644
index 0000000000..83bf6f46ae
--- /dev/null
+++ b/challenge-189/e-choroba/blog.txt
@@ -0,0 +1 @@
+http://blogs.perl.org/users/e_choroba/2022/11/array-degree.html
diff --git a/challenge-189/e-choroba/perl/ch-2.pl b/challenge-189/e-choroba/perl/ch-2.pl
index 7108ed75cc..55e63a6e0b 100755
--- a/challenge-189/e-choroba/perl/ch-2.pl
+++ b/challenge-189/e-choroba/perl/ch-2.pl
@@ -11,24 +11,23 @@ sub array_degree (@array) {
my %freq;
my %from_to;
- my @max = ([0, 0]);
+ my @max = (undef, 0);
for my $pos (0 .. $#array) {
my $e = $array[$pos];
++$freq{$e};
if (exists $from_to{$e}) {
$from_to{$e}[1] = $pos;
} else {
- $from_to{$e} = [$pos];
+ $from_to{$e} = [$pos, $pos];
}
- if ($freq{$e} >= $max[0][0]) {
- @max = () if $freq{$e} > $max[0][0];
- unshift @max, [$freq{$e}, $e];
+ if ($freq{$e} >= $max[-1]) {
+ @max = ($freq{$e}) if $freq{$e} > $max[-1];
+ unshift @max, $e;
}
}
- return [$array[0]] if $max[0][0] == 1;
my %by_length = map +($_->[1] - $_->[0] => $_),
- @from_to{ map $_->[1], @max };
+ @from_to{@max[ 0 .. $#max - 1 ]};
my $shortest = $by_length{ min(keys %by_length) };
return [@array[ $shortest->[0] .. $shortest->[1] ]]
}