Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
/**
* Return the cartesian product of ...iterables.
* cartesian_product([1, 2]) => [ [1], [2] ]
* cartesian_product([1, 2], ["a", "b"]) => [ [1, "a"], [1, "b"], ... ]
*/
public function cartesian_product(...iterables):Array {
if (iterables.length == 1) {
return map(function (item:*):Array {
return [item];
}, iterables[0]);
}
var result:Array = [];
var rest:Array;
rest = cartesian_product.apply(null, iterables.slice(1, iterables.length));
for each (var item:* in iterables[0]) {
for each (var sub_product:Array in rest) {
result.push([item].concat(sub_product));
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment