The weekly challenge 247 - Task 2: Most Frequent Letter Pair
1 #!/usr/bin/perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-247/#TASK2 3 # 4 # Task 2: Most Frequent Letter Pair 5 # ================================= 6 # 7 # You are given a string S of lower case letters 'a'..'z'. 8 # 9 # Write a script that finds the pair of consecutive letters in S that appears 10 # most frequently. If there is more than one such pair, chose the one that is 11 # the lexicographically first. 12 # 13 ## Example 1 14 ## 15 ## Input: $s = 'abcdbca' 16 ## Output: 'bc' 17 ## 18 ## 'bc' appears twice in `$s` 19 # 20 ## Example 2 21 ## 22 ## Input: $s = 'cdeabeabfcdfabgcd' 23 ## Output: 'ab' 24 ## 25 ## 'ab' and 'cd' both appear three times in $s and 'ab' is lexicographically 26 ## smaller than 'cd'. 27 # 28 ############################################################ 29 ## 30 ## discussion 31 ## 32 ############################################################ 33 # 34 # Create a map with all substrings as keys and their frequency as value, 35 # then sort by frequency descending and then by key ascending and return 36 # the first element of the sorted list 37 38 use strict; 39 use warnings; 40 41 most_frequent_letter_pair('abcdbca'); 42 most_frequent_letter_pair('cdeabeabfcdfabgcd'); 43 44 sub most_frequent_letter_pair { 45 my $s = shift; 46 print "Input: $s\n"; 47 my @letters = split //, $s; 48 my $map = {}; 49 foreach my $i (0..$#letters-1) { 50 my $new = $letters[$i] . $letters[$i+1]; 51 $map->{$new}++; 52 } 53 my @sorted = sort { $map->{$b} <=> $map->{$a} || $a cmp $b } keys %$map; 54 print "Output: $sorted[0]\n"; 55 }