Javascript 中的 Itertools.combinations

2023-11-26

JavaScript 中是否有类似于 Python 的 itertools 的库?我对排列和组合特别感兴趣。

我没有使用 Node.js。

我想做这样的事情:

array = ['a', 'b', 'c', 'd'];

//return non-duplicate combinations of length 2
['a', 'b']
['a', 'c']
['a', 'd']
['b', 'c']
['b', 'd']
['c', 'd']

谢谢! :)


您可以使用递归方法来获取具有指定大小的给定数组的排列。

function getPermutations(array, size) {

    function p(t, i) {
        if (t.length === size) {
            result.push(t);
            return;
        }
        if (i + 1 > array.length) {
            return;
        }
        p(t.concat(array[i]), i + 1);
        p(t, i + 1);
    }

    var result = [];
    p([], 0);
    return result;
}

var array = ['a', 'b', 'c', 'd'];

console.log(getPermutations(array, 2));
.as-console-wrapper { max-height: 100% !important; top: 0; }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Javascript 中的 Itertools.combinations 的相关文章

随机推荐