public void Execute(int capacity, KnapsackItem[] ksItems) { _capacity = capacity; for (var i = 0; i < ksItems.Length; i++) { var itemsToProcess = ksItems.Skip(i).ToArray(); var estimatedValue = GetEstimatedValue(itemsToProcess); var firstItem = itemsToProcess.First(); var firstNode = new KnapsackNode(firstItem.Value, firstItem.Weight, estimatedValue); firstNode.SelectedItems.Add(firstItem.Id); if (_bestNode == null) _bestNode = firstNode; if (estimatedValue <= _bestNode.AccumulatedValue) continue; var remaining = itemsToProcess.Skip(1).ToArray(); BuildTree(firstNode, remaining); } foreach (var i in _bestNode.SelectedItems) { var ksItem = ksItems.Single(p => p.Id == i); ksItem.Selected = 1; } }
public void Execute(int capacity, KnapsackItem[] ksItems) { _bestNode = new KnapsackNode(0, 0); _capacity = capacity; for (var i = 0; i < ksItems.Length; i++) { var itemsToProcess = ksItems.Skip(i).ToArray(); var firstItem = itemsToProcess.First(); var firstNode = new KnapsackNode(firstItem.Value, firstItem.Weight); firstNode.SelectedItems.Add(firstItem.Id); var remaining = itemsToProcess.Skip(1).ToArray(); BuildTree(firstNode, remaining); } foreach (var i in _bestNode.SelectedItems) { var ksItem = ksItems.Single(p => p.Id == i); ksItem.Selected = 1; } }