oldtechaa

Posted on

# Perl Weekly Challenge #208

I've been doing the Perl Weekly Challenge, so here are my solutions to the PWC #208. All solutions are about to be posted, but this could be a spoiler if you're trying to solve it too. I was very pleased this week that I got it down to about 15-25 minutes for each task, so I'm definitely getting more comfortable in Perl again.

``````use strict;
use v5.10;

my @list1 = ("Perl", "Raku", "Love");
my @list2 = ("Raku", "Perl", "Hate");

# my @list1 = ("A", "B", "C");
# my @list2 = ("D", "E", "F");

# my @list1 = ("A", "B", "C");
# my @list2 = ("C", "A", "B");

my \$minindex;
my @results;
for (my \$index1 = 0; \$index1 < scalar @list1; \$index1++) {
for (my \$index2 = 0; \$index2 < scalar @list2; \$index2++) {
if (\$list1[\$index1] eq \$list2[\$index2] && defined(\$minindex)) {
if (\$index1 + \$index2 < \$minindex) {
@results = (\$list1[\$index1]);
\$minindex = \$index1 + \$index2;
} elsif (\$index1 + \$index2 == \$minindex) {
push (@results, \$list1[\$index1]);
}
} elsif (\$list1[\$index1] eq \$list2[\$index2] && !defined(\$minindex)) {
@results = (\$list1[\$index1]);
\$minindex = \$index1 + \$index2;
}
}
}
if (scalar @results == 0) {exit}
foreach (@results) {
say \$_;
}
``````

Pretty simple. For every item in list 1, I iterate through list 2 and look for a match with a lower sum than the previous lowest sum. If I find one it replaces the previous results, if it's equal I add it to the results. Then I say the results.

``````use strict;
use v5.10;

my \$index;
my (\$duplicate, \$missing);
foreach (@ARGV) {
if (!defined(\$index)) {\$index = 1 and next}
if (\$_ == \$ARGV[\$index - 1]) {\$duplicate = \$_}
if (\$_ != \$ARGV[\$index - 1] + 1) {\$missing = \$ARGV[\$index - 1] + 1}
\$index++;
}
defined(\$duplicate) && defined(\$missing) ? say ("Duplicate is \$duplicate", "\n", "Missing is \$missing") : say -1;
``````

For this one, I iterate through them and if it's the same thing as the previous one it's my duplicate and if it's not the previous item plus 1 then it's your missing number.

Anyways, hope you liked them this week. I always look at the other solutions blogged about and get ideas for use in my code. If you have any better ideas comment below.