Last active
December 17, 2020 07:21
-
-
Save hu9o/f4e80ed4b036fd76c31ef33dc5b32601 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 // error: arguments must be arrays |
landon9720
commented
Oct 5, 2017
Array.prototype.cartesianProduct = function(other) {
return this.reduce((acc, a) => [...acc, ...other.map(b => [a, b])], []);
};
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment