查找 JavaScript 数组值的所有组合(笛卡尔积) [英] Finding All Combinations (Cartesian product) of JavaScript array values

查看:22
本文介绍了查找 JavaScript 数组值的所有组合(笛卡尔积)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I produce all of the combinations of the values in N number of JavaScript arrays of variable lengths?

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

Let's say I have N number of JavaScript arrays, e.g.

var first = ['a', 'b', 'c', 'd'];
var second = ['e'];
var third =  ['f', 'g', 'h', 'i', 'j'];

(本例中为三个数组,但问题的数组数为 N.)

(Three arrays in this example, but its N number of arrays for the problem.)

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

And I want to output all the combinations of their values, to produce

aef
aeg
aeh
aei
aej
bef
beg
....
dej


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


Here's the version I got working, using ffriend's accepted answer as the basis.

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 c in allCasesOfRest) {
      for (var i = 0; i < arr[0].length; i++) {
        result.push(arr[0][i] + allCasesOfRest[c]);
      }
    }
    return result;
  }

}
var results = allPossibleCases(allArrays);
 //outputs ["acd", "bcd", "azd", "bzd", "ace", "bce", "aze", "bze", "acf", "bcf", "azf", "bzf"]

推荐答案

这不是排列,参见 排列定义 来自维基百科.

This is not permutations, see permutations definitions from Wikipedia.

但是你可以通过递归来实现:

But you can achieve this with recursion:

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

function allPossibleCases(arr) {
  if (arr.length == 1) {
    return arr[0];
  } else {
    var result = [];
    var allCasesOfRest = allPossibleCases(arr.slice(1)); // recur with the rest of array
    for (var i = 0; i < allCasesOfRest.length; i++) {
      for (var j = 0; j < arr[0].length; j++) {
        result.push(arr[0][j] + allCasesOfRest[i]);
      }
    }
    return result;
  }

}

console.log(allPossibleCases(allArrays))

您也可以使用循环来实现,但这会有点棘手,并且需要实现您自己的堆栈模拟.

You can also make it with loops, but it will be a bit tricky and will require implementing your own analogue of stack.

这篇关于查找 JavaScript 数组值的所有组合(笛卡尔积)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆