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.
Here my solution, without keyword 'my', without validating '@ints', without a module:
Alternative:sub max_pos_neg { ( ($pos = scalar(grep { $_ > 0 } @_)) > ($neg = scalar(grep { $_ < 0} @_)) ) ? print("max positive integers: $pos\n") : print("max negative integers: $neg\n"); } #assumption 1: no number 0 #assumption 2: number of positive and negative integers differ @ints = qw(-3 1 2 -1 3 -2 4); max_pos_neg(@ints);# max positive integers: 4 @ints = qw(-1 -2 -3 1); max_pos_neg(@ints);# max negative integers: 3 @ints = qw(1 2); max_pos_neg(@ints);# max positive integers: 2
assumption 1: no number 0 assumption 2: number of positive and negative integers differ, meaning - positive integers > negative integers: more than (scalar(@_)/2) is positive - negative integers > positive integers: less than (scalar(@_)/2) is positive
sub max_pos_neg { ( ($pos = scalar(grep { $_ > 0 } @_)) > (scalar(@_)/2) ) ? print("max positive integers: $pos\n") : print("max negative integers: ", (scalar(@_) - $pos) , "\n"); }
sub count_equal_divisible { ($aref, $k) = @_; @array = @{$aref}; $success = 0; for ($i = 0; $i < scalar(@array)-1; $i++) { for ($j = $i + 1; $j < scalar(@array); $j++) { $success++ if ( $array[$i] == $array[$j] && (($i * $j) % $k == 0) ); } } print("The number of equal divisible pairs (i, j): ", $success, "\n"); } @ints = qw(3 1 2 2 2 1 3); $k = 2; count_equal_divisible(\@ints, $k); # 4 @ints = qw(1 2 3); $k = 1; count_equal_divisible(\@ints, $k);# 0