Someone else came to me with a 1D variant of this problem as a homework example. I wrote this recursive version in a few minutes. This finds all possible combinations for 1D; you could add a scoring mechanism to find the optimum choice. I'm sure it can be improved, but it's speedy enough and simple enough for homework.
#!/usr/bin/perl # First line of DATA is desired total and the tolerance. my $Finish = <DATA>; my ($Wanted, $Tolerance) = ($Finish =~ /(-?\d+)\s+(\d+)/); # Other lines of DATA are the available elements. my @Items = (<DATA>); chomp @Items; #--------------------------------------------------------------------- +------- my $Stack = (); sub build { my $index = shift; my $total = shift; while ($index < @Items) { my $num = $Items[$index]; push(@Stack, $num); if ($num + $total > ($Wanted+$Tolerance)) { next; } elsif ($num + $total >= ($Wanted-$Tolerance) and $num + $total <= ($Wanted+$Tolerance)) { print "( @Stack ) = ", $num+$total, "\n"; } else { build($index+1, $num + $total); } } continue { pop(@Stack); $index++; } } #--------------------------------------------------------------------- +------- build(0, 0); __DATA__ 30 5 -5 5 10 15 20 10 25 25

--
[ e d @ h a l l e y . c c ]


In reply to Finding all subsets which have nearly the desired sum by halley
in thread Finding the simplest combination of descrete thicknesses that sums nearest to the target thickness. by doowah2004

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.