This is a relatively simple binary program.
I offer brute force with cropping. If at any time you exceed the permissible weight, you will not need to use combinations of additional items, you can discard the entire tree.
Oh, do you have negative weights? Always include all negative weights, then proceed as described above for positive weights. Or are negative values ββnegative?
Include all negative weights with a positive value. Exclude all items with a positive weight and a negative value.
For negative weights with a negative value, subtract their weight (increasing the capacity for the satchel) and use a pseudo-element that does not accept this item. The pseudo-element will have a positive weight and value. Perform brute force with cropping.
class Knapsack { double bestValue; bool[] bestItems; double[] itemValues; double[] itemWeights; double weightLimit; void SolveRecursive( bool[] chosen, int depth, double currentWeight, double currentValue, double remainingValue ) { if (currentWeight > weightLimit) return; if (currentValue + remainingValue < bestValue) return; if (depth == chosen.Length) { bestValue = currentValue; System.Array.Copy(chosen, bestItems, chosen.Length); return; } remainingValue -= itemValues[depth]; chosen[depth] = false; SolveRecursive(chosen, depth+1, currentWeight, currentValue, remainingValue); chosen[depth] = true; currentWeight += itemWeights[depth]; currentValue += itemValues[depth]; SolveRecursive(chosen, depth+1, currentWeight, currentValue, remainingValue); } public bool[] Solve() { var chosen = new bool[itemWeights.Length]; bestItems = new bool[itemWeights.Length]; bestValue = 0.0; double totalValue = 0.0; foreach (var v in itemValues) totalValue += v; SolveRecursive(chosen, 0, 0.0, 0.0, totalValue); return bestItems; } }
Ben voigt
source share