Skip to content

Instantly share code, notes, and snippets.

@wolever
Created February 6, 2010 00:13
Show Gist options
  • Save wolever/296418 to your computer and use it in GitHub Desktop.
Save wolever/296418 to your computer and use it in GitHub Desktop.
/**
* 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