perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 320 - Task 1: Maximum Count

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-320/#TASK1
 3 #
 4 # Task 1: Maximum Count
 5 # =====================
 6 #
 7 # You are given an array of integers.
 8 #
 9 # Write a script to return the maximum between the number of positive and
10 # negative integers. Zero is neither positive nor negative.
11 #
12 ## Example 1
13 ##
14 ## Input: @ints = (-3, -2, -1, 1, 2, 3)
15 ## Output: 3
16 ##
17 ## There are 3 positive integers.
18 ## There are 3 negative integers.
19 ## The maximum between 3 and 3 is 3.
20 #
21 #
22 ## Example 2
23 ##
24 ## Input: @ints = (-2, -1, 0, 0, 1)
25 ## Output: 2
26 ##
27 ## There are 1 positive integers.
28 ## There are 2 negative integers.
29 ## The maximum between 2 and 1 is 2.
30 #
31 #
32 ## Example 3
33 ##
34 ## Input: @ints = (1, 2, 3, 4)
35 ## Output: 4
36 ##
37 ## There are 4 positive integers.
38 ## There are 0 negative integers.
39 ## The maximum between 4 and 0 is 4.
40 #
41 ############################################################
42 ##
43 ## discussion
44 ##
45 ############################################################
46 #
47 # We just count the positive and the negative integers.
48 # Then we look which of these two numbers is bigger.
49 
50 use v5.36;
51 
52 maximum_count(-3, -2, -1, 1, 2, 3);
53 maximum_count(-2, -1, 0, 0, 1);
54 maximum_count(1, 2, 3, 4);
55 
56 sub maximum_count(@ints) {
57     say "Input: (" . join(", ", @ints) . ")";
58     my $neg = 0;
59     my $pos = 0;
60     foreach my $elem (@ints) {
61         if($elem > 0) {
62             $pos++;
63         } elsif ( $elem < 0 ) {
64             $neg++;
65         }
66     }
67     if($neg > $pos) {
68         say "Output: $neg";
69     } else {
70         say "Output: $pos";
71     }
72 }