相关疑难解决方法(0)

查找JavaScript数组值的所有组合

如何在N个可变长度的JavaScript数组中生成所有值的组合?

假设我有N个JavaScript数组,例如

var first = ['a', 'b', 'c', 'd'];
var second = ['e'];
var third =  ['f', 'g', 'h', 'i', 'j'];
Run Code Online (Sandbox Code Playgroud)

(在这个例子中有三个数组,但它有N个数组用于解决问题.)

我想输出它们的所有值的组合,以产生

aef
aeg
aeh
aei
aej
bef
beg
....
dej
Run Code Online (Sandbox Code Playgroud)

编辑:这是我工作的版本,使用ffriend接受的答案作为基础.

var allArrays = [['a', 'b'], ['c', 'z'], ['d', 'e', 'f']];

 function allPossibleCases(arr) {
  if (arr.length === 0) {
    return [];
  } 
else if (arr.length ===1){
return arr[0];
}
else {
    var result = [];
    var allCasesOfRest = allPossibleCases(arr.slice(1));  // recur with the rest of array
    for (var …
Run Code Online (Sandbox Code Playgroud)

javascript algorithm

57
推荐指数
8
解决办法
5万
查看次数

如何在JavaScript中查找集合的所有子集?

我需要获取数组的所有可能子集.

说我有这个:

[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

我怎么得到这个?

[], [1], [2], [1, 2], [2, 3], [1, 3], [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

我对所有子集感兴趣.有关特定长度的子集,请参阅以下问题:

  • 大小为n的子集找到:1,2
  • 查找大小> 1:1的子集

javascript subset powerset

29
推荐指数
6
解决办法
1万
查看次数

标签 统计

javascript ×2

algorithm ×1

powerset ×1

subset ×1