Missing and mad
Weekly challenge 327 — 23 June 2025
Week 327: 23 Jun 2025
You are given an array of n integers. Write a script to find all the missing integers in the range 1..n in the given array.
Example 1 Input: @ints = (1, 2, 1, 3, 2, 5) Output: (4, 6) The given array has 6 elements. So we are looking for integers in the range 1..6 in the given array. The missing integers: (4, 6) Example 2 Input: @ints = (1, 1, 1) Output: (2, 3) Example 3 Input: @ints = (2, 2, 1) Output: (3)
This can be done in two steps:
@present
such that $present[$j]
is defined
if $j
is present in the input array.
@present
onto the output array.Could this be done in a single line of Perl? Very likely, but I think that would be even harder to decipher so I'm sticking with my 2-line solution.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2025-06-23 use utf8; # Week 327 - task 1 - Missing integers use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; missing_integers(1, 2, 1, 3, 2, 5); missing_integers(1, 1, 1); missing_integers(2, 2, 1); missing_integers(7, 8, 9); missing_integers(5, 5, 5, 5, 5); missing_integers(5, 4, 3, 2, 1); sub missing_integers { my (@ints, @present, @absent); # initialise @ints = @_; # set $present[$j] to 1 if $j is present in @ints $present[$ints[$_]] = defined $ints[$_] ? 1 : 0 for 0 .. $#ints; # push $j onto @absent if $present[$j] is not defined push @absent, grep {not defined $present[$_]} 1 .. scalar @ints; # report results say qq[\nInput: (] . join(', ', @ints) . q[)]; say qq[Output: (] . join(', ', @absent) . q[)]; }
Input: (1, 2, 1, 3, 2, 5) Output: (4, 6) Input: (1, 1, 1) Output: (2, 3) Input: (2, 2, 1) Output: (3) Input: (7, 8, 9) Output: (1, 2, 3) Input: (5, 5, 5, 5, 5) Output: (1, 2, 3, 4) Input: (5, 4, 3, 2, 1) Output: ()
Any content of this website which has been created by Peter Campbell Smith is in the public domain