The weekly challenge 351 - Task 1: Special Average
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-351/#TASK1 3 # 4 # Task 1: Special Average 5 # ======================= 6 # 7 # You are given an array of integers. 8 # 9 # Write a script to return the average excluding the minimum and maximum of the 10 # given array. 11 # 12 ## Example 1 13 ## 14 ## Input: @ints = (8000, 5000, 6000, 2000, 3000, 7000) 15 ## Output: 5250 16 ## 17 ## Min: 2000 18 ## Max: 8000 19 ## Avg: (3000+5000+6000+7000)/4 = 21000/4 = 5250 20 # 21 # 22 ## Example 2 23 ## 24 ## Input: @ints = (100_000, 80_000, 110_000, 90_000) 25 ## Output: 95_000 26 ## 27 ## Min: 80_000 28 ## Max: 110_000 29 ## Avg: (100_000 + 90_000)/2 = 190_000/2 = 95_000 30 # 31 # 32 ## Example 3 33 ## 34 ## Input: @ints = (2500, 2500, 2500, 2500) 35 ## Output: 0 36 ## 37 ## Min: 2500 38 ## Max: 2500 39 ## Avg: 0 40 # 41 # 42 ## Example 4 43 ## 44 ## Input: @ints = (2000) 45 ## Output: 0 46 ## 47 ## Min: 2000 48 ## Max: 2000 49 ## Avg: 0 50 # 51 # 52 ## Example 5 53 ## 54 ## Input: @ints = (1000, 2000, 3000, 4000, 5000, 6000) 55 ## Output: 3500 56 ## 57 ## Min: 1000 58 ## Max: 6000 59 ## Avg: (2000 + 3000 + 4000 + 5000)/4 = 14000/4 = 3500 60 # 61 ############################################################ 62 ## 63 ## discussion 64 ## 65 ############################################################ 66 # 67 # We find both the minimum and the maximum. Then we skip those 68 # while calculating the average (sum up all remaining parts and 69 # divide by their number). 70 71 use v5.36; 72 73 special_average(8000, 5000, 6000, 2000, 3000, 7000); 74 special_average(100_000, 80_000, 110_000, 90_000); 75 special_average(2500, 2500, 2500, 2500); 76 special_average(2000); 77 special_average(1000, 2000, 3000, 4000, 5000, 6000); 78 79 sub special_average(@ints) { 80 say "Input: (" . join(",", @ints) . ")"; 81 my $min = $ints[0]; 82 my $max = $ints[0]; 83 foreach my $elem (@ints) { 84 if($elem > $max) { 85 $max = $elem; 86 } 87 if($elem < $min) { 88 $min = $elem; 89 } 90 } 91 my $c = 0; 92 my $sum = 0; 93 foreach my $elem (@ints) { 94 next if $elem == $min; 95 next if $elem == $max; 96 $c++; 97 $sum += $elem; 98 } 99 if($c) { 100 say "Output: " . $sum / $c; 101 } else { 102 say "Output: 0"; 103 } 104 } 105