private static void Main() { Helper.ConsoleMio.Setup(); Helper.ConsoleMio.PrintHeading("Knapsack Problem"); // Order Products by Cost/Weight ratio // Start from the best ratio and move to the worst adding products to the bag IList <Product> products = GetTestProducts(); var stopwatch = new Stopwatch(); stopwatch.Start(); var productsMappedByCost = products .OrderByDescending(p => (double)p.Cost / p.Weight) .ThenBy(p => p.Weight) .GroupBy(p => (double)p.Cost / p.Weight); var myBag = new BagOfProducts(MaxCapacity); FillMaBag(myBag, productsMappedByCost); stopwatch.Stop(); Helper.ConsoleMio.Write("Elapsed: ", ConsoleColor.DarkBlue) .WriteLine(stopwatch.Elapsed.ToString(), ConsoleColor.DarkCyan); PrintBagDetails(myBag); }
private static void PrintBagDetails(BagOfProducts bagOfProducts) { Helper.ConsoleMio.Write("Bag weight: ", ConsoleColor.DarkBlue) .WriteLine(bagOfProducts.BagWeigth.ToString(), ConsoleColor.Blue) .Write("Products cost: ", ConsoleColor.DarkBlue) .WriteLine(bagOfProducts.BagCost.ToString(), ConsoleColor.Blue); while (bagOfProducts.BagWeigth > 0) { Helper.ConsoleMio.WriteLine( bagOfProducts.RemoveLastProduct().Name, ConsoleColor.Blue); } }
private static void FillMaBag( BagOfProducts bag, IEnumerable<IGrouping<double, Product>> productsMap) { foreach (var group in productsMap) { foreach (var product in group) { bag.Add(product); if (bag.BagWeigth == bag.BagWeigthCapacity) { break; } } } }
private static void FillMaBag( BagOfProducts bag, IEnumerable <IGrouping <double, Product> > productsMap) { foreach (var group in productsMap) { foreach (var product in group) { bag.Add(product); if (bag.BagWeigth == bag.BagWeigthCapacity) { break; } } } }
private static void Main() { Helper.ConsoleMio.Setup(); Helper.ConsoleMio.PrintHeading("Knapsack Problem"); // Order Products by Cost/Weight ratio // Start from the best ratio and move to the worst adding products to the bag IList<Product> products = GetTestProducts(); var stopwatch = new Stopwatch(); stopwatch.Start(); var productsMappedByCost = products .OrderByDescending(p => (double)p.Cost / p.Weight) .ThenBy(p => p.Weight) .GroupBy(p => (double)p.Cost / p.Weight); var myBag = new BagOfProducts(MaxCapacity); FillMaBag(myBag, productsMappedByCost); stopwatch.Stop(); Helper.ConsoleMio.Write("Elapsed: ", ConsoleColor.DarkBlue) .WriteLine(stopwatch.Elapsed.ToString(), ConsoleColor.DarkCyan); PrintBagDetails(myBag); }