Skip to content

Commit aef7f92

Browse files
committed
knapSack greedy
1 parent fd0f1d3 commit aef7f92

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

chapter11/09-MatrixChainMultiplicationDP.html chapter11/07-KnapSackProblemGreedy.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,6 @@
55
<title></title>
66
</head>
77
<body>
8-
8+
<script src="07-KnapSackProblemGreedy.js"></script>
99
</body>
1010
</html>

chapter11/07-KnapSackProblemGreedy.js

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
function knapSack(capacity, values, weights) {
2+
var n = values.length,
3+
load = 0,
4+
i = 0,
5+
val = 0;
6+
7+
for (i=0; i<n && load < capacity; i++) {
8+
9+
if (weights[i] <= (capacity-load)) {
10+
val += values[i];
11+
load += weights[i];
12+
console.log('using item ' + (i+1) + ' for the solution');
13+
14+
} else {
15+
var r = (capacity-load)/weights[i];
16+
val += r * values[i];
17+
load += weights[i];
18+
console.log('using ratio of ' + r + ' for item ' + (i+1) + ' for the solution');
19+
}
20+
}
21+
return val;
22+
}
23+
24+
var values = [3,4,5],
25+
weights = [2,3,4],
26+
capacity = 6,
27+
n = values.length;
28+
console.log(knapSack(capacity, values, weights));

0 commit comments

Comments
 (0)