Created
June 20, 2013 06:34
-
-
Save jremmen/5820688 to your computer and use it in GitHub Desktop.
js:knapsack object, returns optimal solution in total value, total weight, items selected, and a binary selection process
This file contains 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 Knapsack = function(o) { | |
this.values = o.values; | |
this.weights = o.weights; | |
this.capacity = o.capacity; | |
this.createSolutionTable = function () { | |
this.table = this.initializeMatrix(); | |
for(i = 1; i <= this.values.length; i++) { | |
for(k = 0; k < this.capacity; k++) { | |
if(k - this.weights[i - 1] >= 0) { | |
this.table[i][k] = Math.max(this.table[i - 1][k], this.values[i - 1] + this.table[i - 1][k - this.weights[i - 1]]); | |
} else { | |
this.table[i][k] = this.table[i - 1][k]; | |
} | |
} | |
} | |
return this.table; | |
}; | |
this.getOptimalSolution = function() { | |
var result = []; | |
for(i = this.table.length - 1, k = this.table[0].length - 1; k >= 0 && i > 0; i--) { | |
if(this.table[i][k] !== this.table[i - 1][k]) { | |
result.push({ | |
index: i, | |
value: this.values[i - 1], | |
weight: this.weights[i - 1] | |
}); | |
k -= this.weights[i - 1]; | |
} | |
} | |
return result.reverse(); | |
}; | |
this.getOptimalSolutionBinary = function() { | |
var result = []; | |
for(i = this.table.length - 1, k = this.table[0].length - 1; k >= 0 && i > 0; i--) { | |
if(this.table[i][k] !== this.table[i - 1][k]) { | |
result.push(1); | |
k -= this.weights[i - 1]; | |
} else { | |
result.push(0); | |
} | |
} | |
return result.reverse().toString().replace(/,/g, ' '); | |
} | |
this.initializeMatrix = function() { | |
var matrix = []; | |
for(i = 0; i < this.values.length + 1; i++) { | |
matrix[i] = []; | |
for(k = 0; k < this.capacity; k++) { | |
matrix[i][k] = 0; | |
} | |
} | |
return matrix; | |
}; | |
this.getOptimalTotalWeight = function() { | |
return this.getOptimalSolution().reduce(function(x, y) { return { weight: x.weight + y.weight } }); | |
} | |
this.getOptimalTotalValue = function() { | |
return this.getOptimalSolution().reduce(function(x, y) { return { value: x.value + y.value } }); | |
} | |
this.table = this.createSolutionTable(); | |
} | |
var options = { | |
values: [8, 10, 15, 4, 12, 3], | |
weights: [4, 5, 8, 3, 6, 5], | |
capacity: 19 | |
}; | |
sack = new Knapsack(options); | |
results = { | |
totalValue: sack.getOptimalTotalValue(), | |
totalWeight: sack.getOptimalTotalWeight(), | |
selectedItems: sack.getOptimalSolution(), | |
binaryResult: sack.getOptimalSolutionBinary() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment