Peter
Peter Campbell Smith

Plus versus minus

Weekly challenge 262 — 25 March 2024

Week 262 - 25 Mar 2024

Task 1

Task — 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.

Examples


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

Analysis

This is an easy one-liner:
$count[$_ < 0 ? 0 : 1] ++ for @ints;

which leaves the number of negatives in $count[0] and the number of positives in $count[1].

We're not told how to handle zero, but my code would regard it as positive.

Try it 

Try running the script with any input:



example: 1, 2, 3, -1, -2, -3, -4

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2024-03-25
use utf8;     # Week 262 - task 1 - Max positive negative
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

my (@ints, $j, $num);

max_positive_negative(-3, 1, 2, -1, 3, -2, 4);
max_positive_negative(-1, -2, -3, 1);
max_positive_negative(1, 2);

# larger example
$j = 0;
while ($j < 100) {
    $num = int(rand(100)) - 50;
    $ints[$j ++] = $num if $num;
}
max_positive_negative(@ints);

sub max_positive_negative {
    
    my (@ints, @count);
    
    # initialise
    @ints = @_;
    @count = (0, 0);
    
    # count positive and negative values
    $count[$_ < 0 ? 0 : 1] ++ for @ints;
    
    # show result
    say qq[\nInput:  \@ints = (] . join(', ', @ints) . q[)];
    say qq[Output: ] . ($count[0] > $count[1] ? $count[0] : $count[1]) .
        qq[ ($count[0] negative, $count[1] positive)];
}

Output


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

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

Input:  @ints = (1, 2)
Output: 2 (0 negative, 2 positive)

Input:  @ints = (-15, -37, -43, -34, 22, 43, -30, -14, 20,
46, -13, 31, -32, 48, -4, -35, 10, -42, -10, 36, 30, -12,
-4, -5, 14, 46, 49, 4, 7, -26, -41, 10, -22, 36, -20, -11,
28, -27, -5, -22, -22, 18, 12, 29, -43, 40, -8, -13, 44,
3, 23, -4, -23, 13, -37, -19, -24, -29, -2, 26, -6, 30,
22, -50, -28, -31, -48, 6, -14, -26, 27, -42, 5, 32, -5,
-2, 38, 47, 18, 2, 2, 34, 10, -22, -24, -48, 5, 49, -28,
18, -21, -26, 17, 35, -18, 39, 19, -37, 9, 2)
Output: 52 (52 negative, 48 positive)

The content of this website which has been created by
Peter Campbell Smith is hereby placed in the public domain