Skip to content

Commit 4c3f4d9

Browse files
authored
Create 贪心算法.html
1 parent 60bdd18 commit 4c3f4d9

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

贪心算法.html

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
function greedy(values, weights, capacity){
2+
var returnValue = 0
3+
var remainCapacity = capacity
4+
var sortArray = []
5+
values.map((cur, index) =>{
6+
sortArray.push({
7+
'value': values[index],
8+
'weight': weights[index],
9+
'ratio': values[index]/weights[index]
10+
})
11+
})
12+
sortArray.sort(function(a, b){
13+
return b.ratio > a.ratio
14+
})
15+
console.log(sortArray)
16+
sortArray.map((cur,index) => {
17+
var num = parseInt(remainCapacity/cur.weight)
18+
console.log(num)
19+
remainCapacity -= num*cur.weight
20+
returnValue += num*cur.value
21+
})
22+
return returnValue
23+
}
24+
var items = ['A','B','C','D']
25+
var values = [50,220,60,60]
26+
var weights = [5,20,10,12]
27+
var capacity = 32 //背包容积
28+
greedy(values, weights, capacity) // 320

0 commit comments

Comments
 (0)