This chunk of code is the function that solves a variant of a subset sum problem, but I dont really understand how it gets the answer.
The function returns the subset sum that's closest to the value, if its the same as the value then it just return the value, if two subsets sums are equally close to the value then return the greater sum.
This is it
public static List<int> SolveSubsetSum(int value, IEnumerable<int> xs)
{
int b = 2*value+1;
List<int>[] cols = new List<int>[b];
cols[0] = new List<int>();
foreach(int xi in xs) {
for(int s = b-xi-1; s >= 0; s--) {
if(cols[s+xi] == null && cols[s] != null) {
List<int> cln = new List<int>(cols[s]);
cln.Add(xi);
cols[s+xi] = cln;
}
}
}
for(int d = 0; d <= value; d++) {
if(cols[value+d] != null) {
return cols[value+d];
}
else if(cols[value-d] != null) {
return cols[value-d];
}
}
return cols[0];
}
I understand the standard stuff, but I have no clue whats going on in the loops.
My main questions are
Why does it need an array of
2*value+1
collections ?Whats going on in the loops ?