-
-
Save leotop/869b70c3f51621e826f398293c8922a2 to your computer and use it in GitHub Desktop.
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
// Cartesian product of arrays | |
// @takes N arrays -- arguments *must* be arrays | |
// @returns an array of X arrays of N elements, X being the product of the input arrays' lengths. | |
function cartesianProduct(...arrays) { | |
function _inner(...args) { | |
if (arguments.length > 1) { | |
let arr2 = args.pop(); // arr of arrs of elems | |
let arr1 = args.pop(); // arr of elems | |
return _inner(...args, | |
arr1.map(e1 => arr2.map(e2 => [e1, ...e2])) | |
.reduce((arr, e) => arr.concat(e), [])); | |
} else { | |
return args[0]; | |
} | |
}; | |
return _inner(...arrays, [[]]); | |
}; | |
// Examples of normal use : | |
cartesianProduct(['A', 'B'], [1, 2, 3]); // [['A',1], ['A',2], ['A',3], ['B',1], ['B',2], ['B',3]] | |
cartesianProduct(['a', 'b'], ['-'], [5, 6]); // [[a','-',5], ['a','-',6], ['b','-',5], ['b','-',6]] | |
cartesianProduct(['a', 'b'], [8, 7, 3], []); // [] | |
// side-cases : | |
cartesianProduct(); // [[]] | |
cartesianProduct([]); // [] | |
cartesianProduct([], [], []); // [] | |
cartesianProduct([8]); // [[8]] | |
cartesianProduct([], 42); // error: arguments must be arrays |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment