Skip to content

Instantly share code, notes, and snippets.

@cds-amal
Forked from hu9o/cartesian_product.js
Created September 2, 2017 16:43
Show Gist options
  • Save cds-amal/931a8c0f1687a12ba60060fce04a1ef3 to your computer and use it in GitHub Desktop.
Save cds-amal/931a8c0f1687a12ba60060fce04a1ef3 to your computer and use it in GitHub Desktop.
// 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment