繁体   English   中英

如何获取特定长度数组的所有组合

[英]How to get all the combinations for an array of a specific length

假设我有这个要使用的字符数组:

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

我想得到这个数组的所有可能组合,比如从24的长度,所以 output 可能看起来像这样

aa
ab
ac
ad
ba
bb
bc
bd
ca
cb
cc
cd
da
db
dc
dd

...等等...

生成器应该能够满足这些条件:

  • 针对 2 种长度之间的所有组合,或允许自己接受任何不同的长度
  • 字母可以重复自己

我不确定从哪里开始,所以一些入门代码会很好。

编辑:

    var characters = ['a','b','c','d'];
    var combinations = [];
    for(var i=2;i<=4;i++) {
        var str = "";
        for(var c of characters) {
            str+=c;
            // 'a' spam
        }
        combinations.push(str);
    };
    console.log( combinations );

我不知道如何迭代字符¯_(ツ)_/¯

它看起来像这样:

ab
abc
abcd

我在您的代码中看到的问题是,对于每个额外的组合长度,您需要一个嵌套循环,即对于长度 2,您需要一个双嵌套迭代,对于长度 3,您需要一个三重嵌套迭代,依此类推。

尝试使用递归实现。 它递归到长度为 1 的基本情况并构建结果集。

 const characters = ["a", "b", "c", "d"]; const combinations = (arr, min = 1, max) => { const combination = (arr, depth) => { if (depth === 1) { return arr; } else { const result = combination(arr, depth - 1).flatMap((val) => arr.map((char) => val + char) ); return arr.concat(result); } }; return combination(arr, max).filter((val) => val.length >= min); }; const result = combinations(characters, 2, 4); console.log(`Combinations: ${result.length}`, result);

这是一个非递归版本; 它最终变得更简单了。

 const characters = ["a", "b", "c", "d"]; const combinations = (arr, min = 1, max) => [...Array(max).keys()].reduce( (result) => arr.concat(result.flatMap((val) => arr.map((char) => val + char))), [] ).filter((val) => val.length >= min); const result = combinations(characters, 2, 4); console.log(`Combinations: ${result.length}`, result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM