Here is an example:
Customer orders 57 single peaces of an item. The company only sells in units of 15 and 6.
The algorithm has to figure out the best possible combination of UOMs (unit of measure) with the following priorities in order of importance
- least amount of overage
- using highest unit of measure
In this example the expected result is List<int>
:
{ 15, 15, 15, 6, 6 } //sum=57
I've researched "bin packing" and "knapsack problem" but couldn't figure out how it could be applied in this case.
So far I have this which is clearly doesn't accomplish the best combination.
void Main()
{
var solver = new Solver();
var r = solver.Solve(57, new decimal [] {6, 15}).Dump();
}
public class Solver
{
public List<decimal> mResults;
public List<decimal> Solve(decimal goal, decimal[] elements)
{
mResults = new List<decimal>();
RSolve(goal, 0m, elements, elements.Where(e => e <= goal).OrderByDescending(x => x).FirstOrDefault());
return mResults;
}
public void RSolve(decimal goal, decimal currentSum, decimal[] elements, decimal toAdd)
{
if(currentSum >= goal)
return;
currentSum += toAdd;
mResults.Add(toAdd);
var remainder = goal - currentSum;
var nextToAdd = elements.Where(e => e <= remainder).OrderByDescending(e => e).FirstOrDefault();
if(nextToAdd == 0)
nextToAdd = elements.OrderBy(e => e).FirstOrDefault();
RSolve(goal, currentSum, elements, nextToAdd);
}
}