Skip to content

Instantly share code, notes, and snippets.

@hakre
Created April 13, 2012 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hakre/2379191 to your computer and use it in GitHub Desktop.
Save hakre/2379191 to your computer and use it in GitHub Desktop.
Curry Pairs
<?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