The following should work; I haven't had the guts to run it on your real data yet, but my mini-testset seems to result in an answer...
#!/usr/bin/perl
=cut
my @t = (
'18.930167',
'17.967469',
'0.008720',
'0.008720',
'122.640000',
'12493.320000',
'359.520000',
'288.700000',
'359.520000',
'89.880000',
'32.960000',
'56.920000',
'13.470000',
'1231.360000',
'20587.440000',
'359.520000',
'792.170000',
'629.160000',
'972.290000',
);
my $target = 843.24;
=cut
my @t = (100,2,32,4,65);
my $target = 7;
my @terms = _test($target,@t);
for my $n (0..$#terms) {
next unless $terms[$n];
print (($terms[$n]<0)?'subtract':'add');
print " value number ",$n+1," (",$t[$n],")";
print "\n";
}
print "to obtain total of $target\n";
sub _test {
my ($target,$number,@rest) = @_;
for my $term (0,$number,-$number) {
if(@rest==0) {
next unless $target == sprintf('%.2f',$sum+$te
+rm);
return ($term/$number)
}
my @terms = _test(sprintf('%.2f',$target-$term),@rest)
+;
next unless @terms;
return (($term/$number),@terms);
}
return;
}
It's a recursive algorithm that will eventually try every possibility until it finds a working set of terms... It will probably take a long time with the real dataset, so you'll want to eliminate as many terms as possible beforehand.
-
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.