The weekly challenge 284 - Task 1: Lucky Integer

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-284/#TASK1
 3 #
 4 # Task 1: Lucky Integer
 5 # =====================
 6 #
 7 # You are given an array of integers, @ints.
 8 #
 9 # Write a script to find the lucky integer if found otherwise return -1. If
10 # there are more than one then return the largest.
11 #
12 ### A lucky integer is an integer that has a frequency in the array equal to
13 ### its value.
14 #
15 ## Example 1
16 ##
17 ## Input: @ints = (2, 2, 3, 4)
18 ## Output: 2
19 #
20 ## Example 2
21 ##
22 ## Input: @ints = (1, 2, 2, 3, 3, 3)
23 ## Output: 3
24 #
25 ## Example 3
26 ##
27 ## Input: @ints = (1, 1, 1, 3)
28 ## Output: -1
29 #
30 ############################################################
31 ##
32 ## discussion
33 ##
34 ############################################################
35 #
36 # Count the frequencies for all elements in the array. Then
37 # check the frequencies versus the value sorted in descending
38 # order and stop once we find a match. If there was no match,
39 # return -1.
40 
41 use strict;
42 use warnings;
43 
44 lucky_integer(2, 2, 3, 4);
45 lucky_integer(1, 2, 2, 3, 3, 3);
46 lucky_integer(1, 1, 1, 3);
47 
48 sub lucky_integer {
49    my @ints = @_;
50    print "Input: (" . join(", ", @ints) . ")\n";
51    my $frequencies = {};
52    foreach my $i (@ints) {
53       $frequencies->{$i}++;
54    }
55    foreach my $f (sort {$b<=>$a} keys %{$frequencies}) {
56       return print "Output: $f\n" if $frequencies->{$f} == $f;
57    }
58    print "Output: -1\n";
59 }