【问题标题】:How to get the best combination of numbers from the array of numbers that are closest to the number x如何从最接近数字 x 的数字数组中获得最佳数字组合
【发布时间】:2026-02-08 06:10:02
【问题描述】:

我需要从数组numbers 中获得最接近数字max 的数字组合。 (数组numbers的加法是允许的)

var numbers = [2, 5, 3, 7, 9, 20, 54, 89, 10]; // some numbers in array
var max = 10; // the highest possible number we want to get from array
var highest = []; 

在这种情况下,输出应该是(3, 7) or (2, 5, 3) or (10),输出不应该是9

我已经这样做了,但这不是我想要的。

var possibles = numbers.filter(number => number <= max);
highest.push(Math.max(...possibles));
possibles.sort((a,b) => b - a);
possibles.forEach(number =>{
  if( (max - highest[0]) <= number){
     highest.push(Math.max(...possibles));
  }
});

这种情况下的输出是 9,这不是可能的最大数字。

【问题讨论】:

  • 还请提及您到目前为止所做的尝试
  • 为什么不希望[10] 也作为结果?
  • 有,忘记加了

标签: javascript arrays


【解决方案1】:

您可以采用递归方法,通过使用一些方法来最小化数据和迭代。

首先需要一个变量来保持临时数组right的所有值的实际最小总和。

另一个函数检查结果数组中是否已经存在具有相同值的数组。

最后iter 执行一些退出检查或将right 添加到result,最后通过使用实际值或不使用实际值来对自身进行调用。

结果集包含具有最大可能总和的所有可能结果。

function getMax(values, max) {
    const
        includes = (arrays, array) => arrays.some(a => a.join() === array.join()),
        iter = ([value, ...left], right = [], sum = 0) => {
            ++count;
            if (sum > max) return;
            if (sum > min) {
                result = [right];
                min = sum;
            } else if (sum === min && !includes(result, right)) {
                result.push(right);
            }
            if (sum === max || value === undefined) return;

            iter(left, [...right, value], sum + value);
            iter(left, [...right], sum);
        };

    let min = 0,
        count = 0,
        result = [];

    iter(values.filter(v => v <= max).sort((a, b) => b - a));
    console.log('iterations', count);
    return result;
}

getMax([2, 5, 3, 7, 9, 20, 54, 89, 10], 10).map(a => console.log(...a));
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 谢谢,这对我帮助很大,但我有一个问题。如果我只需要返回这些数字的 1 个最高可能组合(我需要让它更快),我应该改变什么?
  • 你仍然需要迭代到最后,因为你事先并不知道哪个组合得到最大值。
  • 啊,好吧。所以可能没有更快的方法吧?
  • 我添加了一些更改,现在10 也是一个有效结果,直到您希望结果数组中至少有两个项目。通过降序排序,迭代次数最少。你可以玩排序,看看数数。