From 87fc99e47cc0c15093aaf397f59cc66ca6013f4d Mon Sep 17 00:00:00 2001 From: "E. Choroba" Date: Tue, 14 Mar 2023 11:48:16 +0100 Subject: Solve 208: Minimum Index Sum & Duplicate and Missing by E. Choroba --- challenge-208/e-choroba/perl/ch-1.pl | 33 +++++++++++++++++++++++++++++++ challenge-208/e-choroba/perl/ch-2.pl | 38 ++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100755 challenge-208/e-choroba/perl/ch-1.pl create mode 100755 challenge-208/e-choroba/perl/ch-2.pl diff --git a/challenge-208/e-choroba/perl/ch-1.pl b/challenge-208/e-choroba/perl/ch-1.pl new file mode 100755 index 0000000000..411d501fc2 --- /dev/null +++ b/challenge-208/e-choroba/perl/ch-1.pl @@ -0,0 +1,33 @@ +#! /usr/bin/perl +use warnings; +use strict; +use experimental qw( signatures ); + +sub minimum_index_sum($list1, $list2) { + my %index; + $index{ $list2->[$_] } //= $_ for 0 .. $#$list2; + + my $minimum = ($#$list2 + $#$list1 + 1); + my @indices; + for my $i (0 .. $#$list1) { + if (exists $index{ $list1->[$i] }) { + my $sum = $index{ $list1->[$i] } + $i; + if ($sum <= $minimum) { + @indices = () if $sum < $minimum; + $minimum = $sum; + push @indices, $i; + } + } + } + return [@$list1[@indices]] +} + +use Test2::V0; +plan 3; + +is minimum_index_sum([qw[ Perl Raku Love]], [qw[ Raku Perl Hate ]]), + [qw[ Perl Raku ]], 'Example 1'; + +is minimum_index_sum([qw[ A B C ]], [qw[ D E F ]]), [], 'Example 2'; + +is minimum_index_sum([qw[ A B C ]], [qw[ C A B ]]), ['A'], 'Example 3'; diff --git a/challenge-208/e-choroba/perl/ch-2.pl b/challenge-208/e-choroba/perl/ch-2.pl new file mode 100755 index 0000000000..fb60b95c76 --- /dev/null +++ b/challenge-208/e-choroba/perl/ch-2.pl @@ -0,0 +1,38 @@ +#! /usr/bin/perl +use warnings; +use strict; +use experimental qw( signatures ); + +sub duplicate_and_missing(@nums) { + my %seen; + my $duplicate; + my $missing; + for my $n (@nums) { + if (exists $seen{$n}) { + return [-1] if 1 < $seen{$n}; # Triplicate. + + $duplicate = $n; + } + ++$seen{$n}; + } + return [-1] unless defined $duplicate; + + return [-1] + if $seen{ + $missing = $duplicate + (exists $seen{ $duplicate + 1 } ? -1 : 1) + }; + + return [$duplicate, $missing] +} + +use Test2::V0; +plan 3 + 4; + +is duplicate_and_missing(1, 2, 2, 4), [2, 3], 'Example 1'; +is duplicate_and_missing(1, 2, 3, 4), [-1], 'Example 2'; +is duplicate_and_missing(1, 2, 3, 3), [3, 4], 'Example 3'; + +is duplicate_and_missing(1, 2, 2, 3), [-1], 'Duplicate but not missing'; +is duplicate_and_missing(1, 2, 4, 5), [-1], 'Missing but not duplicate'; +is duplicate_and_missing(2, 2, 3, 4), [2, 1], 'Missing at the beginning'; +is duplicate_and_missing(2, 3, 3, 3), [-1], 'Triplicate'; -- cgit