Skip to content

Instantly share code, notes, and snippets.

@DiesIrae
Forked from sam-roth/cartprod.js
Last active August 20, 2020 08:42
Show Gist options
  • Save DiesIrae/7ea457d6c81a119f656cd5384ceaea84 to your computer and use it in GitHub Desktop.
Save DiesIrae/7ea457d6c81a119f656cd5384ceaea84 to your computer and use it in GitHub Desktop.
Google Sheets Function for Cartesian Products
// Usually, you'll want to transpose the input (`CARTESIAN_PRODUCT(TRANSPOSE(X1:Y2))`)
function CARTESIAN_PRODUCT(args) {
if (args.length === 0) {
return [];
}
var first = args[0].filter(function (x) { return x !== ""; });
if (args.length === 1) {
return first;
}
var rest = args.slice(1);
var restProduct = CARTESIAN_PRODUCT(rest);
var result = [];
first.forEach(function (f) {
restProduct.forEach(function (r) {
result.push([f].concat(r));
});
});
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment