The weekly challenge 276 - Task 2: Maximum Frequency

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-276/#TASK2
 3 #
 4 # Task 2: Maximum Frequency
 5 # =========================
 6 #
 7 # You are given an array of positive integers, @ints.
 8 #
 9 # Write a script to return the total number of elements in the given array
10 # which have the highest frequency.
11 #
12 ## Example 1
13 ##
14 ## Input: @ints = (1, 2, 2, 4, 1, 5)
15 ## Ouput: 4
16 ##
17 ## The maximum frequency is 2.
18 ## The elements 1 and 2 has the maximum frequency.
19 #
20 ## Example 2
21 ##
22 ## Input: @ints = (1, 2, 3, 4, 5)
23 ## Ouput: 5
24 ##
25 ## The maximum frequency is 1.
26 ## The elements 1, 2, 3, 4 and 5 has the maximum frequency.
27 #
28 ############################################################
29 ##
30 ## discsussion
31 ##
32 ############################################################
33 #
34 # First, we calculate the frequencies for all numbers in the array.
35 # Then we sort that list by frequency and count all that share the
36 # maximum value.
37 
38 use strict;
39 use warnings;
40 
41 maximum_frequency(1, 2, 2, 4, 1, 5);
42 maximum_frequency(1, 2, 3, 4, 5);
43 
44 sub maximum_frequency {
45    my @ints = @_;
46    my $freq = {};
47    print "Input: (", join(", ", @ints), ")\n";
48    foreach my $i (@ints) {
49       $freq->{$i}++;
50    }
51    my $max = 0;
52    my $output = 0;
53    foreach my $i (sort { $freq->{$b} <=> $freq->{$a}} keys %$freq) {
54       if($max < $freq->{$i}) {
55          $max = $freq->{$i};
56       }
57       if($freq->{$i} == $max) {
58          $output+=$max;
59       }
60    }
61    print "Output: $output\n";
62 }