JS solves the backpack problem based on greedy algorithm

The instance of this paper tells the JS based on the greedy algorithm to solve the problem of backpack. Share to everyone for reference, as follows:

Greedy algorithm: When solving the problem, always make the best choice in the current appearance. That is, it is not considered by the overall optimal, and what he makes is only a local optimal solution in a sense.

Find the process of optimal solution is to get the current best solution

partial backpack problem: fixed volume backpack can be placed in the total maximum value of the item

Item ABCD
price 502206060
size 5,201,012
ratio 101 165

multi-scale descending into the article as possible

  Function Greedy (VARUES, Weights, Capacity) {var ReturnValue = 0 Var RemainCapacity = Capacity Var SortArray = [] VALUES.MAP ((Cur, Index) => {sORTARRAY.PUSH ({ 'Value': Values ​​[Index], 'Weight': Weights [Index], 'Ratio': Values ​​[Index] / Weights [Index]}) SortArray.Sort (Function (A, B) {Return B.ratio > a.ratio}) console.log (sORTARRAY) SortArray.map ((cur, index) => {var Num = parseint (RemainCapacity / Cur.weigHT) Console.log (NUM) RemainCapacity - = Num * Cur.Weight ReturnValue + = Num * Cur.Value}) Return ReturnValue} var Items = ['A', 'B', 'C', 'D'] VAR VALUES = [50, 220, 60, 60] var weights = [5, 20, 10, 12] var capacity = 32 // Backpacco volume Greedy (Values, Weights, Capacity) // 320  

More about JavaScript-related content, readers, interested in this site: “JavaScript Data Structure and Algorithm Skill Summary”, “JavaScript Mathematical Computing Summary”, “JavaScript Sort Algorithm Summary”, “JavaScript Travel Algorithm Summary with skills “,” JavaScript Find Algorithm Skills “and” JavaScript Error and Debugging Skill Summary “

I hope this article will help you JavaScript programming.

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment