aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--challenge-306/mahnkong/perl/ch-1.pl22
-rw-r--r--challenge-306/mahnkong/perl/ch-2.pl35
2 files changed, 57 insertions, 0 deletions
diff --git a/challenge-306/mahnkong/perl/ch-1.pl b/challenge-306/mahnkong/perl/ch-1.pl
new file mode 100644
index 0000000000..4ceac60be1
--- /dev/null
+++ b/challenge-306/mahnkong/perl/ch-1.pl
@@ -0,0 +1,22 @@
+use strict;
+use warnings;
+use feature 'signatures';
+use Test::More 'no_plan';
+
+sub run(@ints) {
+ my $sum = 0;
+ for (my $i = 1; $i <= scalar(@ints); $i +=2) {
+ my $start = 0;
+ while ($start + $i <= scalar(@ints)) {
+ my $end = $start + $i-1;
+ for my $e (@ints[$start..$end]) {
+ $sum += $e;
+ }
+ $start +=1;
+ }
+ }
+ return $sum;
+}
+
+is(run(2, 5, 3, 6, 4), 77, "Example 1");
+is(run(1, 3), 4, "Example 2");
diff --git a/challenge-306/mahnkong/perl/ch-2.pl b/challenge-306/mahnkong/perl/ch-2.pl
new file mode 100644
index 0000000000..7473efbfa3
--- /dev/null
+++ b/challenge-306/mahnkong/perl/ch-2.pl
@@ -0,0 +1,35 @@
+use strict;
+use warnings;
+use feature 'signatures';
+use Test::More 'no_plan';
+
+sub get_largest_int($ints_ref, $not_larger_than = undef) {
+ my $largest = {};
+ for (my $i = 0; $i <= $#$ints_ref; $i++) {
+ if (!exists($largest->{value}) || ($ints_ref->[$i] > $largest->{value} && (! defined $not_larger_than || $ints_ref->[$i] < $not_larger_than))) {
+ $largest->{value} = $ints_ref->[$i];
+ $largest->{index} = $i;
+ }
+ }
+ return $largest;
+}
+
+sub run(@ints) {
+ while (scalar(@ints) > 1) {
+ my @new;
+ my $l1 = get_largest_int(\@ints);
+ my $l2 = get_largest_int(\@ints, $l1->{value});
+ my ($x, $y) = $l1->{index} < $l2->{index} ? ($l1->{value}, $l2->{value}) : ($l2->{value}, $l1->{value});
+
+ foreach my $i (@ints) {
+ if ($i != $x) {
+ push @new, $i == $y ? $y - $x : $i;
+ }
+ }
+ @ints = @new;
+ }
+ return scalar(@ints) > 0 ? $ints[$#ints] : 0;
+}
+
+is(run(3, 8, 5, 2, 9, 2), 1, "Example 1");
+is(run(3, 2, 5), 0, "Example 2");