Skip to content

Instantly share code, notes, and snippets.

@ramn
Created July 13, 2012 08:22
Show Gist options
  • Save ramn/3103615 to your computer and use it in GitHub Desktop.
Save ramn/3103615 to your computer and use it in GitHub Desktop.
Produce cartesian product of a list of lists (javascript)
// Lives at: https://gist.github.com/3103615/
function cartesianProduct(xss) {
if (!xss || xss.length < 1)
return [];
else {
var head = xss[0];
var tail = xss.slice(1);
var result = [];
for (var i = 0; i < head.length; i++) {
var productOfTail = cartesianProduct(tail);
if (productOfTail && productOfTail.length > 0) {
for (var j = 0; j < productOfTail.length; j++) {
result.push([head[i]].concat(productOfTail[j]));
}
}
else
result.push([head[i]]);
}
return result;
}
}
/*
* Example use
var result = cartesianProduct([
['a', 'b'],
['1', '2', '3'],
[{'a':0}, {'a': 1}],
[{'b': 50}, {'b': 100}]
]);
console.log("Answer:");
console.log(result);
for (x in result) console.log(result[x]);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment