The weekly challenge 255 - Task 2: Most Frequent Word
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-255/#TASK2 3 # 4 # Task 2: Most Frequent Word 5 # ========================== 6 # 7 # You are given a paragraph $p and a banned word $w. 8 # 9 # Write a script to return the most frequent word that is not banned. 10 # 11 ## Example 1 12 ## 13 ## Input: $p = "Joe hit a ball, the hit ball flew far after it was hit." 14 ## $w = "hit" 15 ## Output: "ball" 16 ## 17 ## The banned word "hit" occurs 3 times. 18 ## The other word "ball" occurs 2 times. 19 # 20 ## Example 2 21 ## 22 ## Input: $p = "Perl and Raku belong to the same family. Perl is the most 23 ## popular language in the weekly challenge." 24 ## $w = "the" 25 ## Output: "Perl" 26 ## 27 ## The banned word "the" occurs 3 times. 28 ## The other word "Perl" occurs 2 times. 29 # 30 ############################################################ 31 ## 32 ## discussion 33 ## 34 ############################################################ 35 # 36 # Split the sentence into its words, then count all the words != $w 37 38 use strict; 39 use warnings; 40 41 most_frequent_word("Joe hit a ball, the hit ball flew far after it was hit.", "hit"); 42 most_frequent_word("Perl and Raku belong to the same family. Perl is the most" . 43 " popular language in the weekly challenge.", "the"); 44 45 sub most_frequent_word { 46 my ($p, $w) = @_; 47 print "Input: '$p', '$w'\n"; 48 my $found = {}; 49 foreach my $word (split/[^\w]/, $p) { 50 next if $word eq $w; 51 $found->{$word}++; 52 } 53 my @most = sort { $found->{$b} <=> $found->{$a} } keys %$found; 54 print "Found the most frequent word to be '$most[0]'\n"; 55 } 56