The weekly challenge 252 - Task 2: Unique Sum Zero

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-252/#TASK2
 3 #
 4 # Task 2: Unique Sum Zero
 5 # =======================
 6 #
 7 # You are given an integer, $n.
 8 #
 9 # Write a script to find an array containing $n unique integers such that they
10 # add up to zero.
11 #
12 ## Example 1
13 ##
14 ## Input: $n = 5
15 ## Output: (-7, -1, 1, 3, 4)
16 ##
17 ## Two other possible solutions could be as below:
18 ## (-5, -1, 1, 2, 3) and (-3, -1, 2, -2, 4).
19 #
20 ## Example 2
21 ##
22 ## Input: $n = 3
23 ## Output: (-1, 0, 1)
24 #
25 ## Example 3
26 ##
27 ## Input: $n = 1
28 ## Output: (0)
29 #
30 ############################################################
31 ##
32 ## discussion
33 ##
34 ############################################################
35 #
36 # Since we only need to find one array with unique integers, we can
37 # simply use one with both i and -i in it, with |i| growing, starting
38 # at 1. In case of an odd number we just add 0 to the array.
39 use strict;
40 use warnings;
41 
42 unique_sum_zero(5);
43 unique_sum_zero(3);
44 unique_sum_zero(1);
45 unique_sum_zero(2);
46 unique_sum_zero(4);
47 unique_sum_zero(0);
48 
49 sub unique_sum_zero {
50    my $n = shift;
51    print "Input: $n\n";
52    my @result = ();
53    return print "Output: ()\n" if $n == 0;
54    if($n % 2 == 0) {
55       # We always use i and -i, ending up at a sum of 0.
56       my $val = $n / 2;
57       push @result, (-$val..-1);
58       push @result, (1..$val);
59    } else {
60       # We always use i and -i, ending up at a sum of 0 if we add 0.
61       my $val = int($n / 2);
62       push @result, (-$val..-1);
63       push @result, 0;
64       push @result, (1..$val);
65    }
66    print "Output: (", join(", ", @result), ")\n";
67 }
68