1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-205/#TASK1
 3 #
 4 # Third Highest
 5 # =============
 6 #
 7 # You are given an array of integers.
 8 #
 9 # Write a script to find out the Third Highest if found otherwise return the maximum.
10 #
11 ## Example 1
12 ##
13 ## Input: @array = (5,3,4)
14 ## Output: 3
15 ##
16 ## First highest is 5. Second highest is 4. Third highest is 3.
17 #
18 ## Example 2
19 ##
20 ## Input: @array = (5,6)
21 ## Output: 6
22 ##
23 ## First highest is 6. Second highest is 5. Third highest is missing, so maximum is returned.
24 #
25 ## Example 2
26 ##
27 ## Input: @array = (5,4,4,3)
28 ## Output: 3
29 ##
30 ## First highest is 5. Second highest is 4. Third highest is 3.
31 #
32 ############################################################
33 ##
34 ## discussion
35 ##
36 ############################################################
37 #
38 # Basically we need to sort the elements of the array, eliminating
39 # duplicates. If the remaining list contains at least 3 elements,
40 # output the third highest, otherwise the highest.
41 
42 use strict;
43 use warnings;
44 
45 third_highest();
46 third_highest(5,3,4);
47 third_highest(5,6);
48 third_highest(5,4,4,3);
49 third_highest(1,2,3,4,4,7,8,9,9,8,7,6);
50 
51 sub third_highest {
52    my @array = @_;
53    # error handling: empty arrays don't even have a maximum
54    unless(@array) {
55       print "Input empty array, no output!\n";
56       return;
57    }
58    print "Input: (" . join(", ", @array) . ")\n";
59    my $uniq;
60    # put the elements of the array as keys into a hash table
61    # this eliminates duplicates
62    map { $uniq->{$_} = 1 } @array;
63    # sort those keys in descending order
64    my @sorted = sort {$b <=> $a} keys %$uniq;
65    if( @sorted >= 3) {
66       print "Output: $sorted[2]\n";
67    } else {
68       print "Output: $sorted[0]\n";
69    }
70 }