File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments