Created
September 22, 2016 00:07
-
-
Save sam-roth/3a0a89750c58ece4c24ecfb69db701b9 to your computer and use it in GitHub Desktop.
Google Sheets Function for Cartesian Products
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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
Thanks for the formula! I replaced
return x
withreturn x !== ""
in the filter in order to keep explicitely declared falsy values, like "0" or "FALSE"https://gist.github.com/DiesIrae/7ea457d6c81a119f656cd5384ceaea84