查找多维数组中可能组合的整数值

时间:2017-06-02 23:08:52

标签: javascript arrays multidimensional-array

我有这个多维数组。

var multiArray = [
   ['steak tips', 'burgers'],
   ['ice cream', 'cake', 'cookies'],
   ['corona', 'jack daniels']
]

我正在寻找能够以某种方式计算以下用例的可能组合总量的函数:

从第一个嵌套数组中打印一个单词,从第二个嵌套数组中打印一个单词,从第三个嵌套数组中打印一个单词。

我只是希望得到一个整数结果,告诉我有多少可能的解决方案。它不必实际将所有这些可能的组合打印到屏幕上,或类似的东西。

1 个答案:

答案 0 :(得分:0)

这个简单的问题基本上要求任意数量的数组长度的产品,使用Array.reduce方法有一个优雅的通用解决方案:

function numCombinations(...arrays) {
  return arrays.reduce((prod, array) => prod * array.length, 1);
}

// Examples:
console.log(numCombinations([1, 2], [3, 4, 5], [6])); // 6
console.log(numCombinations([1, 2]));                 // 2
console.log(numCombinations([1], []));                // 0

我们需要指定1的初始值,它是乘法的标识元素。

附录:替代的示例性解决方案:

// Expects three arrays, returns the product of their lengths:
function numCombinations1(array1, array2, array3) {
  return array1.length * array2.length * array3.length;
}

console.log(numCombinations1([1, 2], [3, 4, 5], [6])); // 6

// Expects one array containing the three arrays:
function numCombinations2(arrays) {
  return arrays[0].length * arrays[1].length * arrays[2].length;
}

console.log(numCombinations2([[1, 2], [3, 4, 5], [6]])); // 6

// Expects one array containing a variable number of arrays:
function numCombinations3(arrays) {
  var product = 1;
  for (var i = 0; i < arrays.length; i++) {
    product = product * arrays[i].length;
  }
  return product;
}

console.log(numCombinations3([[1, 2], [3, 4, 5], [6]])); // 6

// Replaced traditional for-loop with simpler for-of loop:
function numCombinations4(arrays) {
  var product = 1;
  for (var array of arrays) {
    product *= array.length;
  }
  return product;
}

console.log(numCombinations4([[1, 2], [3, 4, 5], [6]])); // 6

// Expects a variable number of array arguments using rest parasmeter syntax (...):
function numCombinations5(...arrays) {
  var product = 1;
  for (var array of arrays) {
    product *= array.length;
  }
  return product;
}

console.log(numCombinations5([1, 2], [3, 4, 5], [6])); // 6

// Replaced for-of loop with Array.reduce:
function numCombinations6(...arrays) {
  return arrays.reduce(function (product, array) {
    return product * array.length;
  }, 1);
}

console.log(numCombinations6([1, 2], [3, 4, 5], [6])); // 6

// Replaced Array.reduce callback function with shorter arrow function:
function numCombinations7(...arrays) {
  return arrays.reduce((product, array) => product * array.length, 1);
}

console.log(numCombinations7([1, 2], [3, 4, 5], [6])); // 6