The weekly challenge 381 - Task 2: Smaller Greater Element
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-381/#TASK2 3 # 4 # Task 2: Smaller Greater Element 5 # =============================== 6 # 7 # You are given an array of integers. 8 # 9 # Write a script to find the number of elements that have both a strictly 10 # smaller and greater element in the given array. 11 # 12 ## Example 1 13 ## 14 ## Input: @int = (2,4) 15 ## Output: 0 16 ## 17 ## Not enough elements in the array. 18 # 19 ## Example 2 20 ## 21 ## Input: @int = (1, 1, 1, 1) 22 ## Output: 0 23 # 24 ## Example 3 25 ## 26 ## Input: @int = (1, 1, 4, 8, 12, 12) 27 ## Output: 2 28 ## 29 ## The elements are 4 and 8. 30 # 31 ## Example 4 32 ## 33 ## Input: @int = (3, 6, 6, 9) 34 ## Output: 2 35 ## 36 ## Both instances of 6. 37 # 38 ## Example 5 39 ## 40 ## Input: @int = (0, -5, 10, -2, 4) 41 ## Output: 3 42 ## 43 ## The elements are 0, -2, and 4. 44 # 45 ############################################################ 46 ## 47 ## discussion 48 ## 49 ############################################################ 50 # 51 # We just find the min and max values in the array, then we count 52 # all elements that are bigger than the min and smaller than the max. 53 54 use v5.36; 55 use List::Util qw(min max); 56 57 smaller_greater_element(2,4); 58 smaller_greater_element(1, 1, 1, 1); 59 smaller_greater_element(1, 1, 4, 8, 12, 12); 60 smaller_greater_element(3, 6, 6, 9); 61 smaller_greater_element(0, -5, 10, -2, 4); 62 63 sub smaller_greater_element(@int) { 64 say "Input: (" . join(", ", @int) . ")"; 65 my $count = 0; 66 my $min = min(@int); 67 my $max = max(@int); 68 foreach my $elem (@int) { 69 if($elem > $min && $elem < $max) { 70 $count++; 71 } 72 } 73 say "Output: $count"; 74 }