private bool CanAddItemToAllSacks(int k, int j) { if (k > Capacities.Min()) { return(false); } for (int i = 0; i < NumOfknapsacks; i++) { if (Items[j - 1].Constrains[i] > k) { return(false); } } return(true); }
public void run_algorithm(string problem) { ReadDataFromFile(problem); BuildItemsList(false); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); var max = Capacities.Min(); int indexMax = -1; for (int i = 0; i < Capacities.Count; i++) { if (max <= Capacities[i]) { max = Capacities[i]; indexMax = i; } } int[,] table = new int[Capacities[indexMax] + 1, NumOfItems + 1]; for (int j = 1; j <= NumOfItems; j++) { for (int k = 0; k <= Capacities[indexMax]; k++) { bool result = CanAddItemToAllSacks(k, j); if (result == true) { var previousResult = table[k, j - 1]; var plusItem = Items[j - 1].Weight + table[k - Items[j - 1].Constrains[indexMax], j - 1]; table[k, j] = (int)Math.Max(previousResult, plusItem); } else { table[k, j] = table[k, j - 1]; } } } stopWatch.Stop(); double totalTicks = (stopWatch.ElapsedTicks / (double)Stopwatch.Frequency) * 1000; var best = table.Cast <int>().Max(); for (int j = 0; j <= Capacities[indexMax]; j++) { for (int i = 0; i <= NumOfItems; i++) { Console.Write(table[j, i] + " "); } Console.WriteLine(" "); } Console.WriteLine("Best Value:" + best); print_result_details(); int row = Capacities[indexMax]; if (table[row, Items.Count] == 0) { for (int i = Capacities[indexMax] - 1; i > 0; i--) { if (table[i, Items.Count] != 0) { row = i; break; } } } print_chosen_items(table, indexMax, row); Console.WriteLine("Total Ticks " + (long)totalTicks); }