28 March 2024 | Challenge 262 |
Positive, Negative or Divisible?
Task 1: Max Positive Negative
Submitted by: Mohammad Sajid Anwar
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
Solution
The values returned from the numeric equality operator <=>
may be used as an array index to count positive and negative values.
Ignoring zeros, the maximum over the first and the last array element is the requested count.
use v5.24;
use warnings;
use List::Util qw(max reduce);
sub mpn {
max +(reduce {$a->[1 + ($b <=> 0)]++; $a} [0,0,0], @_)->@[0,2];
}
See the full solution.
Task 2: Count Equal Divisible
Submitted by: Mohammad Sajid Anwar
You are given an array of integers, @ints
and an integer $k
.
Write a script to return the number of pairs (i, j) where
a) 0 <= i < j < size of @ints
b) ints[i] == ints[j]
c) i x j is divisible by k
Example 1
Input: @ints = (3,1,2,2,2,1,3) and $k = 2
Output: 4
(0, 6) => ints[0] == ints[6] and 0 x 6 is divisible by 2
(2, 3) => ints[2] == ints[3] and 2 x 3 is divisible by 2
(2, 4) => ints[2] == ints[4] and 2 x 4 is divisible by 2
(3, 4) => ints[3] == ints[4] and 3 x 4 is divisible by 2
Example 2
Input: @ints = (1,2,3) and $k = 1
Output: 0
Solution
The task can be translated to PDL almost literally:
- check the index order
- compare the indexed values
- check the index product modulo
$k
. - count the elements satisfying the above criteria.
An important detail is the usage of the bitwise AND operator &
instead of the logical AND operator &&
that cannot be overload
ed.
use strict;
use warnings;
use PDL;
sub ced {
my $k = shift;
my $ints = long @_;
my $i = sequence($ints);
my $j = $i->dummy(0);
which(($j > $i) & ($ints->dummy(0) == $ints) & ! ($i * $j % $k))->nelem;
}
See the full solution.
If you have a question about this post or if you like to comment on it, feel free to open an issue in my github repository.