-
Notifications
You must be signed in to change notification settings - Fork 311
/
ch-1.pl
executable file
·73 lines (57 loc) · 1.82 KB
/
ch-1.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/perl
use strict;
use warnings;
use English;
################################################################################
# Begin main execution
################################################################################
my @integer_lists = (
[ -1, -2, -3, -4, 3, 2, 1 ],
[ 1, 2, 0, -2, -1 ],
[ -1, -1, 1, -1, 2 ]
);
print("\n");
foreach my $integer_list (@integer_lists){
printf(
"Input: \@ints = (%s)\nOutput: %d\n\n",
join(", ", @{$integer_list}),
list_product_sign(@{$integer_list})
);
}
exit(0);
################################################################################
# End main execution; subroutines follow
################################################################################
################################################################################
# Determine the sign of the product that would result from multiplying
# together all members of a list of integers
# Takes one argument:
# * A list of integers to examine (e.g. ( -1, -2, -3, -4, 3, 2, 1 ) )
# Returns:
# * -1 if the sign of the product would be negative
# * 0 if the product would be zero
# * 1 if the sign of the product would be positive
################################################################################
sub list_product_sign{
my $negatives = 0;
foreach my $int (@ARG){
# If an int is zero, the product of the list
# will be zero
return(0)
unless($int);
# Increment the negative count if this int
# is below zero
$negatives++
if($int < 0);
}
return(
$negatives % 2 ?
# Negative count is odd- product would be
# negative
-1
:
# Negative count is even- product would be
# positive
1
);
}