• Как найти баланс чисел в массиве?

    jonstonrich
    @jonstonrich Автор вопроса
    Выкладываю свой вариант перебора:

    class Player{
        constructor(elo){
            this.elo = elo;
        }
    }
    
    let reducer = (accumulator, value) => accumulator + value.elo;
    
    let players = [
        new Player(3000),
        new Player(700),
        new Player(750),
        new Player(1250),
        new Player(1000),
        new Player(1200),
        new Player(1350),
        new Player(1400),
        new Player(1500),
        new Player(745)
    ];
    
    let combinations = (function () {
    
        function combinations(arr, k, start, idx, current, callback) {
            if (idx === k)
                return callback(current);
    
            for(let i = start; i < arr.length; i++) {
                current[idx] = arr[i];
                combinations(arr, k, i + 1, idx + 1, current, callback);
            }
        }
    
        return function (arr, k, callback) {
            combinations(arr, k, 0, 0, [], callback);
        };
    }());
    
    let minimal = [];
    
    combinations(players, players.length / 2, (combo) => {
    
        let t1 = [...combo],
            t2 = players.filter(p => t1.indexOf(p) < 0),
            w1 = t1.reduce(reducer, 0),
            w2 = t2.reduce(reducer, 0),
            diff = Math.abs(w1 - w2);
    
        if( ! minimal.length)
            minimal = [t1, t2, diff];
    
        if(minimal[2] > diff)
            minimal = [t1, t2, diff];
    });
    
    console.log(minimal);
    Ответ написан