The weekly challenge 321 - Task 1: Distinct Average
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-321/#TASK1 3 # 4 # Task 1: Distinct Average 5 # ======================== 6 # 7 # You are given an array of numbers with even length. 8 # 9 # Write a script to return the count of distinct average. The average is 10 # calculate by removing the minimum and the maximum, then average of the two. 11 # 12 ## Example 1 13 ## 14 ## Input: @nums = (1, 2, 4, 3, 5, 6) 15 ## Output: 1 16 ## 17 ## Step 1: Min = 1, Max = 6, Avg = 3.5 18 ## Step 2: Min = 2, Max = 5, Avg = 3.5 19 ## Step 3: Min = 3, Max = 4, Avg = 3.5 20 ## 21 ## The count of distinct average is 1. 22 # 23 # 24 ## Example 2 25 ## 26 ## Input: @nums = (0, 2, 4, 8, 3, 5) 27 ## Output: 2 28 ## 29 ## Step 1: Min = 0, Max = 8, Avg = 4 30 ## Step 2: Min = 2, Max = 5, Avg = 3.5 31 ## Step 3: Min = 3, Max = 4, Avg = 3.5 32 ## 33 ## The count of distinct average is 2. 34 # 35 # 36 ## Example 3 37 ## 38 ## Input: @nums = (7, 3, 1, 0, 5, 9) 39 ## Output: 2 40 ## 41 ## Step 1: Min = 0, Max = 9, Avg = 4.5 42 ## Step 2: Min = 1, Max = 7, Avg = 4 43 ## Step 3: Min = 3, Max = 5, Avg = 4 44 ## 45 ## The count of distinct average is 2. 46 # 47 ############################################################ 48 ## 49 ## discussion 50 ## 51 ############################################################ 52 # 53 # At first, we sort the array. Then we can always remove the last 54 # and first element via pop() and shift() until there are no more 55 # elements in the array. Of course we calculate the medium value at 56 # each step and take note of it so in the end we can have the number 57 # of distinct averages. 58 59 use v5.36; 60 use List::Util qw(sum); 61 62 distinct_average(1, 2, 4, 3, 5, 6); 63 distinct_average(0, 2, 4, 8, 3, 5); 64 distinct_average(7, 3, 1, 0, 5, 9); 65 66 sub distinct_average(@nums) { 67 say "Input: (" . join(", ", @nums) . ")"; 68 my @sorted = sort { $a <=> $b } @nums; 69 my $avg = {}; 70 while(scalar(@sorted)) { 71 my $s = sum(@sorted); 72 my $average = $s / scalar(@sorted); 73 $avg->{$average} = 1; 74 pop @sorted; 75 shift @sorted; 76 } 77 my $count = scalar(keys(%$avg)); 78 say "Output: $count"; 79 }