From 9bd20673e749979a0705c25e5a67c4f804bbdd4e Mon Sep 17 00:00:00 2001 From: Dave Jacoby Date: Thu, 16 Mar 2023 15:42:05 -0400 Subject: #208 DAJ --- challenge-208/dave-jacoby/perl/ch-1.pl | 40 ++++++++++++++++++++++++++++++++++ challenge-208/dave-jacoby/perl/ch-2.pl | 39 +++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 challenge-208/dave-jacoby/perl/ch-1.pl create mode 100644 challenge-208/dave-jacoby/perl/ch-2.pl diff --git a/challenge-208/dave-jacoby/perl/ch-1.pl b/challenge-208/dave-jacoby/perl/ch-1.pl new file mode 100644 index 0000000000..d977f9ccf6 --- /dev/null +++ b/challenge-208/dave-jacoby/perl/ch-1.pl @@ -0,0 +1,40 @@ +#!/usr/bin/env perl + +use strict; +use warnings; +use experimental qw{ say postderef signatures state }; + +use List::Util qw{ min }; + +my @examples = ( + + [ [qw{ Perl Raku Love}], [qw{Raku Perl Hate}], ], + [ [qw{A B C}], [qw{D E F}], ], + [ [qw{A B C}], [qw{C A B}], ], +); + +for my $e (@examples) { + my @o = min_index_sum( $e->@* ); + my $o = join ',',map { qq{"$_"} } @o; + my $list1 = join ',',map { qq{"$_"} } $e->[0]->@*; + my $list2 = join ',',map { qq{"$_"} } $e->[1]->@*; + say <<"END"; + Input: \@list1 = $list1 + \@list2 = $list2 + Output: ($o) +END +} + +sub min_index_sum ( $list1, $list2 ) { + my %output; + for my $i ( 0 .. -1 + scalar $list1->@* ) { + for my $j ( 0 .. -1 + scalar $list2->@* ) { + next unless $list1->[$i] eq $list2->[$j]; + my $k = $i + $j; + push $output{$k}->@*, $list1->[$i]; + } + } + my $min = min keys %output; + return $output{$min}->@* if $min; + return (); +} diff --git a/challenge-208/dave-jacoby/perl/ch-2.pl b/challenge-208/dave-jacoby/perl/ch-2.pl new file mode 100644 index 0000000000..ec9bfd29a0 --- /dev/null +++ b/challenge-208/dave-jacoby/perl/ch-2.pl @@ -0,0 +1,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; +} -- cgit