Skip to content

Instantly share code, notes, and snippets.

@zheplusplus
Created October 24, 2013 03:34
Show Gist options
  • Save zheplusplus/7130887 to your computer and use it in GitHub Desktop.
Save zheplusplus/7130887 to your computer and use it in GitHub Desktop.
Cartesian product
function cartesianProduct(sets) {
return sets.reduce(function(items, nextSequence) {
return nextSequence.map(function(element) {
return items.map(function(item) {
var copyItem = item.slice(0);
copyItem.push(element);
return copyItem;
});
}).reduce(function(sum, current) {
return sum.concat(current);
});
}, [[]]);
}
/* since javascript doesn't have set, pass a list of lists instead. */
console.log(cartesianProduct([['a', 'b'], [1, 2, 3], ['x']]));
/*
[ [ 'a', 1, 'x' ],
[ 'b', 1, 'x' ],
[ 'a', 2, 'x' ],
[ 'b', 2, 'x' ],
[ 'a', 3, 'x' ],
[ 'b', 3, 'x' ] ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment