Created
April 13, 2012 18:57
-
-
Save hakre/2379191 to your computer and use it in GitHub Desktop.
Curry Pairs
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
<?php | |
/** | |
* curry-pairs.php | |
* | |
* @link http://stackoverflow.com/questions/10144996/permutations-of-values-in-array | |
*/ | |
/** | |
* @param array $a | |
* @param array $b | |
*/ | |
$funky = function($a, $b) | |
{ | |
printf("(%s) and (%s)\n", implode(',', $a), implode(',', $b)); | |
}; | |
/** | |
* paired function of $function | |
* | |
* @param callback $function | |
* @return Closure | |
*/ | |
$paired = function($function) | |
{ | |
return function(array $array) use ($function) | |
{ | |
$stack[] = array(array(), $array); | |
while (list($left, $right) = array_pop($stack)) { | |
$min = end($left); | |
foreach ($right as $value) | |
{ | |
if ($value < $min) continue; | |
$left2 = array_merge($left, array($value)); | |
$right2 = array_diff($right, $left2); | |
if (!($left2 && $count = count($right2))) continue; | |
$function($left2, $right2); | |
--$count && $stack[] = array($left2, $right2); | |
} | |
} | |
}; | |
}; | |
$funkyAll = $paired($funky); | |
$funkyAll(range(1, 5)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment