遍历所有可能性

时间:2020-04-25 16:58:38

标签: javascript arrays

所以我想做的是遍历数组以创建所有可能的组合。

let array = ['A','B','C','D','E','F'];
let length = 8;

我想以所有可能的数组结尾,每个元素都是8个字符的字符串,如下所示:

let result = ['ABCDEFAB', 'ABCDEFAC', 'ABCDEFAD'];

我无法解决这个问题。配对要容易得多,这-我想不起来

2 个答案:

答案 0 :(得分:0)

这是一种蛮力方法。我正在计算6 ^ 8排列,即1,679,616。仅仅无限制地简单地运行它可能不是一个好主意。 html可以查看结果。并不是您问题的一部分。

jQuery仅与显示有关,因此可以忽略:)

<ul id="thelist">
</ul>
    const a = ['A', 'B', 'C', 'D', 'E', 'F'];
    var tot = 0;

    a.forEach(function (a1) {
        a.forEach(function (a2) {
            a.forEach(function (a3) {
                a.forEach(function (a4) {
                    a.forEach(function (a5) {
                        a.forEach(function (a6) {
                            a.forEach(function (a7) {
                                a.forEach(function (a8) {
                                    if (tot++ < 150) {
                                        $('#thelist').append(`<li>${a1}${a2}${a3}${a4}${a5}${a6}${a7}${a8}</li>`);
                                    }
                                });
                            });
                        });
                    });
                });
            });
        });
    });

答案 1 :(得分:0)

您可以使用Generator function*并使用索引数组,并为每次next()调用更新此数组。

function* generate(symbols, length) {
    let indices = Array.from({ length }, _ => 0),
        index = length - 1,
        j = index;

    while (j >= 0) {
        yield indices.map(i => symbols[i]).join('');
        indices[index]++;
        j = index;
        while (indices[j] >= symbols.length) {
            indices[j] = 0;
            indices[--j]++;
        }
        if (j < index) index = length - 1;
    }
}

console.log([...generate('ABCD', 5)]);
.as-console-wrapper { max-height: 100% !important; top: 0; }