perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 327 - Task 1: Missing Integers

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-327/#TASK1
 3 #
 4 # Task 1: Missing Integers
 5 # ========================
 6 #
 7 # You are given an array of n integers.
 8 #
 9 # Write a script to find all the missing integers in the range 1..n in the
10 # given array.
11 #
12 ## Example 1
13 ##
14 ## Input: @ints = (1, 2, 1, 3, 2, 5)
15 ## Output: (4, 6)
16 ##
17 ## The given array has 6 elements.
18 ## So we are looking for integers in the range 1..6 in the given array.
19 ## The missing integers: (4, 6)
20 #
21 #
22 ## Example 2
23 ##
24 ## Input: @ints = (1, 1, 1)
25 ## Output: (2, 3)
26 #
27 #
28 ## Example 3
29 ##
30 ## Input: @ints = (2, 2, 1)
31 ## Output: (3)
32 #
33 ############################################################
34 ##
35 ## discussion
36 ##
37 ############################################################
38 #
39 # We turn each element in the input into a key of a hash. Then
40 # we walk from 1 to n, and if that number is not in the hash,
41 # we simply add it to the output list.
42 
43 use v5.36;
44 
45 missing_integers(1, 2, 1, 3, 2, 5);
46 missing_integers(1, 1, 1);
47 missing_integers(2, 2, 1);
48 
49 sub missing_integers (@ints) {
50     say "Input: (" . join(", ", @ints) . ")";
51     my @output = ();
52     my %map = map { $_ => 1 } @ints;
53     foreach my $i (1..$#ints+1) {
54         push @output, $i unless $map{$i};
55     }
56     say "Output: (" . join(", ", @output) . ")";
57 }