Given I have a list of integers like this:
List<int> items = new List<int> {200, 100, 50, 20, 10, 5, 2, 1};
and given I have a number, say 13, how will I find the numbers from the list which adds up to 13 using LINQ (or any other way). The list is always in the descending order.
For example: 13 = 10 + 2+ 1, so the linq operation would give me back a list of integers containing 10,2 and 1.
If we cant find the full match as in the case of 24, it's ok for an exception to be generated.
Effort:
[Test]
public void Should_find_subset()
{
var items = new List<int>() {200, 100, 50, 20, 10, 5, 2, 1};
var find = 13;
var result = new List<int>();
var subset = new List<int>();
bool found = false;
foreach (var item in items)
{
if (item == find)
{
result.Add(item);
found = true;
}
if (item < find)
{
subset.Add(item);
found = subset.Sum() == find;
}
if (found)
break;
}
}
Thanks,
-Mike