The Weekly Challenge - 320

TASK #1: Maximum Count
You are given an array of integers.

Write a script to return the maximum between the number of positive and negative integers. Zero is neither positive nor negative.

#!/usr/bin/perl
use strict;
use warnings;

sub max_count {
	
    my ($array_ref) = @_;
    die "Error: an array reference expected!" unless ref($array_ref) eq 'ARRAY';

    my ($pos, $neg) = (0, 0);
    
    foreach my $n (@$array_ref) {
        $pos++ if $n > 0;
        $neg++ if $n < 0;
    }	

    # alternative 	
    # Perl programmers often use grep in scalar context to count elements matching a condition. 	
    # my $pos = grep { $_ > 0 } @$array_ref;
    # my $neg = grep { $_ < 0 } @$array_ref;	
	
	return ($pos > $neg) ? $pos : $neg;
}

printf "%d\n",max_count([-3,-2,-1,1,2,3]); # 3
printf "%d\n",max_count([-2,-1,0,0,1]); # 2
printf "%d\n",max_count([1,2,3,4]); # 4
printf "%d\n",max_count([0,0,0,-1]); # 1