Skip to content

Instantly share code, notes, and snippets.

@matgargano
Created August 27, 2015 01:58
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 matgargano/90780ba5617be1848430 to your computer and use it in GitHub Desktop.
Save matgargano/90780ba5617be1848430 to your computer and use it in GitHub Desktop.
permutations.php
<?php
function get_permutations( array $values ) {
$n = count($values);
$rec = function ( array $values, &$ret, $n, array $cur = array() ) use ( &$rec ) {
if ( $n > 0 ) {
foreach ( $values as $v ) {
$newCur = $cur;
if ( ! in_array( $v, $newCur ) ) {
$newCur[] = $v;
}
$rec( $values, $ret, $n - 1, $newCur );
}
} else {
$ret[] = $cur;
}
};
$ret = array();
$rec( $values, $ret, $n );
return array_unique( $ret, SORT_REGULAR );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment