Last active
October 10, 2015 12:47
-
-
Save ChrisTM/3691819 to your computer and use it in GitHub Desktop.
N-Ary/Multiple-List Cartesian Product
This file contains hidden or 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
/* N-ary cartesian product. | |
* Input: any number of lists | |
* Output: the cartesian product of the above lists as list of lists | |
* Example: cartesianProduct([1, 2], ['cat']) -> [ [1, 'cat'], [2, 'cat'] ] | |
*/ | |
var cartesianProduct = function () { | |
function addNextList (tuples, list) { | |
var result = []; | |
tuples.forEach(function (tuple) { | |
list.forEach(function (item) { | |
result.push(tuple.concat(item)); | |
}); | |
}); | |
return result; | |
} | |
var lists = Array.prototype.slice.call(arguments, 0); | |
return lists.reduce(addNextList, [[]]); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment