Created
June 27, 2017 17:55
-
-
Save t0mdicks0n/90368471f11535aa6bf8f9a8644c3089 to your computer and use it in GitHub Desktop.
Knapsack with dynamic programming
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
var testInput = [ | |
[1, 1], | |
[3, 4], | |
[4, 5], | |
[5, 7] | |
]; | |
var knapsackOpt = function (arr) { | |
var matrix = []; | |
// Loop over the given elements | |
for (let i = 0; i < arr.length; i++) { | |
matrix[i] = []; | |
// For each element, loop from 0 to the value of the heaviest item | |
for (let j = 0; j <= arr[arr.length - 1][1]; j++) { | |
// For each of these iteration check what the best we can do is | |
var option1; | |
if (arr[i][0] === j) { | |
option1 = arr[i][1]; | |
} else if (arr[i][0] > j) { | |
option1 = 0; | |
} else { | |
// The base that we can afford | |
option1 = arr[i][1]; | |
// Calculate how much space we have left | |
var rest = j - arr[i][0]; | |
option1 += matrix[i - 1] && matrix[i - 1][rest] ? matrix[i - 1][rest] : 0; | |
} | |
// Find out what option2 is | |
var option2 = matrix[i - 1] && matrix[i - 1][j] ? matrix[i - 1][j] : 0; | |
// Write the bigger of the two options to the matrix | |
matrix[i][j] = Math.max(option1, option2); | |
} | |
} | |
// Return the very last element in the matrix | |
return matrix[matrix.length - 1][matrix[matrix.length - 1].length - 1]; | |
}; | |
// Tests | |
var testRes = knapsackOpt(testInput); | |
console.log('expect output of testInput to be 9 ', testRes === 9); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment