I am working on an application that needs to match two sets of data based on various criteria, including the sum of any number of items from each set. I’ve distilled the problem down to this statement:
Given a set of items and transactions, find the smallest set of items where the sum is equal to the sum of the smallest set of transactions. (There’s some complexity I’m ignoring for this post, but for now I’m only concerned about the total amounts matching, not dates, descriptions, clearing differences, etc.)
Or, mathematically:Given two sets of numbers, find the smallest set from each where the sums are equal.
The other similar SO questions I’ve run across assume you know the sum ahead of time, or know the quantity from each set that you are going for.
And here is a test that (I think) illustrates what I’m going for.
[TestMethod]
public void StackOverflowTest()
{
var seta = new[]{10, 20, 30, 40, 50};
var setb = new[]{ 45, 45, 100, 200 };
var result = Magic(seta, setb);
Assert.AreEqual(new[]{40,50},result.SetA);
Assert.AreEqual(new[] { 45, 45 }, result.SetB);
}
class MagicResult
{
public int[] SetA { get; set; }
public int[] SetB { get; set; }
}
private MagicResult Magic(int[] seta, int[] setb)
{
throw new NotImplementedException();
}
I’m looking for an elegant solution that will make this pass, but will take any pseudocode or suggestion that gets me there 😉
Brute force:
using the Subsets method from the EvenMoreLINQ project.