Показать сообщение отдельно
  #4 (permalink)  
Старый 29.01.2022, 00:07
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,075

Сообщение от DzonyB
Если нужны мои потуги
аналогично что - то из разряда ... слеплено из ... )))

<script>
        function permute(arr) {
            let l = arr.length,
                used = Array(l),
                data = Array(l);
            return function* backtracking(pos) {
                if (pos == l) yield data.slice();
                else
                    for (let i = 0; i < l; ++i)
                        if (!used[i]) {
                            used[i] = true;
                            data[pos] = arr[i];
                            yield* backtracking(pos + 1);
                            used[i] = false;
                        }
            }(0);
        }
        function sumArray(arr) {
            return arr.reduce((a, b) => a + b, 0)
        }
        function permutDevide(arr, n) {
            arr.sort((a, b) => a - b);
            const gen = permute(arr);
            let current = gen.next();
            let max = [],
                k = 0,
                sum = sumArray(arr);
            while (!current.done) {
                let temp = [],
                    num = 0,
                    d = 0,
                    s = sum;
                const res = [temp];
                for (const elem of current.value) {
                if(num + elem > n && s != elem || (elem > n)) {
                if(num == n) d++;
                temp = [elem];
                res.push(temp);
                num = elem;
                }
                else {
                 temp.push(elem);
                 num += elem;
                }

                s -= elem;
                }
                if(num == n) d++;
                if (!temp.length) res.pop();
                if (d >= sum / n - 1.5) return res;
                if (!max.length) max = res;
                if (d > k) {
                    max = res;
                    k = d
                };
                current = gen.next();
            }
            return max
        }
        const test = [
            [1, 2, 4, 7, 1, 6, 2, 8], [5, 2, 5, 1, 5, 4, 6, 3], [100, 8, 7, 3, 1, 45, 20, 6, 4], [2, 2, 3, 9, 5, 6, 1], [3, 3, 3, 3, 3, 3], [3, 7, 3, 3, 3, 3]
        ];
        for (const arr of test) document.write(`${JSON.stringify(arr)} => ${JSON.stringify(permutDevide(arr, 10))}<br>`)
    </script>
Ответить с цитированием