aboutsummaryrefslogtreecommitdiff
path: root/challenge-208/dave-jacoby/perl/ch-2.pl
blob: ec9bfd29a0eb5643a82001f9f73f28afc8ddf86a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/env perl

use strict;
use warnings;
use experimental qw{ say postderef signatures state };

use List::Util qw{ min max };

my @examples = (

    [ 1, 2, 2, 4 ],
    [ 1, 2, 3, 4 ],
    [ 1, 2, 3, 3 ],
);

for my $e (@examples) {
    my $o     = duplicate_and_missing( $e->@* );
    my $array = join ', ', $e->@*;
    say <<"END";
    Input:  \@array = $array
    Output: $o
END
}

sub duplicate_and_missing (@array) {
    my $min = min @array;
    my $max = max @array;

    my $duplicate;
    my $missing;
    for my $i ( $min .. $max ) {
        my $c = () = grep { $_ == $i } @array;
        $duplicate = $i if $c > 1;
        $missing   = $i if $c < 1;
    }
    return -1 if !defined $duplicate && !defined $missing;
    $missing //= $max + 1;
    return join ',', $duplicate, $missing;
}