/
ch-2.pl
executable file
·59 lines (48 loc) · 1.32 KB
/
ch-2.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
#!/usr/bin/perl
use v5.26; # The Weekly Challenge - 2024-01-15
use utf8; # Week 252 task 2 - Unique sum zero
use strict; # Peter Campbell Smith
use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge
binmode STDOUT, ':utf8';
unique_sum_zero(1);
unique_sum_zero(5);
unique_sum_zero(50);
sub unique_sum_zero {
my ($n, $method, $sum, $j, @array, %used);
$n = shift @_;
say qq[\nInput: \$n = $n];
# try two ways
for $method (1 .. 2) {
@array = ();
# use -n to +n, including 0 in the middle if an odd number
if ($method == 1) {
push @array, 0 if $n & 1;
for $j (1 .. int($n / 2)) {
push @array, -$j;
unshift @array, $j
}
# choose $n - 1 random numbers and add - $sum - unless it has already been used
} elsif ($method == 2) {
while (1) {
$sum = 0;
@array = ();
%used = ();
# fill @array with $n - 1 random integers from the range -$n to +$n
while (@array < $n - 1) {
$j = int(rand($n * 2)) - $n;
next if $used{$j};
$used{$j} = 1;
push @array, $j;
$sum += $j;
}
# add the negated sum unless it has been used already
push @array, -$sum;
last unless $used{-$sum};
}
}
# show result
$sum = 0;
$sum += $array[$_] for 0 .. $n - 1;
say qq[Output: (] . join(', ', @array) . qq[), \$sum = $sum];
}
}