SoFunction
Updated on 2025-02-28

Example of JS solving backpack problem based on greedy algorithm

This article describes the example of JS solving backpack problem based on greedy algorithm. Share it for your reference, as follows:

Greedy Algorithm:When solving problems, always making what seems to be the best choice at the moment. In other words, without considering the overall optimality, what he has made is only a local optimal solution in a sense.

The process of finding the optimal solution is to obtain the current optimal solution

Some backpack problems:The total maximum value of a fixed volume backpack that can be placed in an item

Item A B C D
Price 50 220 60 60
Size 5 20 10 12
Ratio 10 11 6 5

Put as many items as possible in descending order

function greedy(values, weights, capacity){
  var returnValue = 0
  var remainCapacity = capacity
  var sortArray = []
  ((cur, index) =>{
    ({
      'value': values[index],
      'weight': weights[index],
      'ratio': values[index]/weights[index]
    })
  })
  (function(a, b){
    return  > 
  })
  (sortArray)
  ((cur,index) => {
    var num = parseInt(remainCapacity/)
    (num)
    remainCapacity -= num*
    returnValue += num*
  })
  return returnValue
}
var items = ['A','B','C','D']
var values = [50,220,60,60]
var weights = [5,20,10,12]
var capacity = 32 //Backpack capacitygreedy(values, weights, capacity) // 320

For more information about JavaScript, readers who are interested in reading this site's special topic:Summary of JavaScript data structure and algorithm techniques》、《Summary of JavaScript mathematical operations usage》、《Summary of JavaScript sorting algorithm》、《JavaScript traversal algorithm and skills summary》、《Summary of JavaScript search algorithm skills"and"Summary of JavaScript Errors and Debugging Skills

I hope this article will be helpful to everyone's JavaScript programming.