Finding closest sum of numbers to a given number

后端 未结 5 1722
我在风中等你
我在风中等你 2021-01-25 09:11

Say I have a list [1,2,3,4,5,6,7] and I would like to find the closest sum of numbers to a given number. Sorry for the crappy explanation but here\'s an example:

Say I h

5条回答
  •  广开言路
    2021-01-25 09:26

    This proposal generates all possible combinations, collects them in an object which takes the sum as key and filters then the closest sum to the given value.

    function getSum(array, sum) {
        function add(a, b) { return a + b; }
    
        function c(left, right) {
            var s = right.reduce(add, 0);
            if (s > sum) {
                return;
            }
            if (!result.length || s === result[0].reduce(add, 0)) {
                result.push(right);
            } else if (s > result[0].reduce(add, 0)) {
                result = [right];
            }
            left.forEach(function (a, i) {
                var x = left.slice();
                x.splice(i);
                c(left.slice(0, i), [a].concat(right));
            });
        }
    
        var result = [];
        c(array, [], 0);
        return result;
    }
    
    function print(o) {
        document.write('
    ' + JSON.stringify(o, 0, 4) + '
    '); } print(getSum([1, 2, 3, 4, 5, 6, 7], 10)); print(getSum([1, 2, 3, 4, 5, 6, 7], 14)); print(getSum([1, 2, 3, 4, 5, 6, 7], 19));

提交回复
热议问题