The weekly challenge 267 - Task 1: Product Sign

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-267/#TASK1
 3 #
 4 # Task 1: Product Sign
 5 # ====================
 6 #
 7 #
 8 # You are given an array of @ints.
 9 #
10 # Write a script to find the sign of product of all integers in the given
11 # array. The sign is 1 if the product is positive, -1 if the product is
12 # negative and 0 if product is zero.
13 #
14 ## Example 1
15 ##
16 ## Input: @ints = (-1, -2, -3, -4, 3, 2, 1)
17 ## Output: 1
18 ##
19 ## The product -1 x -2 x -3 x -4 x 3 x 2 x 1 => 144 > 0
20 #
21 ## Example 2
22 ##
23 ## Input: @ints = (1, 2, 0, -2, -1)
24 ## Output: 0
25 ##
26 ## The product 1 x 2 x 0 x -2 x -1 => 0
27 #
28 ## Example 3
29 ##
30 ## Input: @ints = (-1, -1, 1, -1, 2)
31 ## Output: -1
32 ##
33 ## The product -1 x -1 x 1 x -1 x 2 => -2 < 0
34 #
35 ############################################################
36 ##
37 ## discussion
38 ##
39 ############################################################
40 #
41 # Multiply the integers one after another. If the result is 0,
42 # we can short-circuit the execution by returning 0 right away.
43 # After the loop, if the result is > 0, we can return 1, otherwise
44 # we return -1.
45 
46 use strict;
47 use warnings;
48 
49 product_sign(-1, -2, -3, -4, 3, 2, 1);
50 product_sign(1, 2, 0, -2, -1);
51 product_sign(-1, -1, 1, -1, 2);
52 
53 sub product_sign {
54    my @ints = @_;
55    print "Input: (", join(", ", @ints), ")\n";
56    my $p = 1;
57    foreach my $i (@ints) {
58       $p *= $i;
59       if($p == 0) {
60          print "Output: 0\n";
61          return;
62       }
63    }
64    if($p > 0) {
65       print "Output: 1\n";
66       return;
67    }
68    print "Output: -1\n";
69 }
70