Example #1
0
        static void Main()
        {
            var knapsack = new Knapsack(16);
            var items    = new Item[] {
                new Item {
                    Price = 25, Weight = 10
                },
                new Item {
                    Price = 12, Weight = 8
                },
                new Item {
                    Price = 16, Weight = 8
                }
            };

            CollectItems(items, knapsack);
            Console.WriteLine(knapsack.ToString());
        }
Example #2
0
        static void CollectItems(IList <Item> items, Knapsack knapsack)
        {
            items = items.OrderByDescending(x => x.ValuableRatio()).ToList();
            var index = 0;

            while (knapsack.Capacity > 0 && index < items.Count)
            {
                var currItem = items[index];

                //how many I can take depending on remaining knapsack capacity
                var weigthToTaken = Math.Min(knapsack.Capacity, currItem.Weight);

                //calculate needed percentage of item
                var percentQuantity = weigthToTaken / currItem.Weight;

                //add item in knapsack
                knapsack.AddItem(currItem, percentQuantity);

                //recalculate remaining free capacity
                knapsack.Capacity -= weigthToTaken;

                index++;
            }
        }