diff options
| author | Andreas Mahnke <andreas.mahnke@leuphana.de> | 2025-01-27 17:27:10 +0100 |
|---|---|---|
| committer | Andreas Mahnke <andreas.mahnke@leuphana.de> | 2025-01-27 17:27:10 +0100 |
| commit | 352307760f63bc591f8f450a6edee2e33c3cc72e (patch) | |
| tree | 1bed501c56f438a28688458209fa0318671361a7 /challenge-306 | |
| parent | 906bb690f8e1d091ac358c4ac77818bf879144c8 (diff) | |
| download | perlweeklychallenge-club-352307760f63bc591f8f450a6edee2e33c3cc72e.tar.gz perlweeklychallenge-club-352307760f63bc591f8f450a6edee2e33c3cc72e.tar.bz2 perlweeklychallenge-club-352307760f63bc591f8f450a6edee2e33c3cc72e.zip | |
Challenge 306
Diffstat (limited to 'challenge-306')
| -rw-r--r-- | challenge-306/mahnkong/perl/ch-1.pl | 21 | ||||
| -rw-r--r-- | challenge-306/mahnkong/perl/ch-2.pl | 35 |
2 files changed, 56 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..363f464537 --- /dev/null +++ b/challenge-306/mahnkong/perl/ch-1.pl @@ -0,0 +1,21 @@ +use strict; +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"); |
