From 29f384236e56f32faddf1bd726e90447f21ed179 Mon Sep 17 00:00:00 2001 From: Niels van Dijke Date: Mon, 10 Nov 2025 14:37:31 +0000 Subject: w345 - Task 1 & 2 (Perl) --- challenge-345/perlboy1967/perl/ch1.pl | 33 ++++++++++++++++++++ challenge-345/perlboy1967/perl/ch2.pl | 57 +++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100755 challenge-345/perlboy1967/perl/ch1.pl create mode 100755 challenge-345/perlboy1967/perl/ch2.pl diff --git a/challenge-345/perlboy1967/perl/ch1.pl b/challenge-345/perlboy1967/perl/ch1.pl new file mode 100755 index 0000000000..891d1f6626 --- /dev/null +++ b/challenge-345/perlboy1967/perl/ch1.pl @@ -0,0 +1,33 @@ +#!/bin/perl + +=pod + +L + +Author: Niels 'PerlBoy' van Dijke + +Task 1: Peak Positions +Submitted by: Mohammad Sajid Anwar + +You are given an array of integers, @ints. + +Find all the peaks in the array, a peak is an element that is strictly +greater than its left and right neighbours. Return the indices of all such +peak positions. + +=cut + +use Test2::V0 qw(-no_srand); +use exact 'v5.32', -signatures; + +sub peakPositions (@ints) { + map { $ints[$_-1] < $ints[$_] > $ints[$_+1] ? $_ : () } 1 .. $#ints - 1; +} + +is([peakPositions(1,3,2)],[1],'Example 1'); +is([peakPositions(2,4,6,5,3)],[2],'Example 2'); +is([peakPositions(1,2,3,2,4,1)],[2,4],'Example 3'); +is([peakPositions(5,3,1)],[],'Example 4'); +is([peakPositions(1,5,1,5,1,5,1)],[1,3,5],'Example 5'); + +done_testing; diff --git a/challenge-345/perlboy1967/perl/ch2.pl b/challenge-345/perlboy1967/perl/ch2.pl new file mode 100755 index 0000000000..1621f26920 --- /dev/null +++ b/challenge-345/perlboy1967/perl/ch2.pl @@ -0,0 +1,57 @@ +#!/bin/perl + +=pod + +L + +Author: Niels 'PerlBoy' van Dijke + +Task 2: Last Visitor +Submitted by: Mohammad Sajid Anwar + +You are given an integer array @ints where each element is either a positive integer or -1. + +We process the array from left to right while maintaining two lists: + +|| @seen: stores previously seen positive integers (newest at the front) +|| @ans: stores the answers for each -1 + +Rules: + +If $ints[i] is a positive number -> insert it at the front of @seen +If $ints[i] is -1: + +Let $x be how many -1s in a row we’ve seen before this one. + +If $x < len(@seen) -> append seen[x] to @ans + +Else -> append -1 to @ans + +At the end, return @ans. + +=cut + +use Test2::V0 qw(-no_srand); +use exact 'v5.32', -signatures; + +sub lastVisitor (@ints) { + my ($i,@seen,@ans) = (0); + for (@ints) { + if ($_ >= 0) { + push(@seen,$_); + $i++ if ($i < 0); + } else { + $i += $_ if (@seen); + push(@ans,$seen[$i] // -1); + } + } + return @ans; +} + +is([lastVisitor(5,-1,-1)],[5,-1],'Example 1'); +is([lastVisitor(3,7,-1,-1,-1)],[7,3,-1],'Example 2'); +is([lastVisitor(2,-1,4,-1,-1)],[2,4,2],'Example 3'); +is([lastVisitor(10,20,-1,30,-1,-1)],[20,30,20],'Example 4'); +is([lastVisitor(-1,-1,5,-1)],[-1,-1,5],'Example 5'); + +done_testing; -- cgit