c# - Multiknapsack algorithm - out of collection while trying to remove object -
i've encountered problem while working on multiknapsack solver. program working on 1 knapsack when comes multiple knaps there problems.
problem: items aren't removed collection. know need this, because second knapsack iterating again through same objects - maximized val same...
private void knapsack() { list<plecak> descendingkanps = _plecaklist.orderbydescending(o => o.w).tolist(); // list of configured kanpsacks in descending order list<produkt> descendingproducts = _produktlist.orderbydescending(o => o.cena).tolist(); // list of products pack in descending order int n = descendingproducts.count; //number of items in product list double maxval = 0; // accumulated value of 1 knapsack foreach (plecak p in descendingkanps) // every knapsack... { double[,] v = new double[n + 1, (int)p.w + 1]; //array stores best option (the value of item) (int c = 0; c <= p.w; c++) //since 0-1 mkp problem initialize whole array zeroes { v[0, c] = 0; } (int r = 0; r <= n; r++) { v[r, 0] = 0; } (int = 1; <= n; i++) // constraint of items count { (int wt = 1; wt <= p.w; wt++) //the constraint of weight { if (descendingproducts[i - 1].waga < wt + 1) // if weight of product less constraint, can added... v[i, wt] = math.max(descendingproducts[i - 1].cena + v[i - 1, wt - descendingproducts[i - 1].waga], v[i - 1, wt]); // find best solution , add value value array, comapre value value form previous row else v[i, wt] = v[i - 1, wt]; // keep 0, or last best solution maxval = v[i, wt]; // assign variable } } summary.items.add("maximum val knapsack: " + p.nazwa + " is: " + maxval); // print out value of knapsack } }
this turn answer, question.
in code have this:
for (int c = 0; c <= p.w; c++) //since 0-1 mkp problem initialize whole array zeroes { v[0, c] = 0; } (int r = 0; r <= n; r++) { v[r, 0] = 0; }
you "initialize whole array zeroes". above code array:
0 0 0 0 0 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1
you'll ever reach first column , top row. if places in array should changed 0
, correct approach:
for (int r = 0; r <= n; r++) { (int c = 0; c <= p.w; c++) { v[r, c] = 0; } }
i hope input can of help.
Comments
Post a Comment