The knapsack algorithm breaks if it can't fill the whole bag.
It will fill the entire bag with the smallest weight item instead.
public void TestKnapsack()
{
var set = new Dictionary<int, float>()
{
{ 1, 1f }, { 2, 2f }, { 4, 4f }
};
string Result(Dictionary<int, int> result)
{
var str = "";
foreach (var p in result)
{
str += $"{p.Key} * {p.Value}\n";
}
return str;
}
var ten = PTUtils.Knapsack(set, 10.0f);
var tenPointFive = PTUtils.Knapsack(set, 10.5f);
//as expected
Debug.Log(Result(ten));
//4 * 2
//2 * 1
//1 * 0
//wrong
Debug.Log(Result(tenPointFive));
//4 * 0
//2 * 0
//1 * 10
}
Run the provided code and see that the result is not as expected.
Description
The knapsack algorithm breaks if it can't fill the whole bag.
It will fill the entire bag with the smallest weight item instead.
Version
Steps to reproduce
Run the provided code and see that the result is not as expected.