/
ch-2.pl
50 lines (42 loc) · 1.14 KB
/
ch-2.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/env perl
use strict;
use warnings;
use experimental qw{ say postderef signatures state };
use List::Util qw{ max };
my @examples = (
{
paragraph =>
"Joe hit a ball, the hit ball flew far after it was hit.",
word => "hit",
},
{
paragraph =>
"Perl and Raku belong to the same family. Perl is the most popular language in the weekly challenge.",
word => "the",
}
);
for my $example (@examples) {
my $output = most_frequent_word($example);
my $p = $example->{paragraph};
my $w = $example->{word};
say <<~"END";
Input: \$p = "$p"
\$w = "$w"
Output: "$output"
END
}
sub most_frequent_word ($obj) {
my $paragraph = $obj->{paragraph};
my $banned_word = $obj->{word};
my %hash;
# some people REALLY hate map being used in this way, believing
# that it should end in (start with) @array = , but clearly,
# I disagree
map { $hash{$_}++ }
grep { $_ ne $banned_word }
split /\W+/, $paragraph;
my $max = max values %hash;
my @output =
grep { $hash{$_} == $max } keys %hash;
return shift @output;
}