Created
October 24, 2013 03:34
-
-
Save zheplusplus/7130887 to your computer and use it in GitHub Desktop.
Cartesian product
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
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