Created
January 4, 2017 16:56
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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))); | |
} | |
} |
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
This function uses my previous gist to analyse the content of a given knapsack.