Home Backend Development PHP Tutorial JS implements dynamic programming knapsack algorithm

JS implements dynamic programming knapsack algorithm

Mar 22, 2018 pm 03:28 PM
javascript dynamic programming algorithm

During the interview, I encountered a question about the backpack algorithm. It is slightly different from the traditional backpack. Given the capacity of the backpack and the weight of various items, the total mass of the items placed is required to be as close as possible to the capacity of the backpack and smaller than the backpack. capacity and the minimum number of items placed. This article mainly shares with you the dynamic programming backpack algorithm implemented in JS. I hope it can help you. function Backpack() {

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

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

    var totalWeight;//背包的总质量

    var goodsList = [];//可供选择的物品列表

    var bestMethodList = []//最优解的物品列表

    //设置背包总重量

    this.setTotalWeight = function(t) {

        totalWeight = t

    }

    //加物品

    this.addThing = function(goods) {

        goodsList.push(goods)

    }

    //减物品

    this.removeThing = function(goods) {

        var index = null

        goodsList.forEach(function(everyGoods,i){

            if(everyGoods === goods){

                index = i

            }

        })

        if(index){

            goodsList.splice(index,1)

        }

        else{

            return false

        }

    }

    //计算最优解背包的重量

    this.count = function() {

        return getListWeight(bestMethodList)

    }

    //传入物品列表,返回该列表所有物品总质量

    function getListWeight(list) {

        var weight = 0

        list.forEach(function(everyGoods, i) {

            weight += everyGoods.weight

        })

        return weight

    }

    //满足尽可能接近背包重量且放入物品最少的方法

    this.getBestMethod = function() {

        var arr = []

        //这里只需要两个参数 设置的重质量totalWeight和可供选择的物品goodsList

        goodsList.forEach(function(everyGoods, i) {

            arr[i] = []//创建一个二维数组,放对应位置的最优解

            for (let j = 0; j < totalWeight; j++) {

                if(j+1 > everyGoods.weight) {

                    var newArr = [everyGoods]

                    if(i > 0){

                        var overWeight = j - everyGoods.weight

                        arr[i - 1][overWeight] ? newArr = newArr.concat(arr[i-1][overWeight]) : null

                        if(getListWeight(newArr) < getListWeight(arr[i-1][j])) {

                            newArr = arr[i-1][j]

                        }

                        else if(getListWeight(newArr) === getListWeight(arr[i - 1][j]) && arr[i-1][j].length < newArr.length){

                            newArr = arr[i-1][j]

                        }

                    }

                    arr[i][j] = newArr

                }

                else{

                    if(i === 0){

                        arr[i][j] = null

                    }

                    else{

                        arr[i][j] = arr[i-1][j]

                    }

                }

            }

        })

        return bestMethodList = arr[goodsList.length-1][totalWeight-1]

    }

}

//测试

var myBag = new Backpack()

myBag.setTotalWeight(10)

myBag.addThing({name:'apple',weight:1})

myBag.addThing({ name: 'tomato', weight:3 })

myBag.addThing({ name: 'ball', weight: 5 })

myBag.addThing({ name: 'eggplant', weight: 4 })

console.log(myBag.getBestMethod())//最优解的数组

console.log(myBag.count())//最优解的质量

Copy after login

The core is to create a two-dimensional array to save the local optimal solution, and then slowly deduce it, and finally obtain the final optimal solution.

                                                                                                                                    using using using using               out out through off ’s ’ through out out through out outmb together out right out out out out out out outmb out out out out out out out out out out out out , -- 1-. The quality of the items in the line

2. New arr = arr[i-1][Remaining mass of backpack] + current item (use concat)

3. New arr and column j of the previous row Comparison of arr (if the initial conditions are different, you only need to change here)

4. Obtain arr

Related recommendations:

JavaScript Advanced Algorithm Dynamic programming example analysis

php algorithm learning dynamic programming

PHP dynamic programming to solve the 0-1 knapsack problem example analysis_PHP tutorial

The above is the detailed content of JS implements dynamic programming knapsack algorithm. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CLIP-BEVFormer: Explicitly supervise the BEVFormer structure to improve long-tail detection performance CLIP-BEVFormer: Explicitly supervise the BEVFormer structure to improve long-tail detection performance Mar 26, 2024 pm 12:41 PM

CLIP-BEVFormer: Explicitly supervise the BEVFormer structure to improve long-tail detection performance

Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Jun 03, 2024 pm 01:25 PM

Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions

Explore the underlying principles and algorithm selection of the C++sort function Explore the underlying principles and algorithm selection of the C++sort function Apr 02, 2024 pm 05:36 PM

Explore the underlying principles and algorithm selection of the C++sort function

Improved detection algorithm: for target detection in high-resolution optical remote sensing images Improved detection algorithm: for target detection in high-resolution optical remote sensing images Jun 06, 2024 pm 12:33 PM

Improved detection algorithm: for target detection in high-resolution optical remote sensing images

Can artificial intelligence predict crime? Explore CrimeGPT's capabilities Can artificial intelligence predict crime? Explore CrimeGPT's capabilities Mar 22, 2024 pm 10:10 PM

Can artificial intelligence predict crime? Explore CrimeGPT's capabilities

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

Simple JavaScript Tutorial: How to Get HTTP Status Code

PHP algorithm analysis: efficient method to find missing numbers in an array PHP algorithm analysis: efficient method to find missing numbers in an array Mar 02, 2024 am 08:39 AM

PHP algorithm analysis: efficient method to find missing numbers in an array

Application of algorithms in the construction of 58 portrait platform Application of algorithms in the construction of 58 portrait platform May 09, 2024 am 09:01 AM

Application of algorithms in the construction of 58 portrait platform

See all articles