aboutsummaryrefslogtreecommitdiff
path: root/challenge-078
diff options
context:
space:
mode:
authorMohammad S Anwar <mohammad.anwar@yahoo.com>2020-09-15 20:34:57 +0100
committerMohammad S Anwar <mohammad.anwar@yahoo.com>2020-09-15 20:34:57 +0100
commit5e0fbeae30637c44e522dc2df7272885f22b0357 (patch)
tree71d7898dba7b8dec37fb78ebc57d445b76b64727 /challenge-078
parent45ec20a8ba5c6ff2038366ad8775467e36466dd3 (diff)
downloadperlweeklychallenge-club-5e0fbeae30637c44e522dc2df7272885f22b0357.tar.gz
perlweeklychallenge-club-5e0fbeae30637c44e522dc2df7272885f22b0357.tar.bz2
perlweeklychallenge-club-5e0fbeae30637c44e522dc2df7272885f22b0357.zip
- Added Perl solution to task #1 of week #78.
Diffstat (limited to 'challenge-078')
-rw-r--r--challenge-078/mohammad-anwar/perl/ch-1.pl49
-rw-r--r--challenge-078/mohammad-anwar/perl/ch-1.t49
2 files changed, 98 insertions, 0 deletions
diff --git a/challenge-078/mohammad-anwar/perl/ch-1.pl b/challenge-078/mohammad-anwar/perl/ch-1.pl
new file mode 100644
index 0000000000..8e50189ec3
--- /dev/null
+++ b/challenge-078/mohammad-anwar/perl/ch-1.pl
@@ -0,0 +1,49 @@
+#!/usr/bin/perl
+
+#
+# Perl Weekly Challenge - 078
+#
+# Task #1: Leader Element
+#
+# https://perlweeklychallenge.org/blog/perl-weekly-challenge-078
+#
+
+use strict;
+use warnings;
+use List::Util qw(max);
+
+printf("%s\n", join(", ", leader_elements(get_list($ARGV[0]))));
+
+#
+#
+# METHODS
+
+sub leader_elements {
+ my ($list) = @_;
+
+ my @leaders = ();
+ my $i = 0;
+ my @array = @$list;
+ foreach my $n (@array) {
+ if ($i == $#array) {
+ push @leaders, $n;
+ }
+ else {
+ push @leaders, $n
+ if ($n > max(@array[$i+1 .. $#array]));
+ }
+ $i++;
+ }
+
+ return @leaders;
+}
+
+sub get_list {
+ my ($l) = @_;
+
+ die "ERROR: Missing list.\n" unless defined $l;
+ die "ERROR: Invalid list [$l].\n" unless ($l =~ /^[\-?\d\,?\s?]+$/);
+
+ $l =~ s/\s//g;
+ return [ split /\,/, $l ];
+}
diff --git a/challenge-078/mohammad-anwar/perl/ch-1.t b/challenge-078/mohammad-anwar/perl/ch-1.t
new file mode 100644
index 0000000000..ef48a0eeba
--- /dev/null
+++ b/challenge-078/mohammad-anwar/perl/ch-1.t
@@ -0,0 +1,49 @@
+#!/usr/bin/perl
+
+#
+# Perl Weekly Challenge - 078
+#
+# Task #1: Leader Element
+#
+# https://perlweeklychallenge.org/blog/perl-weekly-challenge-078
+#
+
+use strict;
+use warnings;
+use Test::More;
+use Test::Deep;
+use List::Util qw(max);
+
+is_deeply([leader_elements([9, 10, 7, 5, 6, 1])],
+ [10, 7, 6, 1],
+ "testing example 1");
+
+is_deeply([leader_elements([3, 4, 5])],
+ [5],
+ "testing example 2");
+
+done_testing;
+
+#
+#
+# METHOD
+
+sub leader_elements {
+ my ($list) = @_;
+
+ my @leaders = ();
+ my $i = 0;
+ my @array = @$list;
+ foreach my $n (@array) {
+ if ($i == $#array) {
+ push @leaders, $n;
+ }
+ else {
+ push @leaders, $n
+ if ($n > max(@array[$i+1 .. $#array]));
+ }
+ $i++;
+ }
+
+ return @leaders;
+}