diff options
| -rwxr-xr-x | challenge-306/perlboy1967/perl/ch1.pl | 44 | ||||
| -rwxr-xr-x | challenge-306/perlboy1967/perl/ch2.pl | 51 |
2 files changed, 95 insertions, 0 deletions
diff --git a/challenge-306/perlboy1967/perl/ch1.pl b/challenge-306/perlboy1967/perl/ch1.pl new file mode 100755 index 0000000000..402d471548 --- /dev/null +++ b/challenge-306/perlboy1967/perl/ch1.pl @@ -0,0 +1,44 @@ +#!/bin/perl + +=pod + +The Weekly Challenge - 306 +L<https://theweeklychallenge.org/blog/perl-weekly-challenge-306#TASK1> + +Author: Niels 'PerlBoy' van Dijke + +Task 1: Odd Sum +Submitted by: Mohammad Sajid Anwar + +You are given an array of positive integers, @ints. + +Write a script to return the sum of all possible odd-length subarrays of +the given array. A subarray is a contiguous subsequence of the array. + +=cut + +use v5.32; +use common::sense; +use feature qw(signatures); + +use Test2::V0 qw(-no_srand); + +no warnings qw(experimental::signatures); + +use List::Util qw(sum); + +sub oddSum (@ints) { + my ($sum,$i) = (0,1); + while ($i <= scalar @ints) { + for my $j (0 .. scalar(@ints)-$i) { + $sum += sum(@ints[$j..$j+$i-1]) + } + $i += 2; + } + return $sum; +} + +is(oddSum(2,5,3,6,4),77,'Example 1'); +is(oddSum(1,3),4,'Example 2'); + +done_testing; diff --git a/challenge-306/perlboy1967/perl/ch2.pl b/challenge-306/perlboy1967/perl/ch2.pl new file mode 100755 index 0000000000..564254d8a2 --- /dev/null +++ b/challenge-306/perlboy1967/perl/ch2.pl @@ -0,0 +1,51 @@ +#!/bin/perl + +=pod + +The Weekly Challenge - 306 +L<https://theweeklychallenge.org/blog/perl-weekly-challenge-306#TASK1> + +Author: Niels 'PerlBoy' van Dijke + +Task 2: Last Element +Submitted by: Mohammad Sajid Anwar + +You are given a array of integers, @ints. + +Write a script to play a game where you pick two biggest integers in the given array, +say x and y. Then do the following: + +a) if x == y then remove both from the given array +b) if x != y then remove x and replace y with (y - x) + +At the end of the game, there is at most one element left. + +Return the last element if found otherwise return 0. + +=cut + +use v5.32; +use common::sense; +use feature qw(signatures); + +use Test2::V0 qw(-no_srand); + +no warnings qw(experimental::signatures); + +sub lastElement (@ints) { + my @s = sort { $a <=> $b } @ints; + while (@s > 1) { + my $i = pop(@s); + if (@s) { + my $j = pop(@s); + @s = sort { $a <=> $b } @s,$i-$j if ($i != $j); + return 0 unless @s; + } + } + return $s[-1]; +} + +is(lastElement(3,8,5,2,9,2),1,'Example 1'); +is(lastElement(3,2,5),0,'Example 2'); + +done_testing; |
