The weekly challenge 398 - Task 1: Divisible Average
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-398/#TASK1 3 # 4 # Task 1: Divisible Average 5 # ========================= 6 # 7 # You are given an array of positive integers. 8 # 9 # Write a script to return the closest integer to the mean value of all even 10 # integers that are divisible by 3. If none is divisible, return 0. 11 # 12 ## Example 1 13 ## 14 ## Input: @arr = (18, 5, 7, 11) 15 ## Output: 18 16 ## 17 ## 18 is the only even number and divisible by 3. 18 ## Average: 18 / 1 = 18. 19 # 20 ## Example 2 21 ## 22 ## Input: @arr = (6, 12, 18, 24, 30, 40) 23 ## Output: 18 24 ## 25 ## The qualifying numbers are 6, 12, 18, 24, and 30. 26 ## Average: (6 + 12 + 18 + 24 + 30) / 5 = 90 / 5 = 18 27 # 28 ## Example 3 29 ## 30 ## Input: @arr = (3, 9, 15, 21, 27) 31 ## Output: 0 32 ## 33 ## None of the elements are even. 34 ## Since no elements qualify, return 0. 35 # 36 ## Example 4 37 ## 38 ## Input: @arr = (6, 12, 14, 20) 39 ## Output: 9 40 ## 41 ## The qualifying numbers are 6 and 12. 42 ## Average: (6 + 12) / 2 = 9. 43 # 44 ## Example 5 45 ## 46 ## Input: @arr = (6, 6, 6, 12, 12) 47 ## Output: 8 48 ## 49 ## All five numbers are even and divisible by 3. 50 ## Average: (6 + 6 + 6 + 12 + 12) / 5 = 8.4 => 8 51 # 52 ############################################################ 53 ## 54 ## discussion 55 ## 56 ############################################################ 57 # 58 # First, we collect all even numbers that are divisible by 3, 59 # which are exactly all numbers divisible by 6. Then we calculate 60 # their average, add 0.5 and take the integer value of that. 61 # 62 use v5.36; 63 use List::Util qw(sum); 64 65 sub divisible_average(@arr) { 66 say "Input: (" . join(", ", @arr) . ")"; 67 my @divisible = grep { $_ % 6 == 0 } @arr; 68 return say "Output: 0" unless @divisible; 69 my $count = scalar(@divisible); 70 my $avg = int( sum(@divisible) / $count + 0.5); 71 say "Output: $avg"; 72 } 73 74 75 divisible_average(18, 5, 7, 11); 76 divisible_average(6, 12, 18, 24, 30, 40); 77 divisible_average(3, 9, 15, 21, 27); 78 divisible_average(6, 12, 14, 20); 79 divisible_average(6, 6, 6, 12, 12);