The weekly challenge 231 - Task 1: Min Max
1 #!/usr/bin/perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-231/#TASK1 3 # 4 # Task 1: Min Max 5 # =============== 6 # 7 # You are given an array of distinct integers. 8 # 9 # Write a script to find all elements that is neither minimum nor maximum. 10 # Return -1 if you can’t. 11 # 12 ## Example 1 13 ## 14 ## Input: @ints = (3, 2, 1, 4) 15 ## Output: (3, 2) 16 ## 17 ## The minimum is 1 and maximum is 4 in the given array. So (3, 2) is neither 18 ## min nor max. 19 # 20 ## Example 2 21 ## 22 ## Input: @ints = (3, 1) 23 ## Output: -1 24 # 25 ## Example 3 26 ## 27 ## Input: @ints = (2, 1, 3) 28 ## Output: (2) 29 ## 30 ## The minimum is 1 and maximum is 3 in the given array. So 2 is neither min 31 ## nor max. 32 # 33 ############################################################ 34 ## 35 ## discussion 36 ## 37 ############################################################ 38 # 39 # first, calculate the minimum and maximum of the elements 40 # in the array - we can do that in one pass. Then we collect 41 # all elements that are neither the minimum nor the maximum 42 43 use strict; 44 use warnings; 45 46 min_max(3, 2, 1, 4); 47 min_max(3, 1); 48 min_max(2, 1, 3); 49 50 sub min_max { 51 my @ints = @_; 52 print "Input: (" . join(", ", @ints) . ")\n"; 53 if(@ints <= 2) { 54 print "Output: -1\n"; 55 return; 56 } 57 my ($min, $max) = min_and_max(@ints); 58 my @result = (); 59 foreach my $elem (@ints) { 60 next if $elem == $min; 61 next if $elem == $max; 62 push @result, $elem; 63 } 64 if(@result) { 65 print "Output: (" . join(", ", @result) . ")\n"; 66 return; 67 } 68 print "Output: -1\n"; 69 } 70 71 sub min_and_max { 72 my @ints = @_; 73 my $min = $ints[0]; 74 my $max = $ints[0]; 75 foreach my $elem (@ints) { 76 $min = $elem if $elem < $min; 77 $max = $elem if $elem > $max; 78 } 79 return ($min,$max); 80 }