aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDave Cross <dave@dave.org.uk>2021-05-31 10:45:54 +0100
committerDave Cross <dave@dave.org.uk>2021-05-31 10:47:51 +0100
commit2f03f9ada6efe1f731d076e70fd80988148b2d1f (patch)
treec7b73bb2c5b9be4619bc077473cadb49c4bb0994
parent7933720b0269e9c4d5a684b1f665c8b05eb1ec33 (diff)
downloadperlweeklychallenge-club-2f03f9ada6efe1f731d076e70fd80988148b2d1f.tar.gz
perlweeklychallenge-club-2f03f9ada6efe1f731d076e70fd80988148b2d1f.tar.bz2
perlweeklychallenge-club-2f03f9ada6efe1f731d076e70fd80988148b2d1f.zip
Challenge #115
-rw-r--r--challenge-115/dave-cross/perl/ch-1.pl31
-rw-r--r--challenge-115/dave-cross/perl/ch-2.pl43
2 files changed, 74 insertions, 0 deletions
diff --git a/challenge-115/dave-cross/perl/ch-1.pl b/challenge-115/dave-cross/perl/ch-1.pl
new file mode 100644
index 0000000000..1d02a3c6f4
--- /dev/null
+++ b/challenge-115/dave-cross/perl/ch-1.pl
@@ -0,0 +1,31 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+use feature 'say';
+
+my @words = get_words();
+
+# For a list of words to be able to form a string chain,
+# the set of first letters must be the same as the set of
+# last letters.
+
+my (@first, @last);
+
+# Get arrays containing the first and last letters
+for (@words) {
+ push @first, substr $_, 0, 1;
+ push @last, substr $_, -1, 1;
+}
+
+# Sort the arrays, join them into string and see if they're
+# the same.
+say +(join('', sort @first) eq join('', sort @last)) ? 1 : 0;
+
+sub get_words {
+ my @input = map { lc } grep { ! /[^a-z]/i } @ARGV;
+
+ die "Give me a list of words\n" unless @input;
+
+ return @input;
+}
diff --git a/challenge-115/dave-cross/perl/ch-2.pl b/challenge-115/dave-cross/perl/ch-2.pl
new file mode 100644
index 0000000000..cc1693046c
--- /dev/null
+++ b/challenge-115/dave-cross/perl/ch-2.pl
@@ -0,0 +1,43 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+use feature 'say';
+
+# The naive approach is to just sort the input integers
+# in reverse order and print the result. But this doesn't
+# guarantee that the output is an even number.
+#
+# So, we find the smallest even integer in our list and
+# remove it. We then sort the remaining list and add the
+# smallest even number to the end.
+
+my @ints = get_ints();
+
+my ($min_even, $min_even_idx);
+# This is bigger than the bigger allowed input number
+$min_even = 10;
+
+while (my ($i, $v) = each @ints) {
+ if ($v < $min_even and ! ($v % 2)) {
+ $min_even = $v;
+ $min_even_idx = $i;
+ }
+}
+
+splice @ints, $min_even_idx, 1;
+
+print sort { $b <=> $a } @ints;
+say $min_even;
+
+sub get_ints {
+ my @input = grep { /^\d$/ } @ARGV;
+
+ die "Give me a list of positive integers under 10\n" unless @input;
+
+ unless (grep { !($_ % 2) } @input) {
+ die "There must be at least one even number in the list\n";
+ }
+
+ return @input;
+}