The weekly challenge 319 - Task 2: Minimum Common
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-319/#TASK2 3 # 4 # Task 2: Minimum Common 5 # ====================== 6 # 7 # You are given two arrays of integers. 8 # 9 # Write a script to return the minimum integer common to both arrays. If none 10 # found return -1. 11 # 12 ## Example 1 13 ## 14 ## Input: @array_1 = (1, 2, 3, 4) 15 ## @array_2 = (3, 4, 5, 6) 16 ## Output: 3 17 ## 18 ## The common integer in both arrays: 3, 4 19 ## The minimum is 3. 20 # 21 # 22 ## Example 2 23 ## 24 ## Input: @array_1 = (1, 2, 3) 25 ## @array_2 = (2, 4) 26 ## Output: 2 27 # 28 # 29 ## Example 3 30 ## 31 ## Input: @array_1 = (1, 2, 3, 4) 32 ## @array_2 = (5, 6, 7, 8) 33 ## Output: -1 34 # 35 ############################################################ 36 ## 37 ## discussion 38 ## 39 ############################################################ 40 # 41 # We turn the elements from the first array into the keys of a hash. 42 # Then we walk the sorted second list. As soon as an element can be 43 # found in the hash, it is the searched minimum. If we didn't find 44 # any element, we just return the default for our result, -1. 45 46 use v5.36; 47 48 minimum_common( [1, 2, 3, 4], [3, 4, 5, 6] ); 49 minimum_common( [1, 2, 3], [2, 4] ); 50 minimum_common( [1, 2, 3, 4],[5, 6, 7, 8] ); 51 52 sub minimum_common( $array_1, $array_2 ) { 53 say "Input: (" . join(", ", @$array_1) . "),"; 54 say " (" . join(", ", @$array_2) . ")"; 55 my $tmp; 56 my $result = -1; 57 foreach my $elem (@$array_1) { 58 $tmp->{$elem} = 1; 59 } 60 foreach my $elem (sort {$a <=> $b} @$array_2) { 61 if($tmp->{$elem}) { 62 $result = $elem; 63 last; 64 } 65 } 66 say "Output: $result"; 67 }