Sorry, I hadn't studied the code well enough that you intended
to find years with a unique solution, and the solution requiring
six terms. A modified version of my program finds 5106 and 5328.
Also, my modified versions no longer has three digits hardcoded.
You can now give the number of digits on the command line -
you can also give the minimum number of terms in the unique
solution, and the range of years to investigate. Unfortunally,
doing it for 4 digits takes a long time. There are
about 12 billion sums to consider, compared to about 14 thousand
for 3 digits.
Abigail
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
GetOptions 'digits=i' => \my $digits, # Number of digits.
'min=i' => \my $min, # Minimum sum.
'max=i' => \my $max, # Maximum sum.
'terms=i' => \my $terms, # Minimum number of terms in su
+m.
;
$digits ||= 3;
$min ||= 0;
$max ||= 0x7FFFFFFF;
$terms ||= 6;
#
# Return all permutations of a set.
#
sub perms;
sub perms {
@_ ? map {my $i = $_; map {[$_ [$i] => @$_]}
perms @_ [0 .. $i - 1, $i + 1 .. $#_]} 0 .. $#_ : [];
}
#
# Return the powerset of a set.
#
sub power_set;
sub power_set {
@_ ? do {my @r = power_set @_ [1 .. $#_];
[$_ [0]] => @r => map {[$_ [0] => @$_]} @r} : ()
}
my %answers;
sub try {
local $" = " + ";
foreach my $set (power_set @_) {
my $sum = eval "@$set";
push @{$answers {$sum}} => $set;
}
}
OUTER:
foreach (("0" x $digits) .. ("9" x $digits)) {
my @digits = split //;
for (my $i = 1; $i < @digits; $i ++) {
next OUTER if $digits [$i] < $digits [$i - 1]
}
my %seen;
try grep {!$seen {$_} ++}
map {$_ = join "" => @$_; s/^0*(?=\d)//; $_} perms @digit
+s;
}
foreach my $sum (sort {$a <=> $b} keys %answers) {
next unless $sum >= $min && $sum < $max;
next unless @{$answers {$sum}} == 1;
next unless @{$answers {$sum} [0]} >= $terms;
local $" = " + ";
print "$sum == @{$answers{$sum}[0]}\n";
}
__END__
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|