protected override void TryAddCell(int currentIndexValue, int currentItemIndex, int maxWeight, Queue <int> toVisitNext, KnapsackItem item = null) { var currentCell = memoryTable[currentIndexValue, currentItemIndex]; var newWeight = currentCell.Value; var newPrice = currentIndexValue; if (item != null) { newPrice += item.Price; newWeight += item.Weight; } //Weight limit reached if (newWeight > maxWeight) { return; } var nextCell = memoryTable[newPrice, currentItemIndex + 1]; //Add the new cell into the table if it is better than the one previously placed there if (nextCell == null || nextCell.Value > newWeight) { memoryTable[newPrice, currentItemIndex + 1] = new DPCell { AddedItem = (item != null), PreviousCell = currentCell, Value = newWeight }; toVisitNext.Enqueue(newPrice); } }
protected List <bool> GetItemVector(DPCell lastCell) { var itemsVector = new List <bool>(); var currentCell = lastCell; while (currentCell != null) { itemsVector.Add(currentCell.AddedItem); currentCell = currentCell.PreviousCell; } itemsVector.Reverse(); return(itemsVector); }
private DPCell FindBestCell(KnapsackInstance instance) { DPCell bestCell = memoryTable[toVisit.Dequeue(), instance.ItemCount - 1]; foreach (var weightIndex in toVisit) { var currentCell = memoryTable[weightIndex, instance.ItemCount - 1]; if (currentCell.Value > bestCell.Value) { bestCell = currentCell; } } return(bestCell); }
protected override void InitializeTable(KnapsackInstance instance) { memoryTable = new DPCell[instance.KnapsackSize + 1, instance.ItemCount]; toVisit = new Queue <int>(); toVisit.Enqueue(0); memoryTable[0, 0] = new DPCell { AddedItem = false, Value = 0 }; var firstItem = instance.Items.First(); if (firstItem.Weight <= instance.KnapsackSize) { toVisit.Enqueue(firstItem.Weight); memoryTable[firstItem.Weight, 0] = new DPCell { AddedItem = true, Value = firstItem.Price }; } }