I have a real-world problem (not homework!) that requires finding the sum of a subset of set A that equals the sum of a subset of some other set B.
A very similar question with a helpful answer is here.
Consider this example:
@a = qw(200 2000 2000 2000 4000);
@b = qw(528 565 800 1435 2000 2000 2872);
Using the code provided in the accepted answer to that question, I get the following output:
sum(200 2000 4000) = sum(528 800 2000 2872)
sum(200 4000 4000) = sum(528 800 2000 2000 2872)
sum(200 4000) = sum(528 800 2872)
sum(200 2000 2000 2000 4000) = sum(528 800 2000 2000 2000 2872)
For my purposes, I only want the answer(s) that use the fewest elements of the input sets. In this example, I just want
sum(200 4000) = sum(528 800 2872)
because all of the other answers also have 200
and 4000
in the sum. That is, I'm looking for just the "simplest" possible sums (in the sense that they use the fewest elements). Can someone suggest a reasonably efficient way of doing this? (Brute force is okay as my arrays aren't that large.)
Also, I should note that the second line of the output, sum(200 4000 4000) ...
, isn't correct because 4000
only appears once in @a
. I'm afraid I don't understand the algorithm well enough to see why this is happening.
Any help with either of these would be much appreciated!