1 #!/usr/bin/perl 2 # 3 # https://theweeklychallenge.org/blog/perl-weekly-challenge-201/#TASK1 4 # 5 # You are given an array of unique numbers. 6 # 7 # Write a script to find out all missing numbers in the range 0..$n where $n is the array size. 8 # 9 ## Example 1 10 ## 11 ## Input: @array = (0,1,3) 12 ## Output: 2 13 ## 14 ## The array size i.e. total element count is 3, so the range is 0..3. 15 ## The missing number is 2 in the given array. 16 # 17 ## Example 2 18 ## 19 ## Input: @array = (0,1) 20 ## Output: 2 21 ## 22 ## The array size is 2, therefore the range is 0..2. 23 ## The missing number is 2. 24 # 25 ##################################################################### 26 ## 27 ## discussion 28 ## 29 ##################################################################### 30 # 31 # this is basically a loop from 0..$n and printing all the numbers that 32 # are not in the array. 33 # Note that the task doesn't state that all numbers in the array have to 34 # be in the range 0..$n, just the missing numbers are. So we could also 35 # have an array like (0,2,4,8) where $n = 4, but 8 is clearly not in the 36 # range 0..4, so we would get 1 and 3 as output 37 38 use strict; 39 use warnings; 40 41 my @examples = ( 42 [0, 1, 3], 43 [0, 1], 44 [0, 2, 4, 8], 45 [0, 2, 4, 6, 8, 10] 46 ); 47 48 foreach my $array (@examples) { 49 # let's print the input array 50 print "(" . join(", ", @$array) . "):\n"; 51 # for each element in the array create a corresponding 52 # entry in the %seen hash 53 my %seen = map { $_ => 1, } @$array; 54 my @result; 55 foreach my $i (0..scalar(@$array)) { 56 # the missing elements are the ones not in %seen, 57 # so add them to the result 58 push @result, $i unless $seen{$i}; 59 } 60 # print the result 61 print "Output: " . join(", ", @result) . "\n"; 62 } 63 64