JS怎么实现求某个数的和的所以组合

img


请教下,couponTypes是种类,couponsNums是数量,能用什么方法能实现:例如:金额9980,用里面的数据算出等于9980的所有组合,没有相等的就取接近9980的



<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        let arr = [9980, 998, 499, 198, 99, 50, 30, 20, 10];
        let arr1 = [1, 1, 5, 7, 13, 5, 15, 13, 11, 46];
        let result = [];
        let combination = []

        for (let i = 0; i < arr.length; i++) {
            for (let j = 0; j < arr1.length; j++) {
                combination.push({
                    arr: arr[i],
                    arr1: arr1[j],
                    value: arr[i] * arr1[j] - 9980
                })

            }
        }

        let minvalue = Math.min.apply(null, combination.map(item => Math.abs(item.value)))
        result = combination.filter(item => Math.abs(item.value) == minvalue)

        console.log(combination, result, '===')







    </script>
</body>

</html>

其实你把couponTypes讲成单价,couponsNums讲成数量,这样更好理解一点

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <script>
      let couponTypes = [9980, 998, 499, 198, 99, 50, 30, 20, 10];
      let couponsNums = [1, 1, 5, 7, 13, 5, 15, 13, 11, 46];

      function getArr(couponTypes, couponsNums, value) {
        let result = [];
        for (let i = 0; i < couponTypes.length; i++) {
          for (let j = 0; j < couponsNums.length; j++) {
            if (couponTypes[i] * couponsNums[j] === value) {
              result.push({
                couponTypes: couponTypes[i],
                couponsNums: couponsNums[j],
                value: value,
              });
            }
          }
        }

        return result;
      }

      console.log("getArr", getArr(couponTypes, couponsNums, 9980));
    </script>
  </body>
</html>

没太理解什么意思

可以是重复的使用吧