diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2022-11-06 21:29:20 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-11-06 21:29:20 +0000 |
| commit | 0ad9fb359687f28f0ce11fb841c8983f8ced8fa0 (patch) | |
| tree | a2e737df709ff6ff3aee223e13d5d122ca14f151 | |
| parent | cb621c6e9edd46c33940a8b02bd8577c4a8883d1 (diff) | |
| parent | 30291752320457e13fb1c747320be385c6521dab (diff) | |
| download | perlweeklychallenge-club-0ad9fb359687f28f0ce11fb841c8983f8ced8fa0.tar.gz perlweeklychallenge-club-0ad9fb359687f28f0ce11fb841c8983f8ced8fa0.tar.bz2 perlweeklychallenge-club-0ad9fb359687f28f0ce11fb841c8983f8ced8fa0.zip | |
Merge pull request #7041 from choroba/ech189b
Optimize 189/2 by E. Choroba, add a blog post link
| -rw-r--r-- | challenge-189/e-choroba/blog.txt | 1 | ||||
| -rwxr-xr-x | challenge-189/e-choroba/perl/ch-2.pl | 13 |
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] ]] } |
