public double Evaluate(IChromosome chromosome) { BinaryChromosome knapsackConfiguration = (BinaryChromosome)chromosome; int length = knapsackConfiguration.Length; ulong value = knapsackConfiguration.Value; for (int i = 0; i < length; i++) { if ((value & TestBitsMask[i]) == 0) { _bag.RemoveItem(_items[i]); } else { _bag.InsertItem(_items[i]); } } if (_bag.AcceptableWeight()) { return(_bag.ItemsCost()); } return(0); }
public int Solve(KnapsackProblemModel problem) { Bag bag = new Bag(problem.BagCapacity); List <Item> items = problem.Items.ToList(); int count = items.Count; BitArray possibility = new BitArray(count); int bestItemsCost = 0; while (true) { for (int i = 0; i < count; i++) { //NEXT BIT WILL BE INVERTED bool next = !possibility[i]; possibility[i] = next; //IF NEW VALUE IS TRUE INSERT ITEM - IF FALSE REMOVE IT if (next) { bag.InsertItem(items[i]); } else { bag.RemoveItem(items[i]); } //ONE IS SET - END if (next) { break; } } if (bag.IsEmpty()) { break; } if (bag.AcceptableWeight()) { int itemsCost = bag.ItemsCost(); if (itemsCost > bestItemsCost) { bestItemsCost = itemsCost; } } } return(bestItemsCost); }
public int Solve(KnapsackProblemModel problem) { List <Item> items = problem.Items.ToList(); items.Sort(Item.CostToWeightRatioComparerDescending); Bag bag = new Bag(problem.BagCapacity); foreach (Item t in items) { bag.InsertItem(t); if (!bag.AcceptableWeight()) { bag.RemoveItem(t); } } return(bag.ItemsCost()); }
public int RecursiveSolver(Bag bag, List <Item> items, int bestKnown) { if (items.Count > 0) { int bestItemsCost = bestKnown; List <Item> recList = new List <Item>(items); recList.RemoveAt(0); int sum = recList.Sum(item => item.Cost) + bag.ItemsCost(); if (sum >= bestKnown) { bestItemsCost = RecursiveSolver(bag, recList, bestKnown); } bag.InsertItem(items[0]); if (bag.AcceptableWeight()) { int itemsCost = bag.ItemsCost(); if (itemsCost > bestItemsCost) { bestItemsCost = itemsCost; } recList = new List <Item>(items); recList.Remove(items[0]); sum = recList.Sum(item => item.Cost) + bag.ItemsCost(); if (sum >= bestItemsCost) { bestItemsCost = RecursiveSolver(bag, recList, bestItemsCost); } } bag.RemoveItem(items[0]); return(bestItemsCost); } return(bestKnown); }