Skip to content

Instantly share code, notes, and snippets.

@Muzietto
Created January 4, 2017 16:56
Show Gist options
  • Save Muzietto/4398829bbb0ca1717f800d74d79299ef to your computer and use it in GitHub Desktop.
Save Muzietto/4398829bbb0ca1717f800d74d79299ef to your computer and use it in GitHub Desktop.
Knapsack 0/1 - reverse function that deducts the knapsack content starting from its total value.
function knapsackContents(items, maxWeight) {
items = items.sort((a,b)=>a.weight-b.weight);
var knapsacks = knapsack01(maxWeight, items, true);
var result = [];
return contentsHelper(knapsacks, items);
function contentsHelper(matrix, items) {
var column = matrix[matrix.length-1]
var numItems = items.length;
if (numItems === 0) return [];
var lastBoxInKnapsack = (numItems === 1) ? (column[1] !== 0) : (column[numItems-1] !== column[numItems-2]);
var boxedResult = lastBoxInKnapsack ? [items[numItems-1]] : [];
var lastBoxWeight = lastBoxInKnapsack ? items[numItems-1].weight : 0;
return boxedResult.concat(contentsHelper(matrix.slice(0, matrix.length-lastBoxWeight), items.slice(0, numItems-1)));
}
}
@Muzietto
Copy link
Author

Muzietto commented Jan 4, 2017

This function uses my previous gist to analyse the content of a given knapsack.

@Muzietto
Copy link
Author

Muzietto commented Jan 4, 2017

Sample usage: knapsackContents([{value:1,weight:1},{value:4,weight:3},{value:5,weight:4},{value:7,weight:5}], 8);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment