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