Home > Web Front-end > JS Tutorial > How to Efficiently Generate Cartesian Products from Arrays of Varying Lengths in JavaScript?

How to Efficiently Generate Cartesian Products from Arrays of Varying Lengths in JavaScript?

Susan Sarandon
Release: 2024-11-30 01:52:10
Original
825 people have browsed it

How to Efficiently Generate Cartesian Products from Arrays of Varying Lengths in JavaScript?

Cartesian Product Generation for Varying Arrays in JavaScript

To generate all possible combinations of elements taken from a set of arrays with varying lengths, JavaScript programmers face a unique challenge. Customizing a solution to handle a dynamic number of arrays can be tricky.

A simple and efficient approach is to employ a recursive helper function like the one illustrated below:

function cartesian(...args) {
  var r = [], max = args.length - 1;
  function helper(arr, i) {
    for (var j = 0, l = args[i].length; j < l; j++) {
      var a = arr.slice(0); // clone arr
      a.push(args[i][j]);
      if (i == max) r.push(a);
      else helper(a, i + 1);
    }
  }
  helper([], 0);
  return r;
}
Copy after login

To utilize this function, simply pass your arrays as arguments:

cartesian([0, 1], [0, 1, 2, 3], [0, 1, 2]);
Copy after login

The output will contain all possible combinations of elements from the provided arrays:

[
  [0, 0, 0],
  [0, 0, 1],
  [0, 0, 2],
  [0, 1, 0],
  [0, 1, 1],
  [0, 1, 2],
  [0, 2, 0],
  [0, 2, 1],
  [0, 2, 2],
]
Copy after login

For an array of arrays, adjust the function's signature to function cartesian(args) instead of using rest parameters. This approach allows for handling any number of arrays with varying element counts, providing a flexible solution to this combinatorial problem.

The above is the detailed content of How to Efficiently Generate Cartesian Products from Arrays of Varying Lengths in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template