## Perl Weekly Challenge 262: Max Positive Negative

These are some answers to the Week 262, Task 1, of the Perl Weekly Challenge organized by Mohammad S. Anwar.

Spoiler Alert: This weekly challenge deadline is due in a few days from now (on March 31, 2024 at 23:59). This blog post provides some solutions to this challenge. Please don’t read on if you intend to complete the challenge on your own.

## Task 1: Max Positive Negative

You are given an array of integers, `@ints`.

Write a script to return the maximum number of either positive or negative integers in the given array.

Example 1

``````Input: @ints = (-3, 1, 2, -1, 3, -2, 4)
Output: 4

Count of positive integers: 4
Count of negative integers: 3
Maximum of count of positive and negative integers: 4
``````

Example 2

``````Input: @ints = (-1, -2, -3, 1)
Output: 3

Count of positive integers: 1
Count of negative integers: 3
Maximum of count of positive and negative integers: 3
``````

Example 3

``````Input: @ints = (1,2)
Output: 2

Count of positive integers: 2
Count of negative integers: 0
Maximum of count of positive and negative integers: 2
``````

Although this is not clearly specified, we will consider only strictly positive and strictly negative input values (in other words, we will discard values equal to zero).

### Max Positive Negative in Raku

We use Raku built-in grep, elems, and max methods to come up with a one-liner solution in Raku.

``````sub max-pos-neg (@in) {
(@in.grep({\$_ > 0}).elems, @in.grep({\$_ < 0}).elems).max;
}

my @tests = <-3 1 2 -1 3 -2 4>, <-1 -2 -3 1>, <1 2>;
for @tests -> @test {
printf "%-20s => ", "@test[]";
say max-pos-neg @test;
}
``````

This program displays the following output:

``````\$ raku ./max-pos-neg.raku
-3 1 2 -1 3 -2 4     => 4
-1 -2 -3 1           => 3
1 2                  => 2
``````

### Max Positive Negative in Perl

This is a port to Perl of the above Raku program, with the only significant change being that we use the ternary operator (`? :`) to replace `max`.

``````use strict;
use warnings;
use feature 'say';

sub max_pos_neg {
my \$pos_count = scalar grep {\$_ > 0} @_;
my \$neg_count = scalar grep {\$_ < 0} @_;
\$pos_count > \$neg_count ? \$pos_count : \$neg_count;
}

my @tests = ( [<-3 1 2 -1 3 -2 4>],
[<-1 -2 -3 1>], [<1 2>] );
for my \$test (@tests) {
printf "%-20s => ", "@\$test";
say max_pos_neg @\$test;
}
``````

This program displays the following output:

``````\$ perl ./max-pos-neg.pl
-3 1 2 -1 3 -2 4     => 4
-1 -2 -3 1           => 3
1 2                  => 2
``````

## Wrapping up

The next week Perl Weekly Challenge will start soon. If you want to participate in this challenge, please check https://perlweeklychallenge.org/ and make sure you answer the challenge before 23:59 BST (British summer time) on April 7, 2024. And, please, also spread the word about the Perl Weekly Challenge if you can.