-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnapsack Problem
More file actions
34 lines (28 loc) · 850 Bytes
/
Copy pathKnapsack Problem
File metadata and controls
34 lines (28 loc) · 850 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//this is an ongoing solution to the classic knapsack problem -- not yet finished
function knapsack(arr, maxweight){
var maxtotal = 0;
for(var i = 0; i < arr.length; i++){
var total = (_knapsack(arr, i, 0, maxweight, 0));
if(total > maxtotal) {
maxtotal = total;
}
}
console.log(maxtotal);
}
function _knapsack(arr, indx, curweight, maxweight, value){
if(!arr[indx]){
return value;
}
if (arr[indx].weight <= maxweight-curweight){
curweight += arr[indx].weight;
value += arr[indx].value;
return Math.max(_knapsack(arr, indx + 1, curweight, maxweight, value), _knapsack(arr, indx, curweight, maxweight, value));
}
else{
return value;
}
}
var tosteal = [{"weight": 5, "name": "carrot", "value": 16},
{"weight": 6, "name": "mince", "value": 0},
{"weight": 4, "name": "peach", "value": 15}];
knapsack(tosteal, 9);